contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
13
C
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1
[ "dp", "sortings" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll N = 1e9 + 7; ll bpow(ll a, ll b, ll m) { a %= m; ll res = 1; while (b > 0) { if (b & 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } ll modinv(ll n, ll p) { return bpow(n, p - 2, p); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin>>n; ll a[n],b[n]; for(int i=0;i<n;i++) { cin>>a[i]; b[i]=a[i]; } sort(b,b+n); vector<ll>dp(n); for(int i=0;i<n;i++) { if(i==0) { dp[i]=abs(a[0]-b[i]); } else dp[i]=min(dp[i-1],abs(a[0]-b[i])); } for(int i=1;i<n;i++) { vector<ll>temp(n); for(int j=0;j<n;j++) { if(j==0) { temp[j]=dp[j]+abs(a[i]-b[j]); continue; } temp[j]=min(temp[j-1],dp[j]+abs(a[i]-b[j])); } dp=temp; } cout<<dp[n-1]; return 0; }
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> using namespace std; vector<vector<int>> grafo; vector<vector<int>> grafoOr; vector<int> dis; int inf = 2147483640; void start(int n){ for(int i = 0; i<n;i++){ grafo.push_back({}); grafoOr.push_back({}); dis.push_back(inf); } } void conect(int a, int b){ grafo[b].push_back(a); grafoOr[a].push_back(b); } pair<int,int> count(vector<int> caminoP){ int min=0, max=0, i=0; int nodAc = caminoP[i]; int nodSg = caminoP[i+1]; int disAc; int disSg; while (nodSg!=caminoP[caminoP.size()-1]) { disAc = dis[nodAc]; disSg = dis[nodSg]; if(disAc<=disSg){ min++; max++; } else { int vecMin=-1; bool igual = false; for(int vec : grafoOr[nodAc]) { vecMin = (vecMin == -1 ? dis[vec] : std::min(vecMin, dis[vec])); if(dis[vec] == disSg && nodSg != vec) igual=true; } if(vecMin < disSg){ min++; max++; } else if(igual){ max++; } } i++; nodAc=nodSg; nodSg=caminoP[i+1]; } return make_pair(min,max); } void dijkstra(int nodo){ dis[nodo] = 0; priority_queue< pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> next; next.push(make_pair(0,nodo)); while(!next.empty()){ int act = next.top().second; int actDis = next.top().first; next.pop(); if(actDis <= dis[act]){ for(int i = 0;i<grafo[act].size();i++){ int ves = grafo[act][i]; int vesDis = 1; if(dis[ves] > dis[act] + 1){ dis[ves] = dis[act]+1; next.push(make_pair(dis[ves],ves)); } } } } } int main(){ int n,m; cin >> n >> m; start(n); int u,v; for(int i = 0; i<m; i++){ cin >> u >> v; conect(u-1,v-1); } int k; cin >> k; int t; vector<int> caminoP; for(int i =0; i<k; i++){ cin >> t; caminoP.push_back(t-1); } dijkstra(caminoP[caminoP.size()-1]); pair<int,int> res =count(caminoP); cout << res.first << ' ' << res.second << '\n'; return 0; }
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 998244353; const int mm = 1e5 + 10; int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); ll x; cin>>x; pair<ll,ll>ans={1,x}; vector<ll>v; for(int i=2;i<=x/i;i++){ if(x%i==0){ ll js=1; while(x%i==0){ x/=i; js*=i; } v.push_back(js); } }if(x>1)v.push_back(x); for(ll i=1;i<=(1ll<<v.size())-1;i++){ ll bj=i; vector<int>zy; while(bj||zy.size()<v.size()){ zy.push_back(bj%2); bj/=2; } ll bjl=1,bjr=1; for(int j=0;j<v.size();j++){ if(zy[j])bjl*=v[j]; else bjr*=v[j]; } if(max(bjl,bjr)<max(ans.first,ans.second)){ ans={bjl,bjr}; } } ll xx=ans.first,yy=ans.second; cout<<min(xx,yy)<<' '<<max(xx,yy)<<'\n'; }
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> // v.erase( unique(all(v)) , v.end() ) -----> removes duplicates and resizes the vector as so using namespace std; #define ll long long #define lld long double const lld pi = 3.14159265358979323846; #define pb push_back #define pf push_front #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());} constexpr int mod = (int)(1e9+7); #define log(x) (31^__builtin_clz(x)) // Easily calculate log2 on GNU G++ compilers #define left p<<1 , l , (l+r)>>1 #define right p<<1|1 , ((l+r)>>1)+1 , r const int N=4e4+7; const int M=53; int seg[M][4*N],lazy[M][4*N]; void push(int t,int p){ if(!lazy[t][p]) return; seg[t][p<<1] += lazy[t][p]; seg[t][p<<1|1] += lazy[t][p]; lazy[t][p<<1] += lazy[t][p]; lazy[t][p<<1|1] +=lazy[t][p]; lazy[t][p] = 0; } void upd(int t,int i , int j , int inc , int p , int l , int r){ if(j<l || r<i) return; if(i<=l && r<=j){ lazy[t][p] += inc; seg[t][p] += inc; return; } push(t,p); upd(t,i,j,inc,left); upd(t,i,j,inc,right); seg[t][p]=max(seg[t][p<<1],seg[t][p<<1|1]); } int a[M][N]; int main() {ios_base::sync_with_stdio(0),cin.tie(0); int n,m;cin>>n>>m;int k;cin>>k; for(int i=0;i<n;i++){ for(int j=1;j<=m;j++){ cin>>a[i][j];a[i][j]+=a[i][j-1]; } } if(n==1){ int ans=0; for(int i=k;i<=m;i++)ans=max(ans,a[0][i]-a[0][i-k]); cout<<ans<<'\n';return 0; } for(int i=1;i<=m;i++){ int sum=a[1][i]-a[1][max(i-k,0)]+a[0][i]-a[0][max(i-k,0)]; upd(1,i,i,sum,1,1,2*m); } for(int c=2;c<=n;c++){ for(int i=1;i<=m;i++){ int sum=a[c][i]-a[c][max(i-k,0)]+a[c-1][i]-a[c-1][max(i-k,0)]; int minus=a[c-1][i]-a[c-1][i-1]; upd(c-1,i,i+k-1,-minus,1,1,2*m); upd(c,i,i,sum+seg[c-1][1],1,1,2*m); if(i>=k)upd(c-1,i-k+1,i,(a[c-1][i-k+1]-a[c-1][i-k]),1,1,2*m); } } cout<<seg[n][1]<<'\n'; return 0; } /* */
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; const int MN=8e4; int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN]; set<int> start; vector<int> prime, vals, adj[MN]; unordered_map<int, int> ind; // (value, index it maps to) 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 || i>j) if(adj[i].size()>1) { 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; } } } 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.push_back(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.push_back(prime[j]); } if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; } vals.push_back(x); if (vals.size() == 1) vals.push_back(1); for (int k: vals) if (ind.count(k) == 0) { if (k > 1e3) ind[k] = at++; else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin(); ind[k]=t; start.insert(t); } } adj[ind[vals[0]]].push_back(ind[vals[1]]); adj[ind[vals[1]]].push_back(ind[vals[0]]); } for (int j: start) if(adj[j].size()>1) bfs(j); cout << (ans == MN ? -1 : ans) <<'\n'; }
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 <iostream> using namespace std; int main() { int n; cin >> n; for(int i = 0; i < n; i++) { string a, b, c; cin >> a >> b >> c; int check = 0; for(int i = 0; i < int(a.size()); i++) { if(c[i] != a[i] && c[i] != b[i]) { check = 1; break; } } if(check) cout << "NO" << endl; else cout << "YES" << endl; } }
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" ]
// LUOGU_RID: 99372543 #include<bits/stdc++.h> using namespace std; string s; multiset<string> st; string ss[110]; vector<string> v[110]; char ans[1000]; bool cmp(string s1,string s2) { return s1.size()<s2.size(); } int a[1100]; int n; void branch() { int n1=n; n=(n+1)/2; cout<<"? "<<1<<' '<<n<<'\n'; fflush(stdout); for (int i=0;i<n*(n+1)/2;i++) { cin>>s; sort(s.begin(),s.end()); st.insert(s); } cout<<"? "<<2<<' '<<n<<'\n'; fflush(stdout); for (int i=0;i<n*(n-1)/2;i++) { cin>>s; sort(s.begin(),s.end()); st.erase(st.find(s)); } int cnt=0; for (auto p:st) { ss[cnt++]=p; } sort(ss,ss+cnt,cmp); ans[0]=ss[0][0]; for (int i=1;i<cnt;i++) { for (auto p:ss[i-1]) a[p]--; for (auto p:ss[i]) a[p]++; for (int j=0;j<255;j++) if (a[j]>0) { a[j]=0; ans[i]=j; } } cout<<"? "<<1<<' '<<n1<<'\n'; for (int i=0;i<n1*(n1+1)/2;i++) { cin>>s; v[s.size()].push_back(s); } for (int i=n1-1;i>=n;i--) { for (int j='a';j<='z';j++) a[j]=0; for (auto p:v[i]) for (auto q:p) a[q]++; for (int j=0;j<(n1-i);j++) a[ans[j]]-=(j+1); for (int j=n1-1;j>i;j--) a[ans[j]]-=n1-j; for (int j='a';j<='z';j++) if (a[j]%(n1+1-i)!=0) ans[i]=j; } cout<<"! "; for (int i=0;i<n1;i++) cout<<ans[i]; fflush(stdout); exit(0); } int main() { cin>>n; if (n==1) { cout<<"? "<<1<<' '<<1<<'\n'; char c; cin>>c; cout<<"! "<<c; fflush(stdout); return 0; } if (n>=6) branch(); cout<<"? "<<1<<' '<<n<<'\n'; fflush(stdout); for (int i=0;i<n*(n+1)/2;i++) { cin>>s; sort(s.begin(),s.end()); st.insert(s); } cout<<"? "<<2<<' '<<n<<'\n'; for (int i=0;i<n*(n-1)/2;i++) { cin>>s; sort(s.begin(),s.end()); st.erase(st.find(s)); } int cnt=0; for (auto p:st) { ss[cnt++]=p; } sort(ss,ss+cnt,cmp); ans[0]=ss[0][0]; for (int i=1;i<cnt;i++) { for (auto p:ss[i-1]) a[p]--; for (auto p:ss[i]) a[p]++; for (int j=0;j<255;j++) if (a[j]>0) { a[j]=0; ans[i]=j; } } cout<<"! "<<ans; return 0; }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f3f3f3f3f int main() { int64_t x0, y0, ax, ay, bx, by, xs, ys, t; cin >> x0 >> y0 >> ax >> ay >> bx >> by; cin >> xs >> ys >> t; vector<int64_t> x(1, x0), y(1, y0); while ((INF - bx) / ax >= x.back() && (INF - by) / ay >= y.back()) { x.push_back(ax * x.back() + bx); y.push_back(ay * y.back() + by); } int n = x.size(); int ans = 0; for (int i=0; i<n; i++) { for (int j=i; j<n; j++) { int64_t length = x[j] - x[i] + y[j] - y[i]; int64_t d2l = abs(xs - x[i]) + abs(ys - y[i]); int64_t d2r = abs(xs - x[j]) + abs(ys - y[j]); if (length <= t - min(d2l, d2r)) ans = max(ans, j-i+1); } } cout << ans << endl; }
cpp
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ld long double #define int long long #define uint unsigned long long #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() const int N = 2e5; const int INF = 1e18; const int mod = 1e9 + 7; const ld EPS = 1e-6; random_device rn; mt19937 rnd(rn()); struct SegmentTreeMass { struct Node { int sum = INF; int add = 0; Node(int Sum = INF, int Add = 0) { sum = Sum; add = Add; } }; Node neutral = Node(); int n; vector<Node> tree; SegmentTreeMass(vector<int>& start) { n = start.size(); tree.resize(4 * n + 228); init(start); } SegmentTreeMass(int N) { n = N; tree.resize(4 * n + 228); vector<int> start(n, 0); init(start); } Node merge(Node n1, Node n2) { return Node(min(n1.sum, n2.sum)); } void fix(int v, int l, int r) { tree[v] = merge(tree[v * 2 + 1], tree[v * 2 + 2]); } void apply(int v, int l, int r, int val) { tree[v].add += val; tree[v].sum += val; } void init(int v, int l, int r, vector<int>& start) { if (l + 1 == r) { tree[v] = Node(start[l], 0); return; } int m = (r + l) / 2; init(v * 2 + 1, l, m, start); init(v * 2 + 2, m, r, start); fix(v, l, r); } void init(vector<int>& start) { init(0, 0, n, start); } void push(int v, int l, int r) { int m = (r + l) / 2; apply(v * 2 + 1, l, m, tree[v].add); apply(v * 2 + 2, m, r, tree[v].add); tree[v].add = 0; } // [l: r) Node query(int v, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) { return tree[v]; } if (r <= ql || qr <= l) { return neutral; } int m = (r + l) / 2; push(v, l, r); return merge( query(v * 2 + 1, l, m, ql, qr), query(v * 2 + 2, m, r, ql, qr)); } Node query(int ql, int qr) { return query(0, 0, n, ql, qr); } void add(int v, int l, int r, int ql, int qr, int val) { if (ql <= l && r <= qr) { apply(v, l, r, val); return; } if (r <= ql || qr <= l) { return; } int m = (r + l) / 2; push(v, l, r); add(v * 2 + 1, l, m, ql, qr, val); add(v * 2 + 2, m, r, ql, qr, val); fix(v, l, r); } void add(int ql, int qr, int val) { add(0, 0, n, ql, qr, val); } }; int n; vector<int> t; // возвращает сумму на префиксе int sum (int r) { int res = 0; for (; r > 0; r -= r & -r) res += t[r]; return res; } int sum (int l, int r) { return sum(r) - sum(l-1); } // обновляет нужные t void add (int k, int x) { for (; k <= n; k += k & -k) t[k] += x; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; t.assign(n + 1,0); vector<int> p(n), a(n); vector<int> num(n +1); for (int i = 0; i < n; ++i) { cin >> p[i]; num[p[i]] = i; } for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<int> prefs(n + 2); for (int i = 1; i <= n; ++i) { prefs[i + 1] = prefs[i] + a[num[i]]; } int ans = INF; vector<int> ini(n + 1, INF); SegmentTreeMass tree(ini); int cur = 0; for (int i = 0; i < n - 1; ++i) { int x = prefs[p[i]] - sum(1, p[i]) + sum(p[i], n); cur += a[num[p[i]]]; tree.add(1, p[i], a[num[p[i]]]); tree.add(p[i] + 1, n + 1, -a[num[p[i]]]); tree.add(p[i],p[i] + 1, -tree.query(p[i],p[i] + 1).sum + x); add(p[i], a[num[p[i]]]); if (i + 1 != n) { ans = min(ans, cur); } ans = min(ans,tree.query(1, n + 1).sum); } cout << ans << endl; }
cpp
1290
F
F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3 -1 0 1 1 0 -1 OutputCopy3 InputCopy3 3 -1 0 2 2 0 -1 OutputCopy1 InputCopy3 1776966 -1 0 3 3 0 -2 OutputCopy296161 InputCopy4 15 -4 -4 -1 1 -1 -4 4 3 OutputCopy1 InputCopy5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 OutputCopy0 InputCopy5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 OutputCopy9248783 NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is:
[ "dp" ]
#include<bits/stdc++.h> using namespace std; const int N=6,V=5,L=31,mod=998244353; int f[L][N*V][N*V][N*V][N*V][2][2]; int x[N],y[N]; int n,m; int calc(int p,int px,int nx,int py,int ny,int gx,int gy){ if(p==L-1)return (!px&&!nx&&!py&&!ny&&!gx&&!gy); int &f=::f[p][px][nx][py][ny][gx][gy]; if(f!=-1)return f; f=0; int w=(m>>p)&1; for(int i=0;i<1<<n;i++){ int pxx=px,nxx=nx,pyy=py,nyy=ny; for(int j=0;j<n;j++)if((i>>j)&1){ (x[j]<0?nxx:pxx)+=abs(x[j]); (y[j]<0?nyy:pyy)+=abs(y[j]); } int pxxx=pxx&1,nxxx=nxx&1,pyyy=pyy&1,nyyy=nyy&1; if(pxxx!=nxxx||pyyy!=nyyy)continue; f=(f+calc(p+1,pxx>>1,nxx>>1,pyy>>1,nyy>>1,w==pxxx?gx:pxxx>w,w==pyyy?gy:pyyy>w))%mod; } return f; } int main(){ cin>>n>>m; for(int i=0;i<n;i++)cin>>x[i]>>y[i]; memset(f,-1,sizeof(f)); cout<<(calc(0,0,0,0,0,0,0)+mod-1)%mod<<endl; }
cpp
1310
D
D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8 0 1 2 2 0 0 0 1 1 2 0 1 0 0 0 2 1 1 0 0 2 0 1 2 0 OutputCopy2 InputCopy3 2 0 1 1 2 0 1 2 2 0 OutputCopy3
[ "dp", "graphs", "probabilities" ]
//Author: Frustrated_EH //Complexity: O(?) #include <bits/stdc++.h> //#define int long long using namespace std; const int mod = 998244353; namespace FastIO { template<typename T>inline T read(){T x=0,w=1;char c=0;while(c<'0'||c>'9'){if(c=='-')w=-1;c=getchar();}while(c>='0'&&c<='9'){x=x*10+(c-'0');c=getchar();}return x*w;} template<typename T>inline void write(T x){if(x<0){x=-x;putchar('-');}if(x>9)write(x/10);putchar(x%10+'0');} inline int getInt(){return read<int>();} inline int putInt(int x,char c){write<int>(x),putchar(c);return 0;} } namespace Number_Theory { int pw(int a,int b,int p=mod){int res=1;while(b){if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;} int gcd(int x,int y){return!y?x:gcd(y,x%y);} void exgcd(int a,int b,int&x,int&y){if(!b){x=1,y=0;return;}exgcd(b,a%b,y,x);y-=(a/b*x);} int inv(int x,int p=mod){exgcd(x,p,x,*new int);return(x%p+p)%p;} int bsgs(int a,int b,int p){map<int,int>val;int A=1,t=sqrt(p)+1;for(int i=0;i<t;i++){val[A*b%p]=i;A=A*a%p;}for(int i=1,_a=A;i<=t;i++){if(val[_a]&&val[_a]!=-1){int ans=i*t-val[_a];for(int i=0,A=1;i<t;i++){val[A*b%p]=-1;A=A*a%p;}return ans;}_a=_a*A%p;}return-1;} } using namespace FastIO; using namespace Number_Theory; const int N = 85; int e[N][N], f[N], t[N]; int Solve() { srand(time(0)); int n = getInt(), k = getInt(); int res = mod; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) e[i][j] = getInt(); for(int T = 1; T <= 5000; T++) { for(int j = 2; j <= n; j++) f[j] = mod, t[j] = rand() & 1; for(int i = 1; i <= k; i++) for(int j = 1; j <= n; j++) if((i & 1) == t[j]) { f[j] = mod; for(int k = 1; k <= n; k++) if((i & 1) != t[k]) f[j] = min(f[j], f[k] + e[k][j]); } res = min(res, f[1]); f[1] = 0; } putInt(res, '\n'); return 0; } signed main() { int T = 1; // T = getInt(); while(T--) Solve(); 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; #define int long long #define mp make_pair #define inf 1e9 #define pii pair <int, int> const int mod = 998244353; inline int read () { int x = 0, f = 1; char ch = getchar (); while (ch < '0' || ch > '9') f = ((ch == '-') ? -1 : f), ch = getchar (); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar (); return x * f; } inline void write (int x) { if (x < 0) x = -x, putchar ('-'); if (x >= 10) write (x / 10); putchar (x % 10 + '0'); } inline int quickmod (int x, int y) { int Ans = 1; while (y) { if (y & 1) Ans = (1ll * Ans * x) % mod; x = (1ll * x * x) % mod; y >>= 1; } return Ans; } inline void Add(int &x, int y) { x += y; if(x >= mod) x -= mod; } int n, all = 1; struct st { int l, r; }a[505]; vector <int> G; int f[505][505], sp[505], invsp[505]; inline int C(int x, int y) { if(x < y || y < 0) return 0; int ans1 = 1, ans2 = 1; for(int i = x - y + 1; i <= x; i++) ans1 = ans1 * i % mod; for(int i = 1; i <= y; i++) ans2 = ans2 * i % mod; return ans1 * quickmod(ans2, mod - 2) % mod; } signed main () { // freopen (".in", "r", stdin); // freopen (".out", "w", stdout); n = read(); for(int i = 1; i <= n; i++) { a[i].l = read(), a[i].r = read(); swap(a[i].l, a[i].r); a[i].l = mod - 2 - a[i].l, a[i].r = mod - 2 - a[i].r; G.push_back(a[i].l), G.push_back(a[i].r + 1); all = all * (a[i].r - a[i].l + 1) % mod; } // sp[0] = invsp[0] = 1; // for(int i = 1; i <= n; i++) sp[i] = sp[i-1] * quickmod(a[i].r - a[i].l + 1, mod - 2) % mod, invsp[i] = invsp[i-1] * (a[i].r - a[i].l + 1) % mod; sort(G.begin(), G.end()); G.erase(unique(G.begin(), G.end()), G.end()); int N = (int)G.size(); G.push_back(G.back() + 1); for(int i = 1; i <= n; i++) { a[i].l = lower_bound(G.begin(), G.end(), a[i].l) - G.begin() + 1; a[i].r = lower_bound(G.begin(), G.end(), a[i].r + 1) - G.begin() + 1; // printf("{%lld %lld %lld}\n", a[i].l, a[i].r, G[1] - G[0]); } f[0][0] = 1; for(int i = 1; i <= n; i++) { for(int j = a[i].l; j < a[i].r; j++) { for(int k = i - 1; k >= 0; k--) {//[k + 1, i] if(j < a[k+1].l || j >= a[k+1].r) break; int s = 0; for(int j2 = 0; j2 < j; j2++) Add(s, f[k][j2]); // if(!(j2 == 0 && j == 1 && k == 0)) continue; int len = i - k; Add(f[i][j], s * C(G[j] - G[j-1] + len - 1, len) % mod); } } } int Ans = 0; for(int i = 1; i <= N; i++) Add(Ans, f[n][i]); write(Ans * quickmod(all, mod - 2) % mod), putchar('\n'); 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; #define watch(x) cout << __LINE__ << "| " << #x << " = " << x << endl #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define YES cout << "YES\n" #define NO cout << "NO\n" void solve() { int x, y; cin >> x >> y; if (x == y) { cout << "0\n"; return; } if ((x ^ y) & 1) { cout << 1 + (x > y) << "\n"; return; } cout << 1 + (x < y) << "\n"; } int main(int argc, char *argv[]) { // ios_base::sync_with_stdio(false), cin.tie(nullptr); int t; cin >> t; while (t--) { solve(); } }
cpp
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5 4 8 2 6 2 4 5 4 1 3 OutputCopy7 InputCopy4 1 3 2 4 1 3 2 4 OutputCopy0
[ "binary search", "data structures", "sortings", "two pointers" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ull = unsigned long long; using uint = unsigned int; using vi = vector<int>; using pi = pair<int, int>; #define FAST_IO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) bool is_prime(ll x) { if (x <= 1) return 0; for (ll y = 2; y * y <= x; ++y) if (x % y == 0) return 0; return 1; } using std::gcd; // Computes the greatest common divisor of the integers m and // n. using std::lcm; // Computes the least common multiple of the integers m and n. int popcnt(uint x) { return __builtin_popcount(x); } int popcnt(int x) { return __builtin_popcount(x); } int popcnt(ull x) { return __builtin_popcountll(x); } int popcnt(ll x) { return __builtin_popcountll(x); } int bsr(uint x) { return 31 - __builtin_clz(x); } int bsr(ull x) { return 63 - __builtin_clzll(x); } int ctz(int x) { return __builtin_ctz(x); } int ctz(ll x) { return __builtin_ctzll(x); } int ctz(ull x) { return __builtin_ctzll(x); } template <class T> using vc = vector<T>; template <class T> using vvc = vector<vc<T>>; template <class T> using vvvc = vector<vvc<T>>; template <class T> using vvvvc = vector<vvvc<T>>; template <class T> using vvvvvc = vector<vvvvc<T>>; template <class T> using pq = priority_queue<T>; template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>; #define all(x) x.begin(), x.end() #define len(x) ll(x.size()) #define SUM(v) accumulate(all(v), 0LL) #define MIN(v) *min_element(all(v)) #define MAX(v) *max_element(all(v)) #define LB(c, x) distance((c).begin(), lower_bound(all(c), (x))) #define UB(c, x) distance((c).begin(), upper_bound(all(c), (x))) #define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end()) ll ceil(ll x, ll y) { assert(y >= 1); return (x > 0 ? (x + y - 1) / y : x / y); } ll floor(ll x, ll y) { assert(y >= 1); return (x > 0 ? x / y : (x - y + 1) / y); } ll mod(ll x, ll y) { return x - y * floor(x, y); } struct UnionFind { int n; int n_comp; std::vector<int> size, par; UnionFind(int n) : n(n), n_comp(n), size(n, 1), par(n) { std::iota(par.begin(), par.end(), 0); } int find(int x) { assert(0 <= x && x < n); while (par[x] != x) { x = par[x] = par[par[x]]; } return x; } int operator[](int x) { return find(x); } bool merge(int x, int y) { x = find(x); y = find(y); if (x == y) { return false; } n_comp--; if (size[x] < size[y]) std::swap(x, y); size[x] += size[y]; size[y] = 0; par[y] = x; return true; } std::vector<int> find_all() { std::vector<int> A(n); for (int i = 0; i < n; ++i) A[i] = find(i); return A; } void reset() { n_comp = n; size.assign(n, 1); std::iota(par.begin(), par.end(), 0); } }; template <typename T> std::istream& operator>>(std::istream& is, vc<T>& a) { for (auto& e : a) is >> e; return is; } /**************************** debug utils begin *******************************/ #ifdef OJ_DEBUG #define LOG std::cerr << "line: " << __LINE__ << ", " #else struct NonFunctioningLogger { public: template <typename T> NonFunctioningLogger& operator<<(const T& obj) { return *this; } }; NonFunctioningLogger LOG; #endif // OJ_DEBUG #define DEFINE_CONTAINER_PRINTER(CONTAINER_TYPE) \ template <typename T> \ ostream& operator<<(ostream& ostr, const CONTAINER_TYPE<T>& a) { \ ostr << "{"; \ for (auto it = a.begin(); it != a.end(); it++) { \ if (it != a.begin()) ostr << ", "; \ ostr << *it; \ } \ ostr << "}"; \ return ostr; \ } DEFINE_CONTAINER_PRINTER(std::vector) DEFINE_CONTAINER_PRINTER(std::deque) DEFINE_CONTAINER_PRINTER(std::list) DEFINE_CONTAINER_PRINTER(std::set) DEFINE_CONTAINER_PRINTER(std::unordered_set) template <typename T, typename U> ostream& operator<<(ostream& os, const pair<T, U>& A) { os << "(" << A.first << ", " << A.second << ")"; return os; } template <typename T, typename Y> auto operator<<(std::ostream& os, const std::vector<std::pair<T, Y>>& a) -> std::ostream& { os << "{"; int i; for (i = 0; i < a.size() - 1; i++) { os << "(" << a[i].first << ", " << a[i].second << "), "; } if (i < a.size()) { os << a[i]; } os << "}"; return os; } template <class T, class S> inline bool chmin(T& a, const S& b) { return (a > b ? a = b, 1 : 0); } /**************************** debug utils end *******************************/ int main() { FAST_IO; int n; cin >> n; vc<ll> a(n); vc<ll> b(n); cin >> a >> b; for (int i = 0; i < n; i++) { a[i] -= b[i]; } sort(all(a)); ll cnt{0}; for (int i = 0; i < n - 1; i++) { if (a[i] <= 0) { cnt += distance(lower_bound(a.begin() + i + 1, a.end(), 1LL - a[i]), a.end()); } else { cnt += (n - 1 - i); } } cout << cnt << "\n"; return 0; }
cpp
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
#include<stdio.h> int n,a[400002],f[400002],c[1<<26],ans; int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int k=0;k<25;k++) { long long sum1=0,sum2=0; if(k>0) { for(int i=0;i<(1<<k);i++) c[i]=0; for(int i=1;i<=n;i++) c[a[i]&((1<<k)-1)]++; for(int i=(1<<k)-1;i;i--) c[i]+=c[i+1]; for(int i=1;i<=n;i++) sum1+=c[(1<<k)-(a[i]&((1<<k)-1))]-((a[i]>>(k-1))&1); } int t[2]={0}; for(int i=1;i<=n;i++) t[(a[i]>>k)&1]++; sum2=(long long)t[0]*t[1]; ans|=((sum1/2+sum2)&1)?(1<<k):0; } printf("%d",ans); 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 <bits/stdc++.h> using namespace std; using ll = long long; const int N = 18; ll n, ans, a[1 << N], cnt[1 << N]; struct dsu { vector < int > link, rang; dsu(int sz) { link.resize(sz + 1); rang.resize(sz + 1, 1); for (int i = 0; i <= sz; i++) link[i] = i; } int get(int v) { return (v == link[v] ? v : link[v] = get(link[v])); } int unite(int v, int u) { int lv = v, lu = u; v = get(v); u = get(u); if (v == u) return 0; if (rang[v] > rang[u]) swap(v, u); link[v] = u; rang[u] += v; cnt[lv] = cnt[lu] = 1; return 1; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; cnt[0] = 1; for (int i = 1; i <= n; i++) { cin >> a[i]; ans -= a[i]; cnt[a[i]]++; } dsu G(1 << N); for (int i = (1 << N) - 1; i >= 0; i--) { int j = i; do { if (cnt[j] && cnt[i ^ j]) ans += (cnt[j] + cnt[i ^ j] - 1) * (ll)i * G.unite(j, i ^ j); j = (j - 1) & i; } while (j); } cout << ans; }
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" ]
#include<stdio.h> int d[1000002],h[1000002][2],n,v=0,s; int main(){ scanf("%d",&n);s=n-1; for(int i=1;i<n;i++){ scanf("%d%d",&h[i][0],&h[i][1]); d[h[i][0]]++;d[h[i][1]]++; }for(int i=1;i<n;i++){ if(d[h[i][0]]==1||d[h[i][1]]==1)printf("%d\n",v++); else printf("%d\n",--s); } }
cpp
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
#include <bits/stdc++.h> #define int long long int #define endl "\n" #define pb push_back #define pf push_front #define ff first #define ss second #define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(__null); #define cnt1(x) __builtin_popcountll(x) using namespace std; const int mod = 1e9 + 7; const int N = 1e15; signed main() { fastio() int t; cin >> t; while(t--) { int n,x; cin >> n >> x; string s; cin >> s; vector<int> f0(n,0),f1(n,0); s[0] == '1' ? f1[0] = 1 : f0[0] = 1; for(int i=1;i<n;i++) f0[i]=f0[i-1]+(s[i]=='0'?1:0), f1[i]=f1[i-1]+(s[i]=='1'?1:0); int ans = (x==0 ? 1 : 0); for(int i=0;i<n;i++) { if(x==f0[i]-f1[i] && f0[n-1]==f1[n-1]) ans=N; else if(f0[n-1]!=f1[n-1]) { int y = (x-f0[i]+f1[i])/(f0[n-1]-f1[n-1]); if(y>=0 && y*(f0[n-1]-f1[n-1])==x-f0[i]+f1[i]) ans++; } } cout << (ans>=N ? -1 : ans) << endl; } return 0; }
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 998244353; const int mm = 1e5 + 10; int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); ll x; cin>>x; ll ans=1; for(ll i=1;i<=x/i;i++){ if(x%i==0){ if(lcm(x/i,i)==x)ans=i; } }cout<<ans<<' '<<x/ans; }
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" ]
//header files// #include <bits/stdc++.h> using namespace std; typedef long long int ll; const ll INF = 1e9 + 7; const ll MOD = 998244353; // definition files//; #define int long long #define loop(i, a, b) for(ll i = (ll)a; i <(ll) b; ++i) #define fl(i,n) loop(i, 0, n) #define rfl(i,n) for(ll i=(ll)(n)-1;i>=0;i--) #define pry cout<<"YES\n"; #define prm cout<<"-1\n"; #define prn cout<<"NO\n"; #define pb(x) push_back(x) #define nl '\n' #define inpt(v) fl(i,sz(v)) cin >> v[i]; #define prt(v) for(auto i:v) cout << i << ' '; #define sz(v) sizeof(v) #define ff first #define ss second #define each(a, x) for (auto &a : x) #define all(x) (x).begin(), (x).end() #define Vmax(x) *max_element(all(x)) #define Vmin(x) *min_element(all(x)) #define fix(prec) cout << setprecision(prec) << fixed; #define lowB(v,x) lower_bound(all(v),x)-v.begin() // >=x #define upB(v,x) upper_bound(all(v),x)-v.begin() // > x #define charToInt(c) (c - '0') //Debug void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) void _print(ll t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(double t) {cerr << t;} //Template Class// template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} //main// //IMPORTANT PROPERTIES// //REMEMBER PARANTHESES PRECEDENCE for eg x=(x^y) and not x=x^y; //Modular inverse// /*int modular_inverse(int a, int m){ for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 0; }*/ //Binary exponentiaition// /*long long binpow(long long a, long long b) { if (b == 0) return 1; long long res = binpow(a, b / 2); if (b % 2) return res * res * a; else return res * res; }*/ //-->even no. of 1s in xor cancel each other /*struct cmp { bool operator() (const pair<int, int> &a, const pair<int, int> &b) const { return a.first < b.first; } }*/ void solve(){ string s;cin>>s; int cnt[100]; int inv[100][100]; memset(cnt,0,sizeof(cnt)); memset(inv,0,sizeof(inv)); int ans=0; for(auto x:s){ for(int i=0;i<26;i++) { inv[i][x-'a']+=cnt[i]; ans=max(ans,inv[i][x-'a']); } cnt[x-'a']++; ans=max(ans,cnt[x-'a']); } cout<<ans<<nl; } signed main() { ios_base::sync_with_stdio(false);cin.tie(NULL); int t = 1; // cin >> t; while (t--) { //start her UwU// solve(); } return 0; }
cpp
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
#include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <cstring> #include <list> #include <cassert> #include <climits> #include <bitset> #include <chrono> #include <random> using namespace std; #define PB push_back #define MP make_pair #define SZ(v) ((int)(v).size()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define FORE(i,a,b) for(int i=(a);i<=(b);++i) #define REPE(i,n) FORE(i,0,n) #define FORSZ(i,a,v) FOR(i,a,SZ(v)) #define REPSZ(i,v) REP(i,SZ(v)) std::mt19937 rnd((int)std::chrono::steady_clock::now().time_since_epoch().count()); typedef long long ll; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } const int MAXN = 500000; int n; int lim[MAXN]; int ans[MAXN]; ll lsum[MAXN]; ll rsum[MAXN]; pair<int, int> stck[MAXN]; int nstck; ll stcksum; void solve() { nstck = 0, stcksum = 0; REP(i, n) { int cnt = 1; while (nstck > 0 && stck[nstck - 1].second > lim[i]) stcksum -= (ll)stck[nstck - 1].first * stck[nstck - 1].second, cnt += stck[nstck - 1].first, --nstck; stck[nstck++] = MP(cnt, lim[i]), stcksum += (ll)cnt * lim[i]; lsum[i] = stcksum; } nstck = 0, stcksum = 0; for (int i = n - 1; i >= 0; --i) { int cnt = 1; while (nstck > 0 && stck[nstck - 1].second > lim[i]) stcksum -= (ll)stck[nstck - 1].first * stck[nstck - 1].second, cnt += stck[nstck - 1].first, --nstck; stck[nstck++] = MP(cnt, lim[i]), stcksum += (ll)cnt * lim[i]; rsum[i] = stcksum; } ll best = LLONG_MIN; int bestidx = -1; REP(i, n) { ll cur = lsum[i] + rsum[i] - lim[i]; if (cur > best) best = cur, bestidx = i; } ans[bestidx] = lim[bestidx]; for (int i = bestidx - 1; i >= 0; --i) ans[i] = min(lim[i], ans[i + 1]); for (int i = bestidx + 1; i < n; ++i) ans[i] = min(lim[i], ans[i - 1]); } void run() { scanf("%d", &n); REP(i, n) scanf("%d", &lim[i]); solve(); REP(i, n) { if (i != 0) printf(" "); printf("%d", ans[i]); } puts(""); } int main() { run(); return 0; }
cpp
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
#include <bits/stdc++.h> #define maxn 300086 using namespace std; int n, k; char s[maxn]; int fa[maxn], val[maxn], siz[maxn], cnt[maxn], sum[maxn]; vector<int> a[maxn]; int x, y; int ans; int find(int x){ return x == fa[x] ? x : find(fa[x]); } int get(int x){ return x == fa[x] ? 0 : val[x] ^ get(fa[x]); } void add(int x, int i){ int val; if(sum[x] == -1) val = min(cnt[x], siz[x] - cnt[x]); else if(sum[x] == 0) val = cnt[x]; else val = siz[x] - cnt[x]; ans += i * val; } int main(){ scanf("%d%d%s", &n, &k, s + 1); for(int i = 1;i <= k;i++){ scanf("%d", &x); while(x--){ scanf("%d", &y); a[y].push_back(i); } } for(int i = 1;i <= k;i++) fa[i] = i, siz[i] = 1, sum[i] = -1; for(int i = 1;i <= n;i++){ if(a[i].size() == 2){ x = a[i][0], y = a[i][1]; int fx = find(x), fy = find(y); if(fx ^ fy){ add(fx, -1), add(fy, -1); if(siz[fx] > siz[fy]) swap(x, y), swap(fx, fy); val[fx] = get(x) ^ get(y) ^ (s[i] == '0'); fa[fx] = fy, siz[fy] += siz[fx]; cnt[fy] += val[fx] ? siz[fx] - cnt[fx] : cnt[fx]; if(sum[fx] != -1) sum[fy] = sum[fx] ^ val[fx]; add(fy, 1); } }else if(a[i].size() == 1){ x = a[i][0]; int fx = find(x); add(fx, -1); if(sum[fx] == -1) sum[fx] = get(x) ^ (s[i] == '0'); add(fx, 1); } printf("%d\n", ans); } }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <bits/stdc++.h> #define ll long long #define yes cout << "YES\n" #define no cout << "NO\n" #define pb push_back #define mod 998244353 using namespace std; mt19937 rng(time(0)); int random(int l, int r) { return rng() % (r - l + 1) + l; } int main() { int n,m; cin>>n>>m; string a[n],b[m]; for(int i=0;i<n;i++)cin>>a[i]; for(int i=0;i<m;i++)cin>>b[i]; int k; cin>>k; while(k--){ int r; cin>>r; r--; cout<<a[r%n]<<b[r%m]<<endl; } }
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" ]
// LUOGU_RID: 92552939 #include <bits/stdc++.h> #define P 998244353ll #define ll long long using namespace std; namespace QYB { void exgcd(ll a, ll b, ll &x, ll &y) { if (!b) return x = 1, y = 0, void(); exgcd(b, a % b, y, x); y -= a / b * x; } ll inv(ll a) { ll x, y; exgcd(a, P, x, y); return (x % P + P) % P; } struct matrix { ll a[2][2]; ll *operator[](int x) { return a[x]; } matrix(ll _0 = 0, ll _1 = 0, ll _2 = 0, ll _3 = 0) { a[0][0] = _0; a[0][1] = _1; a[1][0] = _2; a[1][1] = _3; } matrix operator*(matrix x) { return matrix((a[0][0] * x[0][0] + a[0][1] * x[1][0]) % P, (a[0][0] * x[0][1] + a[0][1] * x[1][1]) % P, (a[1][0] * x[0][0] + a[1][1] * x[1][0]) % P, (a[1][0] * x[0][1] + a[1][1] * x[1][1]) % P); } } s[500005]; int n; ll ans, d[100005], v[100005], g[2][100005]; void modify(int p, int l, int r, int x, int a, int b) { if (x < l || x > r) return; if (l == r) return s[p][a][b] = g[a][x], void(); int mid = l + r >> 1; modify(p << 1, l, mid, x, a, b); modify(p << 1 | 1, mid + 1, r, x, a, b); s[p] = s[p << 1 | 1] * s[p << 1]; } matrix query(int p, int l, int r, int L, int R) { if (r < L || R < l) return matrix(1, 0, 0, 1); if (L <= l && r <= R) return s[p]; int mid = l + r >> 1; return query(p << 1 | 1, mid + 1, r, L, R) * query(p << 1, l, mid, L, R); } int main() { scanf("%d", &n); vector<pair<int, int> > f; for (int i = 1; i <= n; i++) { scanf("%lld%lld%lld", d + i, v + i, &g[1][i]); g[0][i] = (P + 1 - ((g[1][i] *= 828542813ll) %= P)) % P; i == 1 || v[i - 1] - v[i] >= 0? modify(1, 1, n, i, 0, 0): f.push_back({i, 0}); i == 1 || v[i - 1] + v[i] <= 0? modify(1, 1, n, i, 0, 1): f.push_back({i, 1}); i == 1 || v[i - 1] + v[i] >= 0? modify(1, 1, n, i, 1, 0): f.push_back({i, 2}); i == 1 || v[i - 1] - v[i] <= 0? modify(1, 1, n, i, 1, 1): f.push_back({i, 3}); } sort(f.begin(), f.end(), [](pair<int, int> x, pair<int, int> y) { auto [ix, sx] = x; auto [iy, sy] = y; ll vx = (sx & 1? 1: -1) * v[ix - 1] + (sx & 2? -1: 1) * v[ix]; ll vy = (sy & 1? 1: -1) * v[iy - 1] + (sy & 2? -1: 1) * v[iy]; return (d[ix] - d[ix - 1]) * vy > (d[iy] - d[iy - 1]) * vx; }); for (auto [i, st]: f) { modify(1, 1, n, i, (st >> 1) & 1, (st >> 0) & 1); matrix res = query(1, 1, n, i + 1, n) * (st == 0? matrix(g[0][i], 0, 0, 0): (st == 1? matrix(0, g[0][i], 0, 0): (st == 2? matrix(0, 0, g[1][i], 0): matrix(0, 0, 0, g[1][i])))) * query(1, 1, n, 1, i - 1); (ans += (d[i] - d[i - 1]) * inv(((st & 1? 1: P - 1) * v[i - 1] % P + (st & 2? P - 1: 1) * v[i] % P) % P) % P * (res[0][0] + res[1][0]) % P) %= P; } return !printf("%lld\n", ans); } } int main() { return QYB::main(); }
cpp
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 OutputCopy5 1 8 6 NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.
[ "dfs and similar", "dp", "greedy", "trees" ]
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; #define endl '\n' #define ilihg ios_base::sync_with_stdio(false);cin.tie(NULL) int o,y,z; pair<int,int> dfs1(int i,vector<int> &b,vector<int> v[],vector<pair<int,int>> x[]){ b[i]=1; int r=0; int c=i; for(auto u:v[i]){ if(!b[u]){ pair<int,int> k=dfs1(u,b,v,x); k.first++; if(r<=k.first){ r=k.first; c=k.second; } x[i].push_back(k); } } return {r,c}; } pair<int,int> dfs(int i,vector<int> &b,vector<int> v[],pair<int,int> d,int &ans,vector<pair<int,int>> x[]){ b[i]=1; vector<pair<int,int>> c; int f=0; int r=i; int p=0; int pi; int w; for(int j=0;j<x[i].size();j++){ if(x[i][j].first>=p){ w=j; p=x[i][j].first; pi=x[i][j].second; } } int q=0; int qi; for(int j=0;j<x[i].size();j++){ if(j==w){ continue; } if(x[i][j].first>=q){ q=x[i][j].first; qi=x[i][j].second; } } int e=0; for(auto u:v[i]){ if(!b[u]){ pair<int,int> s; if(e==w){ if(d.first+1>=q+1){ s=dfs(u,b,v,{d.first+1,d.second},ans,x); } else{ s=dfs(u,b,v,{q+1,qi},ans,x); } } else{ if(d.first+1>=p+1){ s=dfs(u,b,v,{d.first+1,d.second},ans,x); } else{ s=dfs(u,b,v,{p+1,pi},ans,x); } } if(s.first+1>f){ f=s.first+1; r=s.second; } c.push_back({s.first+1,s.second}); e++; } } c.push_back(d); c.push_back({0,i}); c.push_back({0,i}); sort(c.rbegin(),c.rend()); if(c[0].first+c[1].first+c[2].first>=ans){ ans=c[0].first+c[1].first+c[2].first; o=c[0].second; y=c[1].second; z=c[2].second; } return {f,r}; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif clock_t time_req=clock(); ilihg; int t=1; // cin>>t; while(t--){ int n; cin>>n; vector<int> v[n+1]; for(int i=0;i<n-1;i++){ int c,d; cin>>c>>d; v[c].push_back(d); v[d].push_back(c); } int ans=0; vector<int> b(n+1); vector<pair<int,int>> x[n+1]; dfs1(1,b,v,x); for(int i=1;i<=n;i++){ b[i]=0; } dfs(1,b,v,{0,1},ans,x); cout<<ans<<endl; if(y==o){ if(o!=1&&z!=1){ y=1; } else if(o!=2&&z!=2){ y=2; } else{ y=3; } } if(o==z){ if(y!=1&&z!=1){ o=1; } else if(y!=2&&z!=2){ o=2; } else{ o=3; } } if(y==z){ if(y!=1&&o!=1){ z=1; } else if(y!=2&&o!=2){ z=2; } else{ z=3; } } cout<<o<<" "<<y<<" "<<z; } #ifndef ONLINE_JUDGE cout<<"Time : "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl; #endif }
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
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> using namespace std; #define MAX (int) 2e5 #define INF INT_MAX int distanceTo[MAX]; map<int, vector<int>> bertown1; map<int, vector<int>> bertown2; void BFS(int source) { int parent; set<int> visited; queue<int> toVisit; toVisit.push(source); visited.insert(source); while(!toVisit.empty()) { parent = toVisit.front(); for(int child : bertown2[parent]) { if(visited.count(child) == 0) { distanceTo[child] = distanceTo[parent] + 1; toVisit.push(child); visited.insert(child); } } toVisit.pop(); } } int main() { int n; int m; int a; int b; int k; int p; cin >> n; cin >> m; for(int i = 0; i < m; i++) { cin >> a; cin >> b; a--; b--; bertown1[a].push_back(b); bertown2[b].push_back(a); } int minCount = 0; int maxCount = 0; vector<int> actions; cin >> k; for(int i = 0; i < k; i++) { cin >> p; actions.push_back(--p); } BFS(actions[k - 1]); int prev; int curr; for(int i = 1; i < k; i++) { prev = actions[i - 1]; curr = actions[i]; if(distanceTo[curr] >= distanceTo[prev]) { minCount++; maxCount++; } else { for(int child : bertown1[prev]) { if((child != curr) && (distanceTo[child] == distanceTo[curr])) { maxCount++; break; } } } } cout << minCount << " " << maxCount << "\n"; }
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; #define pb push_back #define ll long long #define ull unsigned long long #define fi first #define se second #define SZ(x) ((int)(x).size()) #define ALL(x) (x).begin(), (x).end() #define MASK(i) ((1LL)<<(i)) #define GETBIT(x,i) (((x)>>(i))&1) #define TURNOFF(x,i) ((x)&(~(1<<i))) #define CNTBIT(x) __builtin_popcount(x) #define LOG 20 #define MASK(i) ((1LL)<<(i)) #define EL cout << "\n" #define FU(i, a, b) for(int i=a; i<=b; i++) #define FD(i, a, b) for(int i=a; i>=b; i--) #define REP(i, x) for(int i=0; i<x; i++) #define REPD(i, x) for(int i=x-1; i>=0; i--) const int MAX = 2e5 + 5; const int mod = 1e9 + 7; const int base = 31; const int INF = 1e9 + 7; typedef pair<int, int> ii; #define task "long" void init() { if (fopen(task".inp","r")) { freopen(task".inp","r",stdin); freopen(task".out","w",stdout); } else if (fopen(task".in", "r")) { freopen(task".in", "r", stdin); freopen(task".out", "w", stdout); } } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } int dx[]={0,1,0,-1,1,1,-1,-1}; int dy[]={1,0,-1,0,1,-1,1,-1}; template<class X, class Y> bool maximize(X &x, Y y){ if (x < y) {x = y; return true;} return false;}; template<class X, class Y> bool minimize(X &x, Y y){ if (x > y) {x = y; return true;} return false;}; void add(int &x, int y) { x += y; if (x>=mod) x-=mod;} void sub(int &x, int y) { x -= y; if (x<0) x+=mod;} int mul(int x, int y) {return 1LL * x * y % mod;} int calPw(int x, int y) { int ans = 1; while(y) { if (y&1) ans = 1LL * ans * x % mod; x = 1LL * x * x % mod; y >>= 1; } return ans; } int n; int mx[MAX], sum[MAX]; int S[MAX]; ii a[MAX]; void read() { cin >> n; FU(i, 1, n) cin >> a[i].fi >> a[i].se; } int bs(int x, int sz) { int l = 1, r = sz, ans = 0; while(l <= r) { int mid = (l + r) >> 1; if (S[mid] > x) { ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } void sol() { sort(a+1, a+n+1); memset(mx, 0, sizeof mx); mx[0] = -INF; sum[0] = 0; FU(i, 1, n) { sum[i] = sum[i-1] + (a[i].fi > mx[i-1]); mx[i] = max(mx[i-1], a[i].se); } int ans = 0, sz = 0; FD(i, n, 1) { int pos = bs(mx[i-1], sz); ans = max(ans, sum[i-1] + pos); while(sz && a[i].se >= S[sz]) --sz; S[++sz] = a[i].fi; } cout << ans, EL; } signed main() { fastio(); init(); int TEST = 1; cin >> TEST; while(TEST--) { read(); sol(); } }
cpp
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; int A,B,C,W; string s; int main() { cin>>A; while(A--) { cin>>B>>s;C=W=0; while(B--) { if(s[B]=='P')C++; else W=max(C,W),C=0; } cout<<W<<endl; }}
cpp
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int #define ull unsigned long long #define ld long double #define pb push_back #define endl '\n' #define mpp make_pair #define go continue #define ff first #define ss second #define pii pair<int,int> #define pll pair<ll,ll> #define umap unordered_map #define uset unordered_set #define PQ priority_queue #define Ok cout<<"Ok"<<endl #define Not cout<<"Not Ok"<<endl #define sq_check(x) (((ll)(sqrt((x))))*((ll)(sqrt((x))))==(x)) #define print(v) for(int i=0;i<v.size();i++)cout<<v[i]<<" "; #define DBG(a) cerr<< "Line "<<__LINE__ <<" : "<< #a <<" = "<<(a)<<endl #define fastio {ios_base::sync_with_stdio(false);cin.tie(NULL);} #define mod 1000000007 const double PI = acos(-1.0); const ll INF = 0x3f3f3f3f3f3f3f3f; #define str_to_int(a) atoi(a.c_str()) string int_to_str(int n) {stringstream rr;rr<<n;return rr.str();} //ll gcd(ll a,ll b){while(b){ll x=a%b;a=b;b=x;}return a;} //ll lcm(ll a,ll b){return a/gcd(a,b)*b;} ll fact[300005]; int main() { ll n,m; cin>>n>>m; ll a=1; for(ll i=1;i<=n;i++) { a*=i; a%=m; fact[i]=a; } ll ans=0; for(ll i=1;i<=n;i++) { ll l=i; ll r=n-i+1; ans+=(((fact[l]*fact[r])%m)*r)%m; ans%=m; } cout<<ans<<endl; 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" ]
// LUOGU_RID: 100970504 #include <bits/stdc++.h> #define sz(v) (int) (v).size() #define all(v) begin(v), end(v) #define view(v, l, r) begin(v) + l, begin(v) + r + 1 #define dbg(fmt...) fprintf(stderr, fmt) #define fi first #define se second using namespace std; using i64 = long long; using i128 = __int128_t; using u32 = unsigned; using u64 = unsigned long long; using u128 = __uint128_t; using f64 = double; using f128 = long double; template<typename T> bool chmin(T &a, const T &b) { return (b < a) ? a = b, 1 : 0; } template<typename T> bool chmax(T &a, const T &b) { return (b > a) ? a = b, 1 : 0; } constexpr int M = 18; int buc[1 << M], par[1 << M]; int get(int x) { return par[x] == x ? x : par[x] = get(par[x]); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int m = __lg(*max_element(all(a)) - 1) + 1; iota(par, par + (1 << m), 0); int full = (1 << m) - 1; i64 ans = 0; for (auto &x : a) { ++buc[x]; ans -= x; } ++buc[0]; for (int s = full; s; --s) { for (int u = s; ; u = (u - 1) & s) { int v = s ^ u; if (buc[u] && buc[v] && get(u) != get(v)) { ans += (buc[u] + buc[v] - 1ll) * s; buc[u] = buc[v] = 1; par[get(v)] = get(u); } if (!u) { break; } } } cout << ans; }
cpp
1290
F
F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3 -1 0 1 1 0 -1 OutputCopy3 InputCopy3 3 -1 0 2 2 0 -1 OutputCopy1 InputCopy3 1776966 -1 0 3 3 0 -2 OutputCopy296161 InputCopy4 15 -4 -4 -1 1 -1 -4 4 3 OutputCopy1 InputCopy5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 OutputCopy0 InputCopy5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 OutputCopy9248783 NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is:
[ "dp" ]
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0' or ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0' and ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return x*f; } void write(int x){ if(x<0) putchar('-'),x=-x; if(x>=10) write(x/10); putchar(x%10+'0'); } const int mod = 998244353; int n,m; int x[5],y[5]; int dp[32][22][22][22][22][2][2]; void add(int &x,int y){x=(x+y)%mod;}; int get(int x,int y,int z){return (x^y)?y>x:z;} int dfs(int p,int a,int b,int c,int d,int f1,int f2){ if((1ll<<p)>m) return (!a and !b and !c and !d and !f1 and !f2); if(dp[p][a][b][c][d][f1][f2]>=0) return dp[p][a][b][c][d][f1][f2]; int g=(m>>p)&1,res = 0; for(int s=0;s<(1<<n);s++){ for(int i = 0;i<n;i++) if((s>>i)&1) (x[i]>0?a+=x[i]:b-=x[i]),(y[i]>0?c+=y[i]:d-=y[i]); if((a&1)==(b&1) and (c&1)==(d&1)) add(res,dfs(p+1,a>>1,b>>1,c>>1,d>>1,get(g,a&1,f1),get(g,c&1,f2))); for(int i = 0;i<n;i++) if((s>>i)&1) (x[i]>0?a-=x[i]:b+=x[i]),(y[i]>0?c-=y[i]:d+=y[i]); } return dp[p][a][b][c][d][f1][f2]=res; } signed main(){ // freopen("T.in","r",stdin); // freopen("T.out","w",stdout); n = read(),m = read(),memset(dp,0x80,sizeof(dp)); for(int i = 0;i<n;i++) x[i] = read(),y[i] = read(); write((dfs(0,0,0,0,0,0,0)+mod-1)%mod); return 0; }
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 <algorithm> #include <cmath> #include <vector> #include<string> #include<map> //#include <bits/stdc++.h> using namespace std; #define FAST ios_base::sync_with_stdio(0),cin.tie(0) typedef long long ll; const int N = 2e5 + 9, M = 2e5 + 6, MOD = 998244353, OO = 0x3f3f3f3f, SQR = 320; const ll LOO = 0x3f3f3f3f3f3f3f3f; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { FAST; int n , count , x,sum =0 ; cin >> n; count = n - 2; for (int i = 2; i < n; i++) { int temp = n; while (temp > 0) { int x = temp % i; temp = temp / i; sum += x; } } x = gcd(sum, count); cout << sum / x << '/' << count / x << endl; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<queue> #define ll long long #define int ll #define Inf 0x3f3f3f3f using namespace std; const int N=2e5+60,M=1e6+20,mod=998244353; inline int read(){ int d=0,f=1;char x=getchar(); while(x<'0'||x>'9'){if(x=='-'){f=-1;}x=getchar();} while(x>='0'&&x<='9'){d=(d<<1)+(d<<3)+(x-48);x=getchar();} return d*f; } int n,m,a[N],p[N],ret[N]; struct Seg{ int c[N<<2],mx[N<<2],se[N<<2],tag[N<<2],stag[N<<2],len[N<<2],slen[N<<2],sum[N<<2]; void mem(int rt,int l,int r){ c[rt]=mx[rt]=se[rt]=tag[rt]=stag[rt]=len[rt]=slen[rt]=sum[rt]=0; if(l==r) return ; int mid=(l+r)>>1; mem(rt<<1,l,mid);mem(rt<<1|1,mid+1,r); } void pushup(int rt){ c[rt]=c[rt<<1]+c[rt<<1|1];sum[rt]=sum[rt<<1]+sum[rt<<1|1]; if(mx[rt<<1]>mx[rt<<1|1]){ mx[rt]=mx[rt<<1],se[rt]=max(se[rt<<1],mx[rt<<1|1]); len[rt]=len[rt<<1],slen[rt]=slen[rt<<1]+slen[rt<<1|1]+len[rt<<1|1]; } else if(mx[rt<<1]<mx[rt<<1|1]){ mx[rt]=mx[rt<<1|1],se[rt]=max(se[rt<<1|1],mx[rt<<1]); len[rt]=len[rt<<1|1],slen[rt]=slen[rt<<1]+slen[rt<<1|1]+len[rt<<1]; } else{ mx[rt]=mx[rt<<1],se[rt]=max(se[rt<<1|1],se[rt<<1]); len[rt]=len[rt<<1]+len[rt<<1|1],slen[rt]=slen[rt<<1]+slen[rt<<1|1]; } } void pushtag(int rt,int tag1,int tag2,int flag){ if(!flag) tag1=tag2; mx[rt]+=tag1;tag[rt]+=tag1;se[rt]+=tag2;stag[rt]+=tag2; sum[rt]+=tag1*len[rt]+tag2*slen[rt]; } void pushdown(int rt){ bool flag=mx[rt<<1]<=mx[rt<<1|1]; pushtag(rt<<1,tag[rt],stag[rt],mx[rt<<1]>=mx[rt<<1|1]); pushtag(rt<<1|1,tag[rt],stag[rt],flag); tag[rt]=stag[rt]=0; } int add(int rt,int l,int r,int ql,int qr){ if(ql>r||qr<l) return 0; if(ql<=l&&r<=qr){pushtag(rt,1,1,1);return c[rt];} pushdown(rt); int mid=(l+r)>>1;int res=add(rt<<1,l,mid,ql,qr)+add(rt<<1|1,mid+1,r,ql,qr); pushup(rt); return res; } void update(int rt,int l,int r,int p,int k){ if(l==r){sum[rt]=mx[rt]=k;len[rt]=c[rt]=1;return ;} pushdown(rt);int mid=(l+r)>>1; if(p<=mid) update(rt<<1,l,mid,p,k); else update(rt<<1|1,mid+1,r,p,k); pushup(rt);return ; } void updmin(int rt,int l,int r,int ql,int qr,int k){ if(ql>r||qr<l||k>=mx[rt]) return ; if(ql<=l&&r<=qr&&k>se[rt]){pushtag(rt,min(k-mx[rt],0ll),0,1);return ;} pushdown(rt);int mid=(l+r)>>1; updmin(rt<<1,l,mid,ql,qr,k);updmin(rt<<1|1,mid+1,r,ql,qr,k); pushup(rt); } }t; signed main(){ n=read(); for(int i=1;i<=n;i++) p[a[i]=read()]=i; for(int i=1;i<=n;i++){ int x=t.add(1,1,n,p[i]+1,n);t.update(1,1,n,p[i],i+1); t.updmin(1,1,n,1,p[i]-1,i-x);ret[i]+=t.sum[1]; } for(int i=1;i<=n;i++) p[i]=n-p[i]+1; t.mem(1,1,n); for(int i=1;i<=n;i++){ int x=t.add(1,1,n,p[i]+1,n);t.update(1,1,n,p[i],i+1); t.updmin(1,1,n,1,p[i]-1,i-x);ret[i]+=t.sum[1]; } for(int i=1;i<=n;i++) printf("%lld\n",ret[i]-i*(i+2)); return 0; }
cpp
1284
E
E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5 -1 0 1 0 -10 -1 10 -1 0 3 OutputCopy2InputCopy8 0 1 1 2 2 2 1 3 0 -1 -1 -2 -2 -2 -1 -3 OutputCopy40InputCopy10 588634631 265299215 -257682751 342279997 527377039 82412729 145077145 702473706 276067232 912883502 822614418 -514698233 280281434 -41461635 65985059 -827653144 188538640 592896147 -857422304 -529223472 OutputCopy213
[ "combinatorics", "geometry", "math", "sortings" ]
#include <bits/stdc++.h> using namespace std; #define int long long #define double long double #define N 2501 complex<double> points[N]; double Pi = arg(complex<double>(-1, 0)); int nC2(int n){ return (n * (n - 1)) / 2; } bool cmp(pair<double, complex<double>> a, pair<double, complex<double>> b){ return a.first < b.first; } int solve(int idx, int n){ vector<pair<double, complex<double>>> Circle; for (int i = 0; i < n; i++){ if (i != idx) Circle.push_back({arg(points[i] - points[idx]), points[i] - points[idx]}); } sort(Circle.begin(), Circle.end(), cmp); int j = 0; int nm = Circle.size(); int ans = 0; // for (auto f : Circle){ // cout << '(' << f.real() << ',' << f.imag() << ") "; // } // cout << endl; // cout << arg(Circle[0] * conj(Circle[2])) << endl; for (int i = 0; i < nm; i++){ if (j == i){ j = (j + 1) % nm; } complex<double> tmp = conj(Circle[i].second); while (j != i){ if ((Circle[j].second * tmp).imag() >= 0){ j++; j %= nm; } else break; } // cout << i << ' ' << j << endl; int len = (j >= i + 1 ? j - i - 1 : j - i - 1 + nm); ans += nC2(len); } // cout << ans << endl; ans = (nm * (nm - 1) * (nm - 2)) / 6 - ans; return ans; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 0; i < n; i++){ int x, y; cin >> x >> y; points[i] = complex<double>(x, y); } int ans = 0; for (int i = 0; i < n; i++){ int tmp = ans; ans += solve(i, n); // cout << i << ' ' << ans - tmp << endl; } // ans += solve(0, n); ans *= n - 4; ans /= 2; cout << ans << endl; }
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: 94145794 #include<cstdio> #include<cstring> #include<iostream> #define ll long long using namespace std; char s1[500005], s2[500005], s3[1000005], s4[1000005]; int z1[500005], z2[500005], z3[1000005], z4[1000005]; void calcz(int n1, int n2, char s1[], int z1[], char s2[], int z2[]) { int pos = 0; if(s1 == s2) z2[1] = n2; for(int i = 1 + (s1 == s2); i <= n2; i++) { z2[i] = min(z2[pos] - (i - pos), z1[i - pos + 1]); if(z2[i] < 0) z2[i] = 0; while(s2[i + z2[i]] == s1[z2[i] + 1]) z2[i]++; if(i + z2[i] > pos + z2[pos]) pos = i; } } //1 -> 2 ll fw1[1000005], fw2[1000005]; void fwadd(ll fw[], int n, int p, ll t){while(p <= n) fw[p] += t, p += p & -p;} ll fwget(ll fw[], int p){ll res = 0; while(p) res += fw[p], p -= p & -p; return res;} void modify(int n, int l, int r, ll t) { fwadd(fw1, n, l, t * l), fwadd(fw1, n, r + 1, -t * (r + 1)); fwadd(fw2, n, l, t), fwadd(fw2, n, r + 1, -t); } ll get(int n, int l, int r) { ll res1 = 0, res2 = 0; if(l > 1) res1 = fwget(fw2, l - 1) * l - fwget(fw1, l - 1); res2 = fwget(fw2, r) * (r + 1) - fwget(fw1, r); return res2 - res1; } int main() { int n, m; ll ans = 0; scanf("%d%d", &n, &m); scanf("%s%s%s", s1 + 1, s2 + 1, s3 + 1); s1[n + 1] = s2[n + 1] = '@', s3[m + 1] = s4[m + 1] = '#'; for(int i = 1; i <= m; i++) s4[m + 1 - i] = s3[i]; for(int i = 1, j = n; i < j; i++, j--) swap(s2[i], s2[j]); calcz(m, m, s3, z3, s3, z3), calcz(m, m, s4, z4, s4, z4); calcz(m, n, s3, z3, s1, z1), calcz(m, n, s4, z4, s2, z2); for(int i = 1, j = n; i < j; i++, j--) swap(z2[i], z2[j]); for(int i = 1; i <= n; i++) { modify(m, 1, z1[i], 1); if(i >= m) modify(m, 1, z1[i - m + 1], -1); ans += get(m, m - z2[i], m - 1); } printf("%lld", ans); return 0; }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
//jai shree ram #include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef long long LL; typedef long double ld; typedef vector<long long> vLL; typedef vector<long long int> vll; typedef vector<int> vi; #define pb push_back #define mk make_pair int bisearch(ll arr[],ll x,int n){ int l=0; int r=n-1; while(l<=r){ int mid = (l+r)/2; if(arr[mid]==x){ return mid; } else if(arr[mid]>x){ r=mid-1; } else l=mid+1; } return -1; } int cntDistinct(string str) { unordered_set<char> s; for (int i = 0; i < str.size(); i++) { s.insert(str[i]); } return s.size(); } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; int a[2]; int k=0; for(int i=0;i<n;i++){ if((s[i]-'0')%2==1){ a[k]=s[i]-'0'; k++; } if(k==2)break; } if(k==2)cout<<a[0]<<a[1]; else cout<<"-1"; cout<<endl; } return 0; } //jai shree krishna
cpp
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
#include<bits/stdc++.h> template<class T> inline void read(T &x){ x=0;register char c=getchar();register bool f=0; while(!isdigit(c))f^=c=='-',c=getchar(); while(isdigit(c))x=x*10+c-'0',c=getchar();if(f)x=-x; } template<class T> inline void print(T x){ if(x<0)putchar('-'),x=-x; if(x>9)print(x/10);putchar(x%10+'0'); } template<class T> inline void print(T x,char c){print(x),putchar(c);} template<class T> inline void print(T a,int l,int r){for(int i=l;i<=r;i++)print(a[i]," \n"[i==r]);} const int N=110; int n,m,ans,a[N],b[N],cnt[2]; std::vector<int> q[2]; int solve(){ int ans=0; m=0,cnt[0]=n>>1,cnt[1]=(n+1)>>1; q[0].clear(); q[1].clear(); for(int i=1;i<=n;i++)if(~a[i])cnt[a[i]]--; for(int i=0;i<=n+1;i++)if(~a[i])b[++m]=i; for(int i=1;i<m;i++)if(a[b[i]]!=a[b[i+1]])ans++; for(int i=1;i<m;i++)if(a[b[i]]==a[b[i+1]]){ q[a[b[i]]].push_back(b[i+1]-b[i]-1); } std::sort(q[0].begin(),q[0].end()); std::sort(q[1].begin(),q[1].end()); for(int i=0;i<q[0].size();i++){ if(q[0][i]<=cnt[0])cnt[0]-=q[0][i]; else ans+=2; } for(int i=0;i<q[1].size();i++){ if(q[1][i]<=cnt[1])cnt[1]-=q[1][i]; else ans+=2; } return ans; } int main(){ #ifdef memset0 freopen("1.in","r",stdin); #endif read(n); for(int x,i=1;i<=n;i++)read(x),a[i]=x?x&1:-1; ans=n; a[0]=0,a[n+1]=0,ans=std::min(ans,solve()); a[0]=0,a[n+1]=1,ans=std::min(ans,solve()); a[0]=1,a[n+1]=0,ans=std::min(ans,solve()); a[0]=1,a[n+1]=1,ans=std::min(ans,solve()); printf("%d\n",ans); }
cpp
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
#include<bits/stdc++.h> #define endl '\n' #define int long long using namespace std; const int N=3e5+3; int n,m,x; int vis[N],a[N][10]; bool check(int mid) { memset(vis,0,sizeof(vis)); for(int i=1; i<=n; i++) { int ans=0; for(int j=0; j<m; j++) { if(a[i][j]>=mid) ans+=(1<<j); } vis[ans]=1; } for(int i=0; i<(1<<m); i++) for(int j=0; j<(1<<m); j++) if(vis[i]&&vis[j]&&(i|j)==x)return 1; return 0; } void solve() { cin>>n>>m; for(int i=1; i<=n; i++) for(int j=0; j<m; j++) cin>>a[i][j]; int l=0,r=1e9,sum; x=(1<<m)-1; while(l<=r) { int mid=(l+r)/2; if(check(mid)) sum=mid,l=mid+1; else r=mid-1; } memset(vis,0,sizeof(vis)); for(int i=1; i<=n; i++) { int ans=0; for(int j=0; j<m; j++) { if(a[i][j]>=sum) ans+=(1<<j); } vis[ans]=i; } int x1,x2; for(int i=0; i<(1<<m); i++) for(int j=0; j<(1<<m); j++) if(vis[i]&&vis[j]&&(i|j)==x) { x1=vis[i],x2=vis[j]; break; } cout<<x1<<" "<<x2<<endl; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // int t; cin>>t; while(t--) solve(); return 0; }
cpp
1305
H
H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor; Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of nn questions, and mm students have taken the exam. Each question was worth 11 point. Question ii was solved by at least lili and at most riri students. Additionally, you know that the total score of all students is tt.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 11 to mm, where rank 11 has the highest score and rank mm has the lowest score. Ties were broken arbitrarily.You know that the student at rank pipi had a score of sisi for 1≤i≤q1≤i≤q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students.InputThe first line of input contains two integers (1≤n,m≤1051≤n,m≤105), denoting the number of questions of the exam and the number of students respectively.The next nn lines contain two integers each, with the ii-th line containing lili and riri (0≤li≤ri≤m0≤li≤ri≤m).The next line contains a single integer qq (0≤q≤m0≤q≤m). The next qq lines contain two integers each, denoting pipi and sisi (1≤pi≤m1≤pi≤m, 0≤si≤n0≤si≤n). It is guaranteed that all pipi are distinct and if pi≤pjpi≤pj, then si≥sjsi≥sj.The last line contains a single integer tt (0≤t≤nm0≤t≤nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output −1−1 −1−1.ExamplesInputCopy5 4 2 4 2 3 1 1 0 1 0 0 1 4 1 7 OutputCopy3 2 InputCopy5 6 0 6 0 6 2 5 6 6 4 6 1 3 3 30 OutputCopy-1 -1 NoteFor the first sample; here is one possible arrangement that fits the data:Students 11 and 22 both solved problems 11 and 22.Student 33 solved problems 22 and 33.Student 44 solved problem 44.The total score of all students is T=7T=7. Note that the scores of the students are 22, 22, 22 and 11 respectively, which satisfies the condition that the student at rank 44 gets exactly 11 point. Finally, 33 students tied for first with a maximum score of 22, and it can be proven that we cannot do better with any other arrangement.
[ "binary search", "greedy" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds; const int N = 150000; //number of problems const int M = 150000; //number of students int L[N+10]; int R[N+10]; int a[N+10]; //array of fixed score ll T; int n,m; void read() { cin>>n>>m; for(int i=0;i<n;i++) //problem score { cin>>L[i]>>R[i]; } for(int i=0;i<m;i++) a[i]=-1; int q; cin>>q; for(int i=0;i<q;i++) { int rk, sc; cin>>rk>>sc; a[m-rk] = sc; } cin>>T; //total score } vector<ll> sortedL,sortedR; struct ConvexHull { struct Line { ll m, c; Line (ll _m, ll _c) : m(_m), c(_c) {} ll pass(ll x) { return m * x + c; } }; deque<Line> d; bool irrelevant(Line Z) { if (int(d.size()) < 2) return false; Line X = d[int(d.size())-2], Y = d[int(d.size())-1]; return (X.c - Z.c) * (Y.m - X.m) <= (X.c - Y.c) * (Z.m - X.m); } void push_line(ll m, ll c) { Line l = Line(m,c); while (irrelevant(l)) d.pop_back(); d.push_back(l); } ll query(ll x) { while (int(d.size()) > 1 && (d[0].c - d[1].c <= x * (d[1].m - d[0].m))) d.pop_front(); return d.front().pass(x); } }; bool check_naive(vector<int> b) //check if your assignment is valid { ll sumB = 0; ll sumL = 0; sort(b.begin(),b.end()); for(int i=0;i<b.size();i++) { sumB+=b[i]; if(a[i]!=-1) assert(a[i]==b[i]); if(i>0) assert(b[i]>=b[i-1]); } for(int i=0;i<n;i++) sumL+=L[i]; assert(int(b.size())==m&&sumB==T); ll cursum=0; for(int i=0;i<=m;i++) { for(int j=0;j<=n;j++) { ll s1 = sortedR[j]+cursum+(n-j)*1LL*(m-i); ll s2 = sortedL[j]+cursum+(n-j)*1LL*(m-i); if(s1<sumB||s2<sumL) return false; } if(i<m) cursum+=b[i]; } return true; } bool check(vector<int> b) //check if your assignment is valid { ll sumB = 0; ll sumL = 0; sort(b.begin(),b.end()); for(int i=0;i<b.size();i++) { sumB+=b[i]; if(a[i]!=-1) assert(a[i]==b[i]); if(i>0) assert(b[i]>=b[i-1]); } for(int i=0;i<n;i++) sumL+=L[i]; assert(int(b.size())==m&&sumB==T); ll cursum=0; ConvexHull ch1,ch2; for(int j=n;j>=0;j--) { ch1.push_line(n-j,-sortedR[j]+j*1LL*m); ch2.push_line(n-j,-sortedL[j]+j*1LL*m); } for(int i=0;i<=m;i++) { ll v1 = -ch1.query(i); ll v2 = -ch2.query(i); if(v1<sumB-(cursum+n*1LL*m)||v2<sumL-(cursum+n*1LL*m)) return false; if(i<m) cursum+=b[i]; } return true; } void greedyrange(vector<int> &v, int l, int r, int ub, ll &S) { if(S<=0) return ; ll ext = 0; for(int i=l;i<=r;i++) { ext+=ub-v[i]; } if(ext<=S) { S-=ext; for(int i=l;i<=r;i++) { v[i]=ub; } return ; } deque<ii> dq; for(int i=l;i<=r;i++) { if(!dq.empty()&&dq.back().fi==v[i]) { dq.back().se++; } else { dq.pb({v[i],1}); } } while(S>0&&dq.size()>1) { int L = dq[0].fi; int cnt = dq[0].se; int R = dq[1].fi; //I have (R-L)*cnt before absolute merge if((R-L)*1LL*cnt<=S) { S-=(R-L)*1LL*cnt; dq[1].se+=cnt; dq.pop_front(); continue; } //not enough space liao ll q = S/cnt; ll rem = S%cnt; dq[0].fi+=q; if(rem>0) { ii tmp = dq.front(); dq.pop_front(); dq.push_front({rem,tmp.fi+1}); dq.push_front({cnt-rem,tmp.fi}); } S=0; break; } //S>0 if(S>0) { assert(int(dq.size())==1); ll q = S/(r-l+1); ll rem = S%(r-l+1); for(int i=l;i<=r;i++) { v[i]=dq[0].fi+q; } int ptr=r; for(int i=0;i<rem;i++) { v[ptr--]++; } S=0; } else { int ptr=l; for(ii x:dq) { for(int j=0;j<x.se;j++) v[ptr++]=x.fi; } } } void greedy(vector<int> &v, ll &S) { if(S<=0) return ; vi ans; vector<ii> ranges; int l=0; for(int i=0;i<m;i++) { if(a[i]==-1) continue; if(l<=i-1) { ranges.pb({l,i-1}); } l=i+1; } if(l<m) ranges.pb({l,m-1}); for(ii x:ranges) { int r=x.se; int ub = n; if(r+1<m&&a[r+1]!=-1) ub=a[r+1]; greedyrange(v,x.fi,x.se,ub,S); } } ii solve_full() { sortedL.clear(); sortedR.clear(); sortedL.pb(0); sortedR.pb(0); for(int i=0;i<n;i++) { sortedL.pb(L[i]); sortedR.pb(R[i]); } sort(sortedL.begin(),sortedL.end()); sort(sortedR.begin(),sortedR.end()); for(int i=1;i<=n;i++) { sortedL[i]+=sortedL[i-1]; sortedR[i]+=sortedR[i-1]; } //at least k people tie for first? int lo = 1; int hi = m; int anstie = -1; int ansm = 0; vector<int> testb; vi ori(m,-1); while(lo<=hi) { int mid=(lo+hi)>>1; vector<int> b; int curmin=0; ll cursum=0; for(int i=0;i<m;i++) { if(a[i]!=-1) curmin=a[i]; b.pb(curmin); cursum+=b[i]; } //left T - cursum stuff to add :( //fix the maximum M bool pos=0; int forcedM=-1; for(int j=m-mid;j<m;j++) { if(a[j]>=0) { if(forcedM>=0&&forcedM!=a[j]) forcedM=-2; forcedM = a[j]; } } if(forcedM>=-1) { int L2 = curmin; int R2 = n; if(forcedM>=0) L2=R2=forcedM; //otherwise L2 is the smallest d+curmin such that there EXIST a good covering if(forcedM<0) { int lo2 = curmin; int hi2 = max(0LL,min(ll(n),(T-cursum)/mid+curmin)); //add to everyone i guess L2=int(1e9); while(lo2<=hi2) { int mid2=(lo2+hi2)>>1; vector<int> nwb = b; ll rem = T - cursum; int M = mid2; for(int j=m-mid;j<m;j++) { rem+=b[j]; rem-=M; nwb[j]=M; if(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);} ori[j]=a[j]; a[j]=M; } greedy(nwb, rem); for(int j=m-mid;j<m;j++) { a[j]=ori[j]; } if(rem==0) { hi2=mid2-1; L2=mid2; } else { lo2=mid2+1; } } } //how to figure out L2 otherwise!? while(L2<=R2) { int M = (L2+R2)>>1; vector<int> nwb = b; ll rem = T - cursum; for(int j=m-mid;j<m;j++) { rem+=b[j]; rem-=M; nwb[j]=M; if(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);} ori[j]=a[j]; a[j]=M; } greedy(nwb, rem); if(rem==0&&check(nwb)) { testb=nwb; ansm=M; pos=1; L2=M+1; } else { R2=M-1; } for(int j=m-mid;j<m;j++) { a[j]=ori[j]; } } } if(pos) { anstie=mid; lo=mid+1; } else hi=mid-1; } if(anstie==-1) { return {-1,-1}; } return {anstie,ansm}; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); //freopen("student-scores.in","r",stdin); read(); ii sol2 = solve_full(); cout<<sol2.fi<<' '<<sol2.se<<'\n'; }
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 <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC optimization ("unroll-loops") #pragma GCC target("avx,avx2,fma") using namespace std; using namespace __gnu_pbds; template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key ------> return index // find_by_order -----> use index #define ll long long #define ull unsigned long long #define ld long double #define dl double #define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define f first #define s second #define pb push_back #define el '\n' #define INF 0x3f3f3f3f3f3f3f3f #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define ones(x) __builtin_popcountll(x) #define memss(a, b, sz) memset(arr,b,sz * sizeof (arr[0])) #define ii pair<int,int> int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; const int mod = 1e9 + 7, N = 1e5 + 9, mod2 = 998244353, M = 1e4 + 5; const ld eps = 1e-10; ll n,p,k,dp[N][1 << 7],a[N],s[N][7]; vector<pair<int,int>>t; ll solve(int i,int cnt,int msk) { if(i == n) { return (msk == (1 << p) - 1) ? 0 : -1e18; } ll & ans = dp[i][msk]; if(~ans) return ans; ans = solve(i + 1,cnt,msk); for (int l = 0; l < 7; ++l) { if(msk & (1 << l)) continue; ans = max(ans, solve(i + 1,cnt + 1, msk | (1 << l)) + s[t[i].s][l]); } if(i < (cnt + k)) ans = max(ans, solve(i + 1 ,cnt + 1 ,msk) + t[i].f); return ans; } void set_ans(int Case) { ::memset(dp,-1,sizeof dp); cin >> n >> p >> k; for (int i = 0; i < n; ++i) { cin >> a[i]; t.pb({a[i],i}); } sort(allr(t)); for (int i = 0; i < n; ++i) { for (int j = 0; j < p; ++j) { cin >> s[i][j]; } } ll ans = 0; // sort(all(t)); ans = solve(0,0,0); cout << ans << el; } int main() { io #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif int testCases = 1; // cin >> testCases; for (int Case = 1; Case <= testCases; Case++) set_ans(Case); return 0; }
cpp
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
#define lli long long int #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); lli n, lc = 0, rc = 0; cin>>n; string s; cin>>s; for(int i=0;i<n;i++) { if(s[i] == 'L') { lc++; } else { rc++; } } cout<<(lc+rc+1)<<"\n"; return 0; }
cpp
1288
F
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 OutputCopy35 BUURRU InputCopy3 1 3 4 5 RRR B 2 1 1 1 3 1 OutputCopy-1 InputCopy3 1 3 4 5 URU B 2 1 1 1 3 1 OutputCopy14 RBB
[ "constructive algorithms", "flows" ]
#include <bits/stdc++.h> using namespace std; #define Int register int #define inf 0x3f3f3f3f #define int long long #define MAXM 50005 #define MAXN 5005 template <typename T> void read (T &x){char c = getchar ();x = 0;int f = 1;while (c < '0' || c > '9') f = (c == '-' ? -1 : 1),c = getchar ();while (c >= '0' && c <= '9') x = x * 10 + c - '0',c = getchar ();x *= f;} template <typename T,typename ... Args> void read (T &x,Args& ... args){read (x),read (args...);} template <typename T> void write (T x){if (x < 0) x = -x,putchar ('-');if (x > 9) write (x / 10);putchar (x % 10 + '0');} template <typename T> void chkmax (T &a,T b){a = max (a,b);} struct edge{ int v,flw,cost,nxt; }e[MAXM << 1]; int toop = 1,head[MAXN]; int dis[MAXN],cur[MAXN];bool vis[MAXN]; bool spfa (int s,int t){ memcpy (cur,head,sizeof (head)),memset (dis,0x3f,sizeof (dis)),memset (vis,0,sizeof (vis));queue <int> q;dis[s] = 0,vis[s] = 1,q.push (s); int st0 = dis[t]; while (!q.empty()){ int u = q.front();q.pop(),vis[u] = 0; for (Int i = head[u];i;i = e[i].nxt){ int v = e[i].v,flw = e[i].flw,cst = e[i].cost; if (flw && dis[v] > dis[u] + cst){ dis[v] = dis[u] + cst; if (!vis[v]) vis[v] = 1,q.push (v); } } } return dis[t] != st0; } int dfs (int u,int flow,int t,int &ans){ if (u == t) return ans += flow * dis[t],flow; int rst = flow,tmp = flow;vis[u] = 1; for (Int i = cur[u];i && rst;i = e[i].nxt){ cur[u] = i; int v = e[i].v,flw = e[i].flw,cst = e[i].cost; if (flw && dis[v] == dis[u] + cst && !vis[v]){ int had = dfs (v,min (rst,flw),t,ans); if (!had) dis[v] = -inf; e[i].flw -= had,e[i ^ 1].flw += had,rst -= had; if (!rst) break; } } return tmp - rst; } #define pii pair<int,int> #define se second #define fi first pii Maxflow (int s,int t){ int ans = 0,flw = 0; while (spfa (s,t)) flw += dfs (s,inf,t,ans); return {flw,ans}; } int deg[MAXN]; void addit (int u,int v,int l,int r,int c){ deg[u] -= l,deg[v] += l; e[++ toop] = edge{v,r - l,c,head[u]},head[u] = toop; e[++ toop] = edge{u,0,-c,head[v]},head[v] = toop; } int n1,n2,m,R,B;char str[MAXN]; signed main(){ read (n1,n2,m,R,B); int s = n1 + n2 + 1,t = s + 1, S = t + 1,T = S + 1; scanf ("%s",str + 1); for (Int i = 1;i <= n1;++ i) if (str[i] == 'R') addit (s,i,1,inf,0); else if (str[i] == 'B') addit (i,t,1,inf,0); else addit (s,i,0,inf,0),addit (i,t,0,inf,0); scanf ("%s",str + 1); for (Int i = 1;i <= n2;++ i) if (str[i] == 'R') addit (n1 + i,t,1,inf,0); else if (str[i] == 'B') addit (s,n1 + i,1,inf,0); else addit (s,n1 + i,0,inf,0),addit (n1 + i,t,0,inf,0); int sht = toop; for (Int i = 1,u,v;i <= m;++ i) read (u,v),addit (u,v + n1,0,1,R),addit (v + n1,u,0,1,B); int sum = 0; addit (t,s,0,inf,0); for (Int i = 1;i <= t;++ i){ if (deg[i] > 0) sum += deg[i],addit (S,i,0,deg[i],0); if (deg[i] < 0) addit (i,T,0,-deg[i],0); } pii it = Maxflow (S,T); if (it.fi < sum) return puts ("-1") & 0; write (it.se),putchar ('\n'); for (Int i = sht + 1;i <= sht + 4 * m;i += 4){ if (!e[i].flw) putchar ('R'); else if (!e[i + 2].flw) putchar ('B'); else putchar ('U'); } putchar ('\n'); return 0; }
cpp
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
[ "graphs", "hashing", "math", "number theory" ]
// LUOGU_RID: 101673521 #include<bits/stdc++.h> #include<unordered_map> #include<algorithm> using namespace std; #define ll long long #define pii pair<ll,ll> ll n,m; void solve() { cin >> n >> m; vector<ll> a(n + 1); vector<set<int>> s(n + 1); for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= m; i++) { int u, v; cin >> u >> v; s[v].insert(u); } map<set<int>, ll> mp; for (int i = 1; i <= n; i++) { if(!s[i].empty()) mp[s[i]] += a[i]; } ll ans = 0; for (auto i : mp) { if (ans) ans = gcd(ans, i.second); else ans = i.second; } cout << ans << '\n'; } signed main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); int tt = 1; cin >> tt; while (tt--) solve(); return 0; } /* */
cpp
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5 64 32 97 2 12345 OutputCopyYES 2 4 8 NO NO NO YES 3 5 823
[ "greedy", "math", "number theory" ]
#pragma GCC optimize("O3,inline") #pragma GCC target("bmi,bmi2,lzcnt,popcnt") #include<bits/stdc++.h> using namespace std; typedef long long ll; #define all(a) a.begin(), a.end() #define lpr(i,a,b) for(ll i = a; i >= b; i--) #define lp(i,a,b) for(ll i=a;i<b;i++) #define pb push_back #define pp pop_back #define endl "\n" using namespace std; // const int imax = std::numeric_limits<int>::max(); // using vi = vector<int>; // //ll st,en,n; // map<ll,int>ans; // const int NN=1e6; // int a[NN]; // vector<vector<int>>adjList(NN); // set<int>nodes; // /* printPath - implementation at the end */ // void printPath(int s, int t, const vi &path); // /*input: * n is number of the nodes in the Graph * adjList holds a neighbors vector for each Node * s is the source node */ // // void dfs(int n, vector<vi> adjList, int s) // { // //imax declared above as the max value for int (in C++) // vector<int> distance(n, imax); // vi path; // queue<int> q; q.push(s); distance[s] = 0; // // while (!q.empty()) { // auto curr = q.front(); q.pop(); // // for (int i = 0; i < (int)adjList[curr].size(); ++i) { // if (distance[i] == imax) { // distance[i] = distance[curr] + 1; // //save the parent to have the path at the end of the algo. // path[i] = curr; // } // }//for // }//while // /* t can be anything you want */ // //int t = 5; // printPath(a[st-1], a[en-1], path); cout << endl; // } // // /* print the shortest path from s to t */ // void printPath(int s, int t, const vi &path) // { // if (t == s) { // return; // } // printPath(s, path[t], path); // cout << ans[path[t]]; // } //cout<<setprecision(13)<<n*p; // ll gcd(ll x, ll y) { // if (x == 0) return y; // if (y == 0) return x; // return gcd(y, x % y); // } // bool isprime(ll n) { // if (n <= 1) return false; // if (n <= 3) return true; // // if (n % 2 == 0 || n % 3 == 0) return false; // // for (ll i = 5; i * i <= n; i += 6) // if (n % i == 0 || n % (i+2) == 0) // return false; // // return true; // } // // bool prime[15000105]; // void sieve(int n) { // for (ll i = 0; i <= n; i++) prime[i] = 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; // } // } // prime[1] = prime[0] = 0; // } // // ll fast_power(ll b,ll p,ll m) // { // if(p==0) return 1; // if(p%2==0) // { // ll ans=fast_power(b,p/2,m); // return(ans*ans)%m; // }else{ // return (b%m*fast_power(b,p-1,m))%m; // } //} // // ll mod=1e9+7; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } // Function to return LCM of two numbers ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } ll m=1e9+7; vector<ll>ans; void genrate(ll n) { if(n>1e10)return; ans.pb(n); genrate(n*10); genrate(n*10+1); } int main() { // ofstream out("number2.out"); ifstream in("hanya.in"); ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--) { ll n; cin>>n; map<ll,ll>m; vector<ll>ans; for(int i=2;1LL*i*i<=n;i++) { while(n%i==0) { ans.pb(i); n/=i; } } if(n>1)ans.pb(n); sort(all(ans)); set<ll>st; st.insert(ans[0]); if(ans[0]==ans[1]) { st.insert(ans[1]*ans[2]); ll x=1; for(int i=3;i<ans.size();i++) x*=ans[i]; st.insert(x); }else{ st.insert(ans[1]); ll x=1; for(int i=2;i<ans.size();i++) x*=ans[i]; st.insert(x); } if(st.size()==3) { vector<ll>a; for(auto it:st)a.pb(it); if(a[0]>=2 and a[1]>=2 and a[2]>=2) { cout<<"YES\n"; for(auto it:a)cout<<it<<" "; cout<<"\n"; }else cout<<"NO\n"; }else cout<<"NO\n"; } }
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; typedef pair<int,int> pi; const int MN=8e4; int N, at=170, dist[MN], ans = MN; bool pvis[1001], vis[MN]; set<int> start; vector<int> prime, vals, adj[MN]; queue<pi> q; unordered_map<int, int> ind; // (value, index it maps to) void bfs(int r){ memset(dist, 0, sizeof(dist)); q.push({r,-1}); dist[r]=1; while(!q.empty()){ pi t = q.front(); int x=t.first, p=t.second; q.pop(); for(int nx: adj[x]) if(nx!=p && nx>=r) if(adj[nx].size()>1) { if(dist[nx]) ans=min(ans,dist[x]+dist[nx]-1); else{ dist[nx]=dist[x] + 1; q.push({nx,x}); } } } } 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.push_back(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.push_back(prime[j]); } if (vals.empty() && x == 1) { cout << 1 <<'\n'; return 0; } vals.push_back(x); if (vals.size() == 1) vals.push_back(1); for (int k: vals) if (ind.count(k) == 0) { if (k > 1e3) ind[k] = at++; else { int t=lower_bound(prime.begin(),prime.end(),k)-prime.begin(); ind[k]=t; start.insert(t); } } adj[ind[vals[0]]].push_back(ind[vals[1]]); adj[ind[vals[1]]].push_back(ind[vals[0]]); } for (int j: start) if(adj[j].size()>1) bfs(j); cout << (ans == MN ? -1 : ans) <<'\n'; }
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 <iostream> #include<bits/stdc++.h> using namespace std; #define ll long long typedef vector<int> BigInt; #define ACPC ios_base::sync_with_stdio(false); cin.tie(NULL); ll mod=1e9+7; bool PowerOfTwo(ll x){ return !(x&(x-1)); } ll FastPower(ll base,ll power) { if (power == 0) return 1; ll ans = FastPower(base, power / 2); ans *= ans; if (power % 2) ans *= base; return ans; } bool isPrime(ll v){ if(v<=1) return false; if(v==2) return true; if(v%2==0) return false; for(int i=3;i*i<=v;i+=2){ if(v%i==0) return false; } return true; } ll LCM(ll a,ll b){ return (a/ gcd(a,b))*b; } ll getGcd(ll a,ll b){ if(b==0) return a; return getGcd(b,a%b); } bool isPowerOftwo(ll x){ return !((x-1)&x); } bool sorting(int l,int r){ return l%2>r%2; } void Solution(){ ll n,m; cin>>n>>m; ll s=0; for(ll i=1;i<=n;i++){ ll x; cin>>x; s=s+x; } cout<<min(s,m)<<"\n"; } int main(){ ACPC int testcase=1; cin>>testcase; while(testcase--){ Solution(); } }
cpp
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3 7 10 50 12 1 8 OutputCopy5 InputCopy1 1 100 99 100 OutputCopy1 InputCopy7 4 2 1 1 3 5 4 2 7 6 OutputCopy6
[ "greedy", "sortings" ]
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include<fstream> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <iomanip> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> #include <random> #include <bitset> #include <fstream> #include <array> #include <functional> #include <stack> #include <memory> #define debug(x) std::cerr << __FUNCTION__ << ":" << __LINE__ << " " << #x << " = " << x << '\n'; using ll = long long; using ull = unsigned long long; using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; using namespace std; int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); ll n, a, b, c; cin >> n >> a >> b >> c; vector<ll> ar(n); for (int i = 0; i < n; i++){ cin >> ar[i]; } vector<ll> min_isp(n); for (int i = 0; i < n; i++){ ll temp = ar[i] % (a + b); if (temp == 0){ temp = a + b; } if (temp <= a) { min_isp[i] = 0; } else{ temp-=a; if (temp <= 0){ min_isp[i] = 0; } else{ min_isp[i] = min_isp[i] + (temp / a) + 1 * (temp%a != 0); } } } sort(min_isp.begin(), min_isp.end()); ll ans = 0; for (int i = 0; i < n; i++){ if (c - min_isp[i] >= 0){ ans++; c = c - min_isp[i]; } else{ break; } } cout << ans; return 0; }
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<bits/stdc++.h> using namespace std; #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define MOD 1000000007 #define MOD1 998244353 #define INF 1e18 #define nline "\n" #define pb push_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define PI 3.141592653589793238462 #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define f(i,a,b) for(long long i=a;i<=b;i++) #define fr(i,a,b) for(long long i=a;i>=b;i--) #define ain(a,n) for(ll i=0;i<n;i++)cin>>(a)[i] #define vll vector<ll> #define show(a) for(auto x:a)cout<<x<<" "; typedef long long ll; typedef unsigned long long ull; typedef long double lld; // typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key #ifndef ONLINE_JUDGE #define debug(x) cerr << #x <<" "; _print(x); cerr << endl; #else #define debug(x) #endif 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(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} #define N 50005 ll lis(vector<ll> const& a) { ll n = a.size(); vector<ll> d(n+1, INF); d[0] = -INF; for (ll i = 0; i < n; i++) { ll j = upper_bound(d.begin(), d.end(), a[i]) - d.begin(); if (d[j-1] <= a[i] && a[i] <= d[j]) d[j] = a[i]; } ll ans = 0; for (ll i = 0; i <= n; i++) { if (d[i] < INF) ans = i; } return ans; } vector<ll> sieve(ll n) { ll *arr = new ll[n + 1](); vector<ll> vect; for (ll i = 2; i <= n; i++) if (arr[i] == 0) { vect.push_back(i); for (ll j = (i * i); j <= n; j += i) arr[j] = 1; } return vect; } ll expo(ll a, ll b, ll mod) { ll res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b = b >> 1; } return res; } ll mminvprime(ll a, ll b) { return expo(a, b - 2, b); } 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; } void google(ll t) { cout << "Case #" << t << ": "; } 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; } void init_code(){ fastio(); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void solve() { ll n,m; cin>>n>>m; vector<vll> a(n,vll (m,0)); f(i,0,n-1) { f(j,0,m-1) cin>>a[i][j]; } ll ans=0; f(col,0,m-1) { map<ll,ll> mp; ll curr=col+1; f(i,0,n-1) { ll diff=curr-a[i][col]; if(diff%m==0) mp[diff/m]++; curr+=m; } if(col==1) { debug(mp) } // if(col==1) // // debug(mp) ll best=n-mp[0]; curr=col+1; f(i,0,n-2) { ll prev_diff=curr-a[i][col]; if(col==1) { debug(prev_diff) } if(prev_diff%m==0) { mp[prev_diff/m]--; mp[(prev_diff+(n-1)*m)/m+1]++; if(col==1) { debug(mp) } } if(col==1) { debug(i+1+n-mp[i+1]) } best=min(best,i+1+n-mp[i+1]); curr+=m; } ans+=best; // debug(ans) } cout<<ans<<nline; } int main() { #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); #endif init_code(); // ll t; // cin>>t; // while(t--) solve(); return 0; }
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" ]
#include <bits/stdc++.h> using namespace std; #define forn for (int i = 0; i < n; i++) #define int long long #define ed "\n" #define cyes cout << "YES\n" #define cno cout << "NO\n" #define pb push_back #define deb cout << "Hi\n" #define pint pair<int, int> const long long MOD = 1000000007; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------// void solve(){ int n; cin>>n; vector<vector<int>> adj(n+1); vector<pint> v; for(int i = 1; i < n; i++){ int x, y; cin>>x>>y; v.pb({x, y}); adj[x].pb(y); adj[y].pb(x); } int nd = -1; for(int i = 1; i <= n; i++){ if(!adj[i].empty() && adj[i].size() > 2){ nd = i; break; } } if(nd == -1){ for(int i = 0; i <= n-2; i++) cout<<i<<ed; } else{ int ct = 3; int cur = 3; for(auto val: v){ if(ct && (val.first == nd || val.second == nd)){ cout<<(ct - 1)<<ed; ct--; } else{ cout<<cur<<ed; cur++; } } } } signed main(){ std::ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin>>t; while(t--) solve(); }
cpp
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
[ "data structures", "dsu" ]
#include <vector> #include <string> #include <algorithm> #include <cmath> #include <numeric> #include <iomanip> #include <set> #include <map> #include <queue> #include <unordered_map> #include <stack> #include <cassert> #include <random> #include <iostream> using namespace std; //#define int long long typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = (int)1e9 + 7, maxn = (int)1e6, mod = (int)1e9 + 7; #define debug(x) cerr << (#x) << ": " << (x) << endl #define fastinp ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); vector<int> read_vector(int n) { vector <int> t(n); for (int i = 0; i < n; i++) { cin >> t[i]; } return t; } void cout_vector(vector <int> v) { for (auto e : v) { cout << e << ' '; } cout << endl; } int b; signed main() { fastinp; int n, m; cin >> n >> m; //vector <int> v = read_vector(n); b = ceil(sqrt(n)); vector <vector<int>> sqr/*(ceil(n * 1.0 / (b * 1.0)), vector<int>(b))*/; for (int i = 0; i < n;) { vector <int> t; for (int j = 0; i + j < n && j < b; j++) { int a; cin >> a; t.push_back(a); } i += b; sqr.push_back(t); } vector <int> next(n, 0), cnt(n, 0); //last elem is needed???? next.back() = -1; cnt.back() = 1; for (int i = (int)sqr.size() - 1; i >= 0; i--) { for (int j = (int)sqr[i].size() - 1; j >= 0; j--) { if (i * b + j + sqr[i][j] >= n) { next[i * b + j] = -1; cnt[i * b + j] = 1; } else { if ((i * b + j + sqr[i][j]) / b > i) { next[i * b + j] = i * b + j + sqr[i][j]; cnt[i * b + j] = 1; } else { next[i * b + j] = next[i * b + j + sqr[i][j]]; cnt[i * b + j] = cnt[i * b + j + sqr[i][j]] + 1; } } } } for (int _ = 0; _ < m; _++) { int t; cin >> t; if (t == 0) { int x, y; cin >> x >> y; x--; int i = x / b, j = x - x / b * b; sqr[i][j] = y; if (i * b + j + sqr[i][j] >= n) { next[i * b + j] = -1; cnt[i * b + j] = 1; } else { if ((i * b + j + sqr[i][j]) / b > i) { next[i * b + j] = i * b + j + sqr[i][j]; cnt[i * b + j] = 1; } else { next[i * b + j] = next[i * b + j + sqr[i][j]]; cnt[i * b + j] = cnt[i * b + j + sqr[i][j]] + 1; } } while (--j >= 0) { if (i * b + j + sqr[i][j] >= n) { next[i * b + j] = -1; cnt[i * b + j] = 1; } else { if ((i * b + j + sqr[i][j]) / b > i) { next[i * b + j] = i * b + j + sqr[i][j]; cnt[i * b + j] = 1; } else { next[i * b + j] = next[i * b + j + sqr[i][j]]; cnt[i * b + j] = cnt[i * b + j + sqr[i][j]] + 1; } } } } else { int x; cin >> x; x--; int count = 0, answ = x; int i = x / b, j = x - x / b * b; while (true) { if (next[answ] == -1) { count += cnt[answ]; while (answ + sqr[answ / b][answ - answ / b * b] < n) { answ += sqr[answ / b][answ - answ / b * b]; } break; } count += cnt[answ]; answ = next[answ]; } cout << answ + 1 << ' ' << count << endl; } } }
cpp
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
// Problem: D. Same GCDs // Contest: Codeforces - Educational Codeforces Round 81 (Rated for Div. 2) // URL: https://codeforces.com/problemset/problem/1295/D // Memory Limit: 256 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org) #include<bits/stdc++.h> #define pb push_back #define endl '\n' #define mod 1000000007 #define N 500005 #define vi vector<int> #define vvi vector<vector<int>> #define vb vector<bool> #define control ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define int long long int #define ffor(i, n) for(int i=0; i<n; i++) #define fforr(i, n) for(int i=1; i<=n; i++) #define rfor(i, n) for(int i=n-1; i>=0; i--) #define rforr(i, n) for(int i=n; i>0; i--) #define all(x) x.begin(), x.end() #define F first #define S second #define inf 9223372036854775807 using namespace std; void setIO() { control; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif } void print(bool chk){ if(chk){ cout << "YES" << endl; }else{ cout << "NO" << endl; } } int min(int a, int b){ return a>b?b:a; } int max(int a, int b){ return a<b?b:a; } int power(int x,int y,int p) { int ans=1; x=x%p; if(x==0) { return 0; } while(y>0) { if(y&1) { ans=(ans*x)%p; } y=y>>1; x=(x*x)%p; } return ans; } int phi(int m){ int x=2; int ans = m; while(x*x <= m){ int cnt = 0; while(m%x == 0){ m/=x; cnt++; } if(cnt)ans -= ans/x; x++; } if(m>1)ans -= ans/m; return ans; } int32_t main(){ int t; cin >> t; while(t--){ int n, m; cin >> n >> m; cout << phi(m/__gcd(n, m)) << endl; } }
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" ]
//In The Name of ALLAH #include <bits/stdc++.h> using namespace std; #define sahadat() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long int main() { sahadat(); ll t;cin>>t; while(t--){ ll n;cin>>n; cout<<1<<" "<<n-1<<endl; } return 0; }
cpp
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD = 1000000007; const ll eps = 1e-9; typedef vector<int>vi; typedef vector<ll>vl; #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(), v.rend() #define read(v,n) for(ll i=0;i<n;i++)cin>>v[i]; #define aff(v) for(int i : v) cout << i << ' '; int n , h , l , r; vi v; int helper(int i, vector<vi>& dp , int hours){ if(i == n) { if(hours <= r && hours >= l) return 1; return 0; } if(dp[i][hours] != -1) return dp[i][hours]; dp[i][hours] = 0; dp[i][hours] = max(dp[i][hours] ,helper(i + 1 , dp , (hours + v[i]) % h)); dp[i][hours] = max(dp[i][hours] ,helper(i + 1 , dp , (hours + v[i] - 1)%h)); if(hours <= r && hours >=l && i > 0) dp[i][hours]++; return dp[i][hours]; } void solve(){ cin >> n >> h >> l >> r; v.resize(n); read(v,n); vector<vi> dp(max(n ,h) ,vector<int>(max(n,h) , -1)); cout << helper(0 , dp , 0) << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int tc = 1; //cin >> tc; while(tc--)solve(); 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<iostream> #include <bits/stdc++.h> #include <ext/numeric> using namespace std; using L = __int128; #include<ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using ll = long long; using ull = unsigned long long; using ld = long double; #define nd "\n" #define all(x) (x).begin(), (x).end() #define lol cout <<"i am here"<<nd; #define py cout <<"YES"<<nd; #define pp cout <<"ppppppppppppppppp"<<nd; #define pn cout <<"NO"<<nd; #define popcount(x) __builtin_popcount(x) #define clz(n) __builtin_clz(n)//31 -x const double PI = acos(-1.0); double EPS = 1e-9; #define print2(x , y) cout <<x<<' '<<y<<nd; #define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd; #define watch(x) cout << (#x) << " = " << x << nd; template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;} //template <class Type1 , class Type2> ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v; } ll inf = 1e9 , mod= 1e9+7;//998244353;// template <typename T> using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>; const int N = 500 +20 ,LOG = 10; ll mul (ll a, ll b){ return ( ( a % mod ) * ( b % mod ) ) % mod; } ll add (ll a , ll b){ return (a + b + mod) % mod; } int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& a) { } template< typename T > using min_heap = priority_queue <T , vector <T > , greater < T > > ; // m n ll n , m; int pref [4][N][N]; int mx[N][N]; int table[N][LOG][N][LOG]; int Log[N]; ll merge (ll u ,ll v){ return max(u , v); } void build(){// zero based // rows - power of rows && cols - power of cols for (int i = 2; i <= max(n , m); ++i) Log[i] = Log[i >> 1] +1; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) table[i][0][j][0] = mx[i][j]; for (int i = 0; i < n; ++i) for (int l = 1; l < LOG; ++l) for (int j = 0; j + (1 << l)-1 < m; ++j) table[i][0][j][l] = merge(table[i][0][j][l-1] , table[i][0][j + (1 << (l-1))][l-1]); for (int k = 1; k < LOG; ++k) for (int i = 0; i + (1 << k)-1 < n; ++i) for (int l = 0; l < LOG; ++l) for (int j = 0; j + (1 << l)-1 < m; ++j) table[i][k][j][l] = merge(table[i][k-1][j][l] , table[i+ (1 << (k-1))][k-1][j][l]); } ll query(ll x1 , ll y1 , ll x2 , ll y2){// zero based if (x1 > x2 || y1 > y2 || min({x1 , x2 , y1 , y2}) <0 || max(x1 , x2) >= n || max(y1 , y2) >= m) return 0; assert(x1 >=0 && x1 <n); assert(y1 >=0 && y1 < m); assert(x2 >=0 && x2 < n &&x2 >= x1);assert(y2 >=0 &&y2 < m && y2 >= y1); ll lx = Log[x2-x1+1]; ll ly = Log[y2-y1+1]; ll prob1 = merge(table[x1][lx][y1][ly] , table[x1][lx][1 + y2- (1 << ly)][ly]); ll prob2 = merge(table[1 + x2 -(1<< lx)][lx][y1][ly] , table[1 +x2 - (1 << lx)][lx][1 + y2- (1 << ly)][ly]); // cout <<lx<<" "<<ly <<" "<<prob1 <<" "<<prob2 <<" "<<x1<<" "<<y1 <<" "<<x2<<" "<<y2 << nd; return merge(prob1 , prob2); } //vector <vector <vector <int > > > pref; vector<string > s; void build_prefix (char c , int t){ for (int i = 1; i <= n; ++i){ for (int j = 1; j <= m; ++j){ char in = s[i-1][j-1]; pref[t][i][j]+= (in == c); pref[t][i][j]+= pref[t][i-1][j]; pref[t][i][j]+= pref[t][i][j-1]; pref[t][i][j]-=pref[t][i-1][j-1]; } } } ll get (ll x1 , ll y1 , ll x2 , ll y2 , int t ){ ++x1 , ++y1 , ++x2 , ++y2; assert(x1 >=1 && x1 <=n); assert(y1 >=1 && y1 <=m); assert(x2 >=1 && x2 <= n &&x2 >= x1);assert(y2 >=1 &&y2 <= m && y2 >= y1); return pref[t][x2][y2]- pref[t][x2][y1-1] - pref[t][x1-1][y2] +pref[t][x1-1][y1-1]; } void main_(int tc){ int q; cin >> n >> m >> q; s = vector<string > (n); for (auto &i : s) cin >> i; build_prefix('R' , 0);build_prefix('G' , 1);build_prefix('Y' , 2);build_prefix('B' , 3); for (int i = 0;i < n; ++i){ for (int j = 0; j < m; ++j){ for (int k = 1; min(i , j)-k +1 >= 0 && i+k < n && j+k < m; ++k){ if (get(i-k+1 , j-k+1 , i , j , 0) != k * k) break; if (get(i-k+1 , j+1 , i , j+k , 1) != k *k) break; if (get(i+1 , j-k+1 , i+k , j , 2) != k *k) break; if (get(i+1 , j+1 , i+k , j+k , 3) != k * k) break; mx[i][j] = k; } } } build(); while (q--){ int r1 , r2 , c1 , c2; cin >> r1 >> c1 >> r2 >> c2; --r1 , --r2 , --c1 , --c2; ll s = 0 , e = n; ll ans = 0; while (s<= e){ ll m = s + e >> 1; ll nr1 = r1+m -1 , nc1 = c1 + m-1; ll nr2 = r2-m; ll nc2 = c2-m; if (query(nr1 , nc1 , nr2 , nc2) >= m) { ans = m; s = m+1; } else e = m-1; } cout << 4 * ans * ans <<nd; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); //the_best_is_still_yet_to_come(); //freopen("red2.in ","r",stdin);// freopen("output.txt","w",stdout); int tt = 1 , tc = 0; // cin>>tt; while(tt--) main_(++tc); #ifndef ONLINE_JUDGE cout << "Running Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s .\n"; #endif return 0; }
cpp
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#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, c; string s, best; cin >> t; while (t--) { cin >> n >> s; string s2 = s + s; best = s, c = 0; for (int k = 1; k < n; k++) { if (n%2 == k%2) { for (int i = 0; i < n; i++) if (s2[k+i] < best[i]) { c = k; best = s2.substr(k, n); break; } else if (s2[k+i] > best[i]) break; } else { int i = 0; for (; i < n-k; i++) { if (s2[k+i] < best[i]) { c = k; best = s2.substr(k, n-k); string s3 = s.substr(0, k); reverse(s3.begin(), s3.end()); best += s3; break; } else if (s2[k+i] > best[i]) break; } if (i < n-k) continue; for (; i<n; i++) { if (s2[n-i-1] < best[i]) { c = k; best = s2.substr(k, n-k); string s3 = s.substr(0, k); reverse(s3.begin(), s3.end()); best += s3; break; } else if (s2[n-i-1] > best[i]) break; } } } cout << best << endl; cout << c+1 << endl; } }
cpp
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3 5 7 10 19 10 18 OutputCopyYES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO NotePictures corresponding to the first and the second test cases of the example:
[ "brute force", "constructive algorithms", "trees" ]
#include <bits/stdc++.h> #include <cstdio> using namespace std; /*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<pair<long long,long long>, null_type,less<pair<long long,long long> >, rb_tree_tag,tree_order_statistics_node_update>*/ template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;}; template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for(auto &x : a) out << x << ' '; return out;}; #define mod1 (long long)998244353 #define mod2 (long long)1000000007 #define first_bit(x) (x&(-x)) #define last_bit(x) (x&~(x)) #define ll long long #define ld long double //#define int long long #define ff first #define ss second #define pb push_back #define w(x) long long x;cin>>x;while(x--) #define vi vector<long long> #define mii map<long long,long long> #define pii pair<long long,long long> #define set_bits(x) __builtin_popcountll(x) #define fast() ios_base::sync_with_stdio(false);cin.tie(NULL); #define sz(x) ((long long)x.size()) #define all(x) begin(x), end(x) #define memo(x,y) memset((x),(y),sizeof(x)); signed main(){ fast(); w(x){ int n,x; cin>>n>>x; int curr=2; map<int,int> lev; map<int,int> deg; map<int,int> par; map<int,int> is; vector<int> mx; mx.push_back(1); queue<int> q; q.push(1); while(curr<n+1){ int a=q.front(); q.pop(); if(lev[a]+1==mx.size()){mx.push_back(curr);is[curr]++;} par[curr]=a; lev[curr]=lev[a]+1; q.push(curr); x-=lev[curr++]; deg[a]++; if(curr<n+1){ par[curr]=a; lev[curr]=lev[a]+1; q.push(curr); x-=lev[curr++]; deg[a]++; } } while(x>0){ bool fd=false; for(int i=2;i<=n;i++)if(!is[i]&&deg[i]==0&&deg[mx[lev[i]]]<2){ x--; deg[mx[lev[i]]]++; deg[par[i]]--; par[i]=mx[lev[i]]; lev[i]++; if(lev[i]==mx.size()){is[i]++;mx.push_back(i);} fd=true; break; } if(!fd)break; } if(x==0){ cout<<"YES"<<endl; for(int i=2;i<=n;i++)cout<<par[i]<<" "; cout<<endl; } else cout<<"NO"<<endl; } }
cpp
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
#include <bits/stdc++.h> #pragma GCC target("sse,sse2,avx2") #pragma GCC optimize("unroll-loops,O3") #define rep(i,l,r) for (int i = l; i < r; i++) #define repr(i,r,l) for (int i = r; i >= l; i--) #define X first #define Y second #define all(x) (x).begin() , (x).end() #define pb push_back #define endl '\n' #define debug(x) cerr << #x << " : " << x << endl; using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> pll; constexpr int N = 3e5+10,mod = 998244353; constexpr ll inf = 1e18+10; inline int mkay(int a,int b){ if (a+b >= mod) return a+b-mod; // if (a+b < 0) return a+b+mod; return a+b; } inline int poww(int a,int k,int mod){ if (k < 0) return 0; int z = 1; while (k){ if (k&1) z = 1ll*z*a%mod; a = 1ll*a*a%mod; k >>= 1; } return z; } int par[N],h[N],sz[N][2],fl[N][2],fx[N]; int ans; vector<int> ve[N],adj[N]; int getpar(int v){ if (v == par[v]) return v; int p = getpar(par[v]); h[v] ^= h[par[v]]; par[v] = p; return par[v]; } int main(){ ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; string s; cin >> n >> k >> s; rep(i,0,k){ par[i] = i; sz[i][0] = 1; } rep(i,0,k){ int sz; cin >> sz; ve[i].resize(sz); rep(j,0,sz){ cin >> ve[i][j]; ve[i][j]--; adj[ve[i][j]].pb(i); } } rep(i,0,n){ if (adj[i].empty()){ cout << ans << endl; continue; } if ((int)adj[i].size() == 1){ int ind = adj[i][0],p = getpar(ind); if (fl[p][0] || fl[p][1]){ cout << ans << endl; continue; } ans -= min(sz[p][1],sz[p][0]); fx[p] = 1; if (s[i] == '1'){ ans += sz[p][1-h[ind]]; fl[p][1-h[ind]] = 1; } else{ ans += sz[p][h[ind]]; fl[p][h[ind]] = 1; } cout << ans << endl; continue; } int u = adj[i][0],v = adj[i][1]; int p1 = getpar(u),p2 = getpar(v); if (p1 == p2){ cout << ans << endl; continue; } bool d = h[u]^h[v]; if (s[i] == '0') d ^= 1; par[p1] = p2; h[p1] = d; if (fx[p2] && fx[p1]){ sz[p2][0] += sz[p1][d]; sz[p2][1] += sz[p1][1-d]; cout << ans << endl; continue; } if (fx[p2]){ ans -= min(sz[p1][0],sz[p1][1]); if (fl[p2][0]) ans += sz[p1][d]; else ans += sz[p1][1-d]; sz[p2][0] += sz[p1][d]; sz[p2][1] += sz[p1][1-d]; cout << ans << endl; continue; } if (fx[p1]){ ans -= min(sz[p2][0],sz[p2][1]); if (fl[p1][d]){ ans += sz[p2][0]; fl[p2][0] = 1; } else{ ans += sz[p2][1]; fl[p2][1] = 1; } sz[p2][0] += sz[p1][d]; sz[p2][1] += sz[p1][1-d]; cout << ans << endl; fx[p2] = 1; continue; } ans -= min(sz[p2][0],sz[p2][1]); ans -= min(sz[p1][0],sz[p1][1]); sz[p2][0] += sz[p1][d]; sz[p2][1] += sz[p1][1-d]; ans += min(sz[p2][0],sz[p2][1]); cout << ans << endl; continue; } }
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; int main() { cin.tie(0), ios::sync_with_stdio(0); int n, m; cin >> n >> m; vector<string> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i]; reverse(b[i].begin(), b[i].end()); } vector<tuple<int, int>> ps; string p; for (int i = 0; i < n; i++) { if (a[i] == b[i]) p = a[i]; for (int j = i + 1; j < n; j++) { if (a[i] == b[j]) { ps.push_back({i, j}); break; } } } int k = ps.size(); cout << (k * m * 2) + p.size() << '\n'; for (int i = 0; i < k; i++) cout << a[get<0>(ps[i])]; cout << p; for (int i = k-1; i >= 0; i--) cout << a[get<1>(ps[i])]; cout << '\n'; }
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
#include <bits/stdc++.h> #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>; map <int, int> m; priority_queue <pair <int, int>> q; pair <int, int> v[200005], aux; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for(int i = 1; i <= n; i++){ cin >> v[i].first; m[v[i].first]++; } for(int i = 1; i <= n; i++){ cin >> v[i].second; } sort(v + 1, v + n + 1); long long sol = 0; for(int i = 1; i <= n; i++){ if(m[v[i].first] > 1){ int nr = m[v[i].first], x = v[i].first; while(x - v[i].first + 1 < nr){ x++; nr += m[x]; } int y = v[i].first; for(y; y <= x; y++){ while(v[i].first <= y && i <= n){ q.push({v[i].second, v[i].first}); i++; } aux = q.top(); q.pop(); sol = sol + 1LL * aux.first * (y - aux.second); } i--; } } cout << sol; return 0; }
cpp
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
/** * author: Pratham_Shah10 * date: 10.02.2023 **/ #include<bits/stdc++.h> using namespace std; #define fastio() ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define endl "\n" #define pb push_back #define ff first #define ss second #define sz(x) ((ll)(x).size()) #define all(x) x.begin(),x.end() #define set_bits __builtin_popcountll typedef long long ll; typedef unsigned long long ull; typedef long double lld; #ifndef ONLINE_JUDGE #define debug(x) cerr << #x <<": "; _print(x); cerr << endl; #else #define debug(x) #endif 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(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.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 google(int t) {cout << "Case #" << t << ": ";} ll binexpo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} ll min(ll a, ll b) {if (a > b) return b; return a;} ll max(ll a, ll b) {if (a > b) return a; return b;} 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 gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll lcm(ll a, ll b) {return ((a * b) / (gcd(a, b)));} /* ------------------------------------------------------------------------------------------------------------------------------------------------ */ void solve() { int n; cin >> n; string s; cin >> s; int cnt = 0; while (1) { n = s.length(); char mx = 'a'; mx--; for (int i = 0; i < n; i++) { int t1 = (i + 1 < n) ? s[i] - s[i + 1] : 0; int t2 = (i - 1 >= 0) ? s[i] - s[i - 1] : 0; if (t1 == 1 || t2 == 1) { if (s[i] > mx) { mx = s[i]; } } } if (mx < 'a') { break; } for (int i = 0; i < n; i++) { if (s[i] == mx) { if (i + 1 < n && ((s[i] - s[i + 1]) == 1)) { s[i] = '-'; cnt++; } else if (i - 1 >= 0 && ((s[i] - s[i - 1]) == 1)) { s[i] = '-'; cnt++; } } } string ss; for (int i = 0; i < n; i++) { if (s[i] != '-') ss += s[i]; } s = ss; } cout << cnt << endl; } int main() { #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); #endif fastio(); solve(); }
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
#pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") // #pragma GCC target("popcnt") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2,tune=native") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2") // #pragma GCC target("avx2") #include <bits/stdc++.h> long long FLOOR(long long n, long long div) { return n >= 0 ? n / div : (n - div + 1) / div; } long long CEIL(long long n, long long div) { return n >= 0 ? (n + div - 1) / div : n / div; } #define UNIQUE(a) (a).erase(unique((a).begin(), (a).end()), (a).end()) #define UNIQUER(a) (a).resize(unique((a).begin(), (a).end()) - (a).begin()) #define prec cout << fixed << setprecision(10) #define ALLR(a) (a).rbegin(), (a).rend() #define ALL(a) (a).begin(), (a).end() // 0x3f3f3f3f using namespace std; using ll = long long; signed main() { cin.tie(NULL)->sync_with_stdio(false); cin.exceptions(cin.failbit); int n; cin >> n; vector<pair<int, int>> v(n); for (auto &[x, y] : v) cin >> x; for (auto &[x, y] : v) cin >> y; sort(ALL(v)); multiset<ll, greater<ll>> s; ll cur = -1, i = 0, sum = 0, ans = 0; while (i < n || !s.empty()) { if (s.empty()) cur = v[i].first; while (i < n && v[i].first == cur) { sum += v[i].second; s.insert(v[i].second); ++i; } sum -= *s.begin(); s.erase(s.begin()); ans += sum; ++cur; } cout << ans; return 0; }
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<iostream> #include<cstdio> #include<bitset> #include<vector> #include<math.h> #include<algorithm> #include<stack> #include<set> #include<map> #include<queue> #include<unordered_set> #include <cstring> #include <iomanip> //#include <bits/stdc++.h> #define BATSY ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define endl '\n' #define DEC(n) cout<<fixed;cout<<setprecision(n); #define LENGTH(n) (floor(log10(max(abs(n),1LL)))+1) #define log_n(number,n) log2(number)/log2(n) #define OO (ll)1e18 #define F first #define S second using namespace std; //_____________________ _____________________ //`-._ \ |\__/| / _.-' // \ \ | | / / // \ `-_______/ \_______-' / // | '||''|. | |''||''| .|'''.| '||' '| ' | // | || || ||| || ||.. ' || | | // | ||'''|. | || || ''|||. || | // / || || .''''|. || . '|| || \ // /________.||...|' .|. .||. .||. |'....|' .||.__________\ // `----._ _.----' // `--. .--' // `-. .-' // \ / // \ / // \/ bool cmp(pair<ll,ll>a,pair<ll,ll>b){ if(a.first==b.first)return a.second<b.second; return a.first<b.first; } int main(){ #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); //freopen("out.out", "w", stdout); #endif BATSY int t; cin>>t; while(t--){ ll n; cin>>n; vector<pair<ll,ll>>v(n); pair<ll,ll>pos={0,0}; for(int i=0;i<n;i++){ cin>>v[i].first>>v[i].second; } sort(v.begin(),v.end(),cmp); bool f=1; string pth; for(int i=0;i<n;i++){ if(pos.first>v[i].first||pos.second>v[i].second){ f=0; break; } for(int j=0;j<v[i].first-pos.first;j++){ pth.push_back('R'); } for(int j=0;j<v[i].second-pos.second;j++){ pth.push_back('U'); } pos=v[i]; } if(f)cout<<"YES\n"<<pth<<endl; else cout<<"NO\n"; } }
cpp
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
#define llt long long i using namespace std; //s //h #include<vector> //w //a #include<map> //a //r #include<list> //r //s #include<set> //a //h #include<algorithm> //j //i #include<queue> //t #include<cstring> #include<cmath> #include<bitset> #include<string> #include<cstdlib> #include<bits/stdc++.h> #define ll long long #define input(a,n) for(int i=0;i<n;i++)cin>>a[i]; #define w(t) while(--t >= 0)nt #define ss second #define endl '\n'ios_base::sync_with_stdio(false); #define pb push_back int main() { ll t; cin>>t; while(t--) { ll n,b; cin>>n; ll a[2*n]; input(a,2*n); sort(a,a+2*n); b=a[n]-a[n-1]; cout<<b<<'\n'; } }
cpp
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <array> #include <unordered_map> #include <unordered_set> #include <iomanip> #include <chrono> #include <random> #define ld long double #define ll long long using namespace std; void solve() { int n, m, k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } if (m <= k) { int mx = 0; for (int i = 0; i < m; i++) { mx = max(mx, max(a[i], a[n-i-1])); } cout << mx << endl; return; } int v = m - k - 1; int ans = 0; for (int i = 0; i <= k; i++) { int mn = 1e9; for (int j = 0; j <= v; j++) { int b = max(a[i+j], a[i+j+n-m]); mn = min(mn, b); } ans = max(ans, mn); } cout << ans << endl; } int main() { int t = 1; cin >> t; for (int i = 0; i < t; i++) { //cout << "Case #" << i +1 << ": \n"; solve(); } }
cpp
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
#include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define Ta7a ios_base::sync_with_stdio(false);cout.tie(NULL);cin.tie(NULL); // EL_MEXICY using namespace std; int main() { Ta7a; ll t = 1; cin >> t; while (t--) { string s;cin >>s; int cnt = 0,res = 0; if (s.size() == 1) { if (s[0] =='L')cout << "2\n"; else cout << "1\n"; continue; } if(s[0]=='L') res = 1; for (int i = s.size()-1; i > 0;i--){ cnt = 0; while (s[i] == 'L'){ cnt++; i--; } res = max(res,cnt); } cout << res+1 << '\n'; } }
cpp
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
[ "implementation", "math" ]
#include <bits/stdc++.h> using namespace std; #pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") // Datatypes Begin #define int long long int #define double long double #define longlong long long #define __int64 int // Datatypes End // Constants Begin #define PI 3.14159265358979323846264338327950288419716939937510l const string PI_string = "314159265358979323846264338327950288419716939937510"; const int MAX_N = 1e5 + 5, MOD = 1e9 + 7, INF = 1e9, EPS = 1e-9; // Constants End // Definitions Begin void fast_io() { ios::sync_with_stdio(false); ios_base::sync_with_stdio(0); cin.tie(0); cin.tie(NULL); cout.tie(0); cout.tie(NULL); } #define all(a) a.begin(), a.end() void fix_prec(int prec) { cout << fixed << setprecision(prec); } // Definitions End // Custom Structs and Classes Begin struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; // Custom Structs and Classes End // Functions Begin void open_file(string input, string output) { freopen(input.c_str(), "r", stdin); freopen(output.c_str(), "w", stdout); } void usaco(string filename) { freopen((filename + ".in").c_str(), "r", stdin); freopen((filename + ".out").c_str(), "w", stdout); } template <typename T> T gcd(T a, T b) { return (b ? __gcd(a, b) : a); } template <typename T> T lcm(T a, T b) { return (a * (b / gcd(a, b))); } unordered_map<int, int, custom_hash> factorials; int factorial(int n) { if (n < 0) return 0; if (n <= 1) return 1; if (factorials.find(n) != factorials.end()) return factorials[n]; return factorials[n] = (n * factorial(n - 1)); } int nCr(int n, int r) { return factorial(n) / (factorial(r) * factorial(n - r)); } int nPr(int n, int r) { return factorial(n) / factorial(n - r); } template<typename T> T power(T a, T n, T mod) { T power = a, result = 1; while (n) { if (n & 1) { result = (result * power) % mod; } power = (power * power) % mod; n >>= 1; } return result; } template<typename T> bool witness(T a, T n) { int t, u, i; std::int64_t prev, curr; u = n / 2; t = 1; while (!(u & 1)) { u /= 2; ++t; } prev = power(a, u, n); for (i = 1; i <= t; ++i) { curr = (prev * prev) % n; if ((curr == 1) && (prev != 1) && (prev != n - 1)) { return true; } prev = curr; } if (curr != 1) { return true; } return false; } template<typename T> bool is_prime(T number) { if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) return false; if (number < 1373653) { for (int k = 1; 36 * k * k - 12 * k < number; ++k) if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) return false; return true; } if (number < 9080191) { if (witness(std::int64_t(31), number)) return false; if (witness(std::int64_t(73), number)) return false; return true; } if (witness(std::int64_t(2), number)) return false; if (witness(std::int64_t(7), number)) return false; if (witness(std::int64_t(61), number)) return false; return true; } // GEO template <typename T> inline T PointDistanceHorVer(T x1, T y1, T x2, T y2) { return abs(x1 - x2) + abs(y1 - y2); } template <typename T > inline T PointDistanceDiagonally(T x1, T y1, T x2, T y2) { return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } template <typename T > inline T PointDistanceMinimum(T x1, T y1, T x2, T y2) { T tmp1 = abs(x1 - x2), tmp2 = abs(y1 - y2), tmp3 = abs(tmp1 - tmp2), tmp4 = min(tmp1, tmp2); return tmp3 + tmp4; } template <typename T> inline T PointDistance3D(T x1, T y1, T z1, T x2, T y2, T z2) { return sqrt(square(x2 - x1) + square(y2 - y1) + square(z2 - z1)); } template <typename T> inline T Cube(T a) { return a * a * a; } template <typename T> inline T RectengularPrism(T a, T b, T c) { return a * b * c; } template <typename T> inline T Pyramid(T base, T height) { return (1 / 3) * base * height; } template <typename T> inline T Ellipsoid(T r1, T r2, T r3) { return (4 / 3) * PI * r1 * r2 * r3; } template <typename T> inline T IrregualarPrism(T base, T height) { return base * height; } template <typename T> inline T Sphere(T radius) { return (4 / 3) * PI * radius * radius * radius; } template <typename T> inline T CylinderB(T base, T height) { return base * height; } template <typename T> inline T CylinderR(T radius, T height) { return PI * radius * radius * height; } template <typename T> inline T Cone(T radius, T base, T height) { return (1 / 3) * PI * radius * radius * height; } // Functions End void solve(int tt = 0) { int n, m; cin >> n >> m; if (m % n != 0) { cout << -1 << endl; return; } if (m == n) { cout << 0 << endl; return; } int a = m / n, ans = 0; while (a != 1) { if (a % 2 == 0) { a /= 2; ans++; } else if (a % 3 == 0) { a /= 3; ans++; } else { cout << -1 << endl; return; } // cout << "DEBUG: " << a << endl; } cout << ans << endl; } int32_t main(void) { fast_io(); #ifdef test_cases int tc = 1; cin >> tc; for (int t = 1; t <= tc; t++) solve(t); #else solve(); #endif } /* By Thamognya Kodi ▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓ ░░▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓░░ ░░▓▓░░░░▓▓▓▓ ▓▓ ▒▒▓▓░░ ▓▓░░░░░░░░░░░░▓▓░░░░▓▓ ▒▒░░ ░░░░░░░░░░░░░░░░▓▓▓▓▒▒ ▓▓░░░░░░░░░░░░░░░░░░░░▓▓░░▓▓ ██████████ ▒▒▓▓░░░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░▓▓ ██████ ██████ ▓▓▓▓▓▓▓▓▓▓▓▓▒▒ ▒▒▒▒▒▒▓▓▓▓ ████ ████████▓▓▓▓▓▓▓▓▓▓▒▒ ▒▒ ▒▒▓▓ ████ ██████░░ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ██████████░░ ░░░░░░██░░░░░░████ ██████████ ██░░░░░░░░░░▒▒░░░░░░▒▒██ ██████████ ██░░░░░░░░░░░░░░░░░░░░██ ██████████ ████░░░░░░░░░░░░░░░░██ ██████ ████░░░░░░▒▒▒▒░░██ ████ ██▓▓██░░░░░░░░██ ████ ████████▓▓▓▓████████ ██ ████▓▓▓▓▓▓████████▓▓██████ ██ ████▓▓▓▓▓▓▓▓▓▓██████▓▓██▓▓▓▓██ ▓▓████▓▓▓▓██▓▓▓▓▓▓▓▓██▓▓██▓▓██▓▓▓▓ ████████▓▓▓▓██▓▓▓▓▓▓▓▓██▓▓██▓▓██▓▓██ ██▓▓▓▓▓▓▓▓████████████████▓▓██████▓▓██ ██▓▓██▓▓▓▓████▒▒░░░░ ░░░░▓▓██▒▒██▓▓██ ██▓▓▓▓██████████▒▒ ░░░░ ▓▓██▒▒██▓▓████ ██▓▓▓▓▓▓████ ██▒▒░░ ░░░░▓▓██▒▒▒▒██████ ██▓▓▓▓▓▓▓▓██ ██▒▒░░░░ ▓▓██▒▒▒▒██▓▓██ ██▓▓▓▓▓▓▓▓██ ██▒▒░░░░░░░░░░░░▓▓██▒▒██▓▓██ ██▓▓▓▓████▓▓██ ████▒▒░░ ░░░░▓▓██▒▒██▓▓▓▓██ ██▓▓██░░░░██ ████████▓▓▓▓▓▓▓▓████████▓▓▓▓████ ██░░░░████ ████████████████████████▓▓████░░████ ██░░░░░░░░██ ██▒▒░░░░░░░░░░░░░░░░████▓▓██░░░░░░░░██ ██░░░░░░░░░░██ ██░░ ░░░░░░░░░░░░░░░░████░░░░░░░░██ ██░░░░░░░░░░██ ██▒▒░░░░ ░░░░██░░░░░░████░░░░░░██ ██░░░░░░░░██ ██▒▒ ▒▒▒▒▒▒░░░░░░██░░░░░░░░████████ ████████ ██████ ▒▒▒▒████░░████░░░░██ ██ ████▒▒██ ████▒▒▒▒▒▒▒▒░░██ ██░░░░░░ ▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░░░██ ██░░░░░░▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░░░░░░░▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒░░░░██ ██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░░░░░▒▒▒▒▒▒██ ██▒▒▒▒▒▒▒▒░░██ ██░░▒▒▒▒▒▒██ ████████████ ████████████ ████████ ██▓▓▓▓████ ██▓▓▓▓██ ████████████ ██▓▓██████████ ██▓▓▓▓▓▓▓▓██ ██▓▓▓▓▓▓▓▓▓▓▓▓████ ██▓▓▓▓▓▓▓▓▓▓██ ██████▓▓▓▓▓▓░░░░░░██ ██▓▓░░░░░░░░████ ██████████████ ██████████████ */
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" ]
// #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") // #pragma GCC optimize("unroll-loops") #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; #ifdef LOCAL #include "debug.h" #else #define dbg(...) 42 #endif #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 forn(i,n) rep(i,0,(n)) #define rof(i,n) per(i,(n)-1,0) #define ff first #define ss second #define mp make_pair #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define endl "\n" #define int long long #define ll long long #define pii pair<int,int> #define setbits(x) __builtin_popcountll(x) #define pqb priority_queue<int> // maxheap #define pqs priority_queue<int,vector<int>,greater<int>> // minheap #define piipqs priority_queue<pii,vector<pii>,greater<pii>> // minheap for pair<int,int> #define piipqb priority_queue<pii> // maxheap for pair<int,int> #define mod 1000000007 // #define mod 998244353 #define memt(a) memset(a,true,sizeof(a)) #define memf(a) memset(a,false,sizeof(a)) #define mem0(a) memset(a,0,sizeof(a)) #define mem1(a) memset(a,-1,sizeof(a)) #define meminf(a) memset(a,0x7f,sizeof(a)) #define precise(x,y) fixed<<setprecision(y)<<x #define FIO ios_base::sync_with_stdio(0); cin.tie(0) #define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());} #define NO {cout<<"NO"<<endl; return;} #define YES {cout<<"YES"<<endl; return;} #define NEG1 {cout<<"-1"<<endl; return;} // #define oset tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> // set // #define osetpii tree<pii, null_type,less<pii>, rb_tree_tag,tree_order_statistics_node_update> //like multiset mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // for long long use mt19937_64 and usage - just do rng() typedef tuple<int, int> tpl; const ll inf = 2e18; //2e18 const double epsilon = 1e-7; template<typename T, typename T1>T amax(T &a, T1 b) {if (b > a)a = b; return a;} template<typename T, typename T1>T amin(T &a, T1 b) {if (b < a)a = b; return a;} inline ll gcd(ll a, ll b) {return (b == 0) ? a : gcd(b, a % b);} int mypow(int x, int y) { x%=mod; int res = 1; while (y) { if (y & 1) res = (res * x) % mod; x = (x * x) % mod; y >>= 1; } return res; } int dx[] = { -1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; // **************************** Code Begins **************************** // void solve() { int n,m; cin>>n>>m; int a[n][m]; forn(i,n) { forn(j,m) { cin>>a[i][j]; a[i][j]--; } } int ans=0; forn(j,m) { map<int,int> f; forn(i,n) { if(a[i][j]%m!=j || a[i][j]>=n*m) continue; int row=a[i][j]/m; // dbg(i,j,row); if(row<=i) f[i-row]++; else f[n+i-row]++; } int mx=n; for(auto p:f) amin(mx,p.ff+n-p.ss); ans+=mx; // dbg(j,mx); } cout<<ans<<endl; } signed main() { FIO; int tt = 1; // cin >> tt; for (int i = 1; i <= tt; i++) solve(); }
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" ]
#pragma GCC optimize("O3,unroll-loops") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace chrono; using namespace __gnu_pbds; #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define MOD 1000000007 #define MOD1 998244353 #define INF 1e18 #define nline "\n" #define pb push_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define PI 3.141592653589793238462 #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #ifdef tushar23 #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; #else #define debug(x); #endif typedef long long ll; typedef unsigned long long ull; typedef long double lld; typedef __int128 ell; typedef tree<pair<ll, ll>, null_type, less<pair<ll, ll>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key 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(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} void _print(pbds v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); /*---------------------------------------------------------------------------------------------------------------------------*/ ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3 ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} bool revsort(ll a, ll b) {return a > b;} ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;} void google(int t) {cout << "Case #" << t << ": ";} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} 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);} /*--------------------------------------------------------------------------------------------------------------------------*/ void solve() { ll n; cin>>n; ll arr[n]; ll sum = 0; for(int i=0; i<n; i++){ cin>>arr[i]; sum += arr[i]; } ll mx = LONG_MIN; ll currsm = 0; for(int i=0; i<n-1; i++){ currsm += arr[i]; if(currsm > mx) mx = currsm; if(currsm < 0) currsm = 0; } currsm = 0; for(int i=1; i<n; i++){ currsm += arr[i]; if(currsm > mx) mx = currsm; if(currsm < 0) currsm = 0; } if(sum > mx) cout<<"Yes"<<endl; else cout<<"No"<<endl; } int main() { #ifdef tushar23 freopen("Error.txt", "w", stderr); #endif fastio(); auto start1 = high_resolution_clock::now(); int t; cin>>t; while(t--){ solve(); } auto stop1 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop1 - start1); #ifdef tushar23 cerr << "Time: " << duration . count() / 1000 << endl; #endif }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
#pragma GCC optimize ("O3") #pragma GCC target ("sse4") #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt") #include <bits/stdc++.h> #define f first #define s second #define mp make_pair #define pb push_back #define all(x) (x).begin(), (x).end() #define sz(x) ((int) (x).size()) using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vp = vector <pii>; using vl = vector<ll>; const int inf = INT_MAX; const ll linf = LLONG_MAX; int main() { int n; scanf("%d", &n); vi primes; vi spf(5001), w(5001); vector <vi> info(5001); for(int i = 2; i <= 5000; i++) { if(!spf[i]) { primes.pb(i); for(int j = i; j <= 5000; j += i) spf[j] = i; } } vi rel, a(n); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); if(a[i] == 0) a[i] = 1; if(!w[a[i]]) rel.pb(a[i]); w[a[i]]++; } reverse(all(primes)); for(int v : rel) { for(int p : primes) { int x = v; int r = 0; while(x) { r += x / p; x /= p; } info[v].pb(r); } } vector <vi> ancestor_info; sort(all(rel), [&](int u, int v) { return info[u] < info[v]; }); for(int v : rel) { ancestor_info.pb(info[v]); } auto lca = [&](vi &u, vi &v) -> vi { vi ret(sz(primes), 0); for(int i = 0; i < sz(primes); i++) { if(u[i] == v[i]) { ret[i] = u[i]; } else { ret[i] = min(u[i], v[i]); break; } } return ret; }; for(int i = 1; i < sz(rel); i++) { vi lca_info = lca(info[rel[i - 1]], info[rel[i]]); ancestor_info.pb(lca_info); } sort(all(ancestor_info)); ancestor_info.resize(unique(all(ancestor_info)) - begin(ancestor_info)); vi sub(sz(ancestor_info)); vector <vp> adj(sz(ancestor_info)); auto lb = [&](vi &v_info) -> int { return lower_bound(all(ancestor_info), v_info) - begin(ancestor_info); }; for(int v : rel) { sub[lb(info[v])] += w[v]; } for(int i = 1; i < sz(ancestor_info); i++) { vi lca_info = lca(ancestor_info[i - 1], ancestor_info[i]); int w = 0; for(int j = 0; j < sz(primes); j++) { w += ancestor_info[i][j] - lca_info[j]; } adj[lb(lca_info)].pb({i, w}); } vl below(sz(ancestor_info)); ll ans = linf; auto dfs1 = [&](auto &&self, int u) -> void { for(auto [v, w] : adj[u]) { self(self, v); sub[u] += sub[v]; below[u] += below[v] + 1ll * sub[v] * 1ll * w; } }; dfs1(dfs1, 0); auto dfs2 = [&](auto &&self, int u, ll above) -> void { for(auto [v, w] : adj[u]) { self(self, v, above + below[u] - (below[v] + 1ll * sub[v] * 1ll * w) + 1ll * (n - sub[v]) * 1ll * w); } ans = min(ans, below[u] + above); }; dfs2(dfs2, 0, 0); printf("%lld\n", ans); return 0; }
cpp
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
#include <bits/stdc++.h> using namespace std; #ifndef ONLINE_JUDGE #define dbg(x) \ cerr << #x << " "; \ _print(x); \ cerr << endl; #else #define dbg(x) ; #endif typedef long long ll; 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(double t) { cerr << t; } template <class T, class V> void _print(pair<T, V> p); template <class T> void _print(vector<T> v); template <class T> void _print(set<T> v); template <class T, class V> void _print(map<T, V> v); template <class T> void _print(multiset<T> v); template <class T, class V> void _print(pair<T, V> p) { cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}"; } template <class T> void _print(vector<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T> void _print(set<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T> void _print(multiset<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T, class V> void _print(map<T, V> v) { cerr << "[ "; for (auto i : v) { _print(i); cerr << " "; } cerr << "]"; } void solve() { ll n; cin >> n; ll arr[2 * n]; for (int i = 0; i < 2 * n; i++) cin >> arr[i]; sort(arr, arr + 2*n); cout << arr[n] - arr[n - 1] << endl; } int main() { #ifndef ONLINE_JUDGE freopen("inputf.txt", "r", stdin); freopen("outputf.txt", "w", stdout); freopen("errorf.txt", "w", stderr); #endif int t; cin >> t; while (t--) { solve(); } return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t; cin>>t; while(t--) { ll n; cin>>n; ll arr1[n], arr2[n]; for(ll i = 0; i < n; i++) cin>>arr1[i]; for(ll i = 0; i < n; i++) cin>>arr2[i]; sort(arr1, arr1 + n); sort(arr2, arr2 + n); for(ll i = 0; i < n; i++) cout<<arr1[i]<<" "; cout<<"\n"; for(ll i = 0; i < n; i++) cout<<arr2[i]<<" "; cout<<"\n"; } }
cpp
1284
F
F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4 1 2 2 3 4 3 1 3 2 4 1 4 OutputCopy3 3 2 4 2 2 1 1 3 4 3 1 4 InputCopy5 1 2 2 4 3 4 4 5 1 2 1 3 1 4 1 5 OutputCopy4 2 1 1 2 3 4 1 3 4 2 1 4 5 4 1 5 InputCopy9 7 9 2 8 2 1 7 5 4 7 2 4 9 6 3 9 1 8 4 8 2 9 9 5 7 6 1 3 4 6 5 3 OutputCopy8 4 2 9 2 9 7 6 7 5 7 5 9 6 9 4 6 8 2 8 4 3 9 3 5 2 1 1 8 7 4 1 3
[ "data structures", "graph matchings", "graphs", "math", "trees" ]
// LUOGU_RID: 102062552 #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> using namespace std; typedef pair<int,int> P; const int N=3e5+5; struct edge{ int v,nx; }e[N<<1],g[N<<1]; int n,ne,cnt,fe[N],fg[N],p[N],sz[N],son[N],deep[N],fa[N],top[N],id[N],rev[N]; vector<P> fv,gv; void read(edge *eg,int *f,int u,int v) { eg[++ne]=(edge){v,f[u]}; f[u]=ne; } int find(int x) { if(x==p[x])return x; return p[x]=find(p[x]); } void dfs(int u,int ffa) { deep[u]=deep[ffa]+1,fa[u]=ffa,sz[u]=1; for(int i=fe[u];i;i=e[i].nx) { int v=e[i].v; if(v==ffa)continue; dfs(v,u),sz[u]+=sz[v]; if(sz[v]>sz[son[u]])son[u]=v; } } void dfs2(int u,int tops) { top[u]=tops,id[u]=++cnt,rev[cnt]=u; if(son[u])dfs2(son[u],tops); for(int i=fe[u];i;i=e[i].nx) { int v=e[i].v; if(v!=fa[u]&&v!=son[u])dfs2(v,v); } } void lca(int u,int v) { while(top[u]!=top[v]) { if(deep[top[u]]<deep[top[v]])gv.push_back(make_pair(id[top[v]],id[v])),v=fa[top[v]]; else fv.push_back(make_pair(id[top[u]],id[u])),u=fa[top[u]]; } if(deep[u]<deep[v])gv.push_back(make_pair(id[u],id[v])); else fv.push_back(make_pair(id[v],id[u])); } void link(int u,int v) { printf("%d %d ",rev[u],rev[v]); p[find(u)]=find(v); } void del(int u,int v) { fv.clear(),gv.clear(),lca(u,v),reverse(gv.begin(),gv.end()); int h=0,fl=0,oo=find(id[u]); for(auto k:fv) { int l=k.first,r=k.second; if(find(r)!=oo)link(r,h),fl=1; if(!fl&&find(l)!=oo) { for(int i=18;i>=0;i--)if(r-(1<<i)>l&&find(r-(1<<i))==oo)r-=(1<<i); link(r,r-1),fl=1; } if(fl){printf("%d %d\n",u,v);return;} h=l; } for(auto k:gv) { int l=k.first,r=k.second; if(find(l)!=oo)link(l,h),fl=1; if(!fl&&find(r)!=oo) { for(int i=18;i>=0;i--)if(l+(1<<i)<r&&find(l+(1<<i))==oo)l+=(1<<i); link(l,l+1),fl=1; } if(fl){printf("%d %d\n",u,v);return;} h=r; } } void solve(int u,int ffa) { for(int i=fg[u];i;i=g[i].nx) { int v=g[i].v; if(v!=ffa)solve(v,u); } if(ffa)del(u,ffa); } int main() { scanf("%d",&n); for(int i=1,u,v;i<n;i++) { scanf("%d%d",&u,&v); read(e,fe,u,v),read(e,fe,v,u); } ne=0; for(int i=1,u,v;i<n;i++) { scanf("%d%d",&u,&v); read(g,fg,u,v),read(g,fg,v,u); } for(int i=1;i<=n;i++)p[i]=i; dfs(1,0),dfs2(1,1); printf("%d\n",n-1); solve(1,0); return 0; }
cpp
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int #define ss string #define loop1(i,n) for(ll i=0;i<n;++i) #define loop2(i,n) for(ll i=n-1;i>=0;--i) #define loop3(i,a,b) for(ll i=a;i<b;i++) #define loop4(i,a,b) for(ll i=a;i>=b;i--) #define NO cout<<"NO"<<endl; #define YES cout<<"YES"<<endl; #define No cout<<"No"<<endl; #define Yes cout<<"Yes"<<endl; #define out(x) cout<<x<<endl; int main() { ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0); ll n,m;cin>>n>>m;ll ans=0; vector<ll>dp(255001,1); for(ll i=1;i<255000;i++) { dp[i]=(dp[i-1]*i)%m; } for(ll i=1;i<=n;i++) { ll p=dp[n-i+1]; p*=dp[i]; p%=m; p*=(n-i+1); p%=m; ans+=p; ans%=m; } cout<<ans<<endl; }
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; #define ll long long #define ull unsigned long long //#define endl '\n' #define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); void dfs(int u, int fa, vector<int>& depth, vector<vector<int>>& f, vector<vector<int>>& g){ depth[u] = depth[fa] + 1; f[u][0] = fa; for (auto v : g[u]){ if (v == fa) continue; dfs(v, u, depth, f, g); } } int LCA(int x, int y, vector<int>& depth, vector<vector<int>>& f){ if (depth[x] < depth[y]) swap(x, y); for (int i = 19; i >= 0; i--){ if (depth[f[x][i]] >= depth[y]) x = f[x][i]; } if (x == y) return x; for (int i = 19; i >= 0; i--){ if (f[x][i] != f[y][i] && f[x][i] != 0 && f[y][i] != 0){ x = f[x][i]; y = f[y][i]; } } return f[x][0]; } int get(int x, int k, vector<vector<int>>& f){ for (int i = 19; i >= 0; i--){ if (k >= (1 << i)){ x = f[x][i]; k -= (1 << i); } } return x; } int find(int x, vector<int>& fa){ if (fa[x] == x) return x; return fa[x] = find(fa[x], fa); } int main(){ IOS; int n, k, r; cin>>n>>k>>r; int n1 = n + n - 1; vector<vector<int>> g(n1 + 10); for (int i = 1; i < n; i++){ int u, v; cin>>u>>v; g[u].push_back(n + i); g[n + i].push_back(u); g[v].push_back(n + i); g[n + i].push_back(v); } vector<vector<int>> f(n1 + 10, vector<int> (20)); vector<int> depth(n1 + 10); dfs(1, 0, depth, f, g); for (int i = 1; i <= 19; i++){ for (int j = 1; j <= n1; j++){ f[j][i] = f[f[j][i - 1]][i - 1]; } } vector<int> dist(n1 + 10, -1); queue<int> q; for (int i = 1; i <= r; i++){ int x; cin>>x; q.push(x); dist[x] = 0; } vector<int> fa(n1 + 10); for (int i = 1; i <= n1; i++){ fa[i] = i; } while (!q.empty()){ int u = q.front(); q.pop(); if (dist[u] == k) break; for (auto v : g[u]){ int fu = find(u, fa), fv = find(v, fa); fa[fu] = fv; if (dist[v] == -1){ dist[v] = dist[u] + 1; q.push(v); } } } int t; cin>>t; while (t--){ int x, y; cin>>x>>y; int lca = LCA(x, y, depth, f); int len = depth[x] - depth[lca] + depth[y] - depth[lca]; if (len <= 2 * k){ cout << "YES" << endl; continue; } int x1, y1; if (depth[x] - depth[lca] >= k){ x1 = get(x, k, f); } else x1 = get(y, len - k, f); if (depth[y] - depth[lca] >= k) y1 = get(y, k, f); else y1 = get(x, len - k, f); if (find(x1, fa) == find(y1, fa)) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include <bits/stdc++.h> using namespace std; int t,n,a[101],b[101]; int main() { cin >> t; while(t--){ cin >> n; for(int i=1; i<=n; ++i){ cin >> a[i]; } for(int i=1; i<=n; ++i){ cin >> b[i]; } sort(a+1, a+n+1); sort(b+1, b+n+1); for(int i=1; i<=n; ++i){ cout << a[i] << ' '; } cout << endl; for(int i=1; i<=n; ++i){ cout << b[i] << ' '; } cout << endl; } 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" ]
// LUOGU_RID: 101244776 #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
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; int i,n,k,x,y,d[200200],e[200200]; vector<int> a[200200],A[200200]; void dfs(int t,int w,int s){ for (int i=0;i<a[t].size();i++) if (a[t][i]!=w) e[A[t][i]]=(++s>d[n-k])?s=1:s,dfs(a[t][i],t,s); return ; } int main(){ scanf("%d %d",&n,&k); for (i=1;i<n;i++){ scanf("%d %d",&x,&y); a[x].push_back(y);A[x].push_back(i); a[y].push_back(x);A[y].push_back(i); d[x]++;d[y]++; } sort(d+1,d+1+n);dfs(1,0,0); printf("%d\n",d[n-k]); for (i=1;i<n;i++) printf("%d ",e[i]); return 0; }
cpp
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
#include <bits/stdc++.h> #define N 2505 using namespace std; typedef long long ll; template <typename T> inline void read(T &num) { T x = 0, f = 1; char ch = getchar(); for (; ch > '9' || ch < '0'; ch = getchar()) if (ch == '-') f = -1; for (; ch <= '9' && ch >= '0'; ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ '0'); num = x * f; } const int inf = 0x3f3f3f3f; int n, m, Q; int head[N], pre[N<<1], to[N<<1], flow[N<<1], cost[N<<1], sz = 1; vector<int> A, B; inline void addedge(int u, int v, int w, int c) { pre[++sz] = head[u]; head[u] = sz; to[sz] = v; flow[sz] = w; cost[sz] = c; pre[++sz] = head[v]; head[v] = sz; to[sz] = u; flow[sz] = 0; cost[sz] = -c; } queue<int> q; int dis[N], vis[N], lst[N]; bool SPFA() { for (int i = 1; i <= n; i++) dis[i] = inf, vis[i] = lst[i] = 0; dis[1] = 0; vis[1] = 1; q.push(1); while (!q.empty()) { int x = q.front(); q.pop(); vis[x] = 0; for (int i = head[x]; i; i = pre[i]) { int y = to[i]; if (!flow[i]) continue; if (dis[y] > dis[x] + cost[i]) { dis[y] = dis[x] + cost[i]; lst[y] = i; if (!vis[y]) vis[y] = 1, q.push(y); } } } return dis[n] != inf; } void mincost() { int F = 0, C = 0; while (SPFA()) { int Fl = inf; for (int i = n; i != 1; i = to[lst[i]^1]) Fl = min(Fl, flow[lst[i]]); F += Fl; for (int i = n; i != 1; i = to[lst[i]^1]) { C += Fl * cost[lst[i]]; flow[lst[i]] -= Fl; flow[lst[i]^1] += Fl; } A.push_back(F); B.push_back(C); } } int main() { read(n); read(m); for (int i = 1, u, v, w; i <= m; i++) { read(u); read(v); read(w); addedge(u, v, 1, w); } mincost(); read(Q); for (int i = 1, x; i <= Q; i++) { read(x); double ans = 1e12; for (int j = 0; j < A.size(); j++) { ans = min(ans, (B[j]+x)*1.0/A[j]); } printf("%.10f\n", ans); } 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<iostream> #include<cstring> #include<vector> #include<map> #include<queue> #include<unordered_map> #include<cmath> #include<cstdio> #include<algorithm> #include<set> #include<cstdlib> #include<stack> #include<ctime> #define forin(i,a,n) for(int i=a;i<=n;i++) #define forni(i,n,a) for(int i=n;i>=a;i--) #define fi first #define se second using namespace std; typedef long long ll; typedef double db; typedef pair<int,int> PII; const double eps=1e-7; const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[N]; void solve() { n=read(); for(int i=1;i<=n;i++) w[i]=read(); int idx=0; int i=1; while(i<=n&&w[i]>=idx) idx++,i++; if(w[i]==w[i-1]&&idx-1==n-i) { printf("No\n"); return ; } idx=n-i; while(i<=n&&w[i]>=idx) idx--,i++; if(i>n) printf("Yes\n"); else printf("No\n"); } int main() { // init(); // stin(); scanf("%d",&T); // T=1; while(T--) solve(); return 0; }
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> #ifdef ONPC #include "t_debug.cpp" #else #define debug(...) 42 #endif using namespace std; //namespace pbds = __gnu_pbds; using ll = long long; const int inf = 1e9; const ll infl = 1e18; const int RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count(); mt19937 rng(RANDOM); template<typename T, typename U> istream& operator>>(istream& is, pair<T, U>& p) { return is >> p.first >> p.second; } template<typename Cont> int sz(const Cont& cont) { return int(cont.size()); } const string fileio = ""; constexpr int tests = 0, nmax = 2e5, nlog = __lg(nmax), mod = 1e9+7; int nextPower2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return 1+n; } struct SegmentTree { // TO CHANGE struct Node { // defaults int sum = 0; int value = 0; bool marked = false; template<typename T> void apply(const T& newval, int l, int r) { // update value = newval; sum = (r - l + 1) * value; marked = true; } friend ostream& operator<<(ostream& os, const Node& v) { os << "{" << v.sum; if (v.marked) os << " !" << v.value; return os << "}"; } }; void push(int v, int l, int r) { if (tree[v].marked) { int mid = (l + r) / 2; int vl = v * 2, vr = v * 2 + 1; tree[vl].apply(tree[v].value, l, mid); tree[vr].apply(tree[v].value, mid+1, r); tree[v].marked = false; } } Node merge(const Node& l, const Node& r) { return Node{l.sum + r.sum}; } int n; vector<Node> tree; // CONSTRUCTION SegmentTree(int n) : n(nextPower2(n)) { tree.resize(this->n * 2); build(1, 0, n-1); } template<typename T> SegmentTree(vector<T> arr) : n(nextPower2(arr.size())) { tree.resize(n * 2); for (int i = 0; i < arr.size(); i++) { // leaves int v = n + i; tree[v].apply(arr[i], i, i); } build(1, 0, n-1); } void build(int v, int l, int r) { if (l == r) return; int mid = (l + r) / 2; int vl = v * 2, vr = v * 2 + 1; build(vl, l, mid); build(vr, mid+1, r); tree[v] = merge(tree[vl], tree[vr]); } // INTERNALS template<typename T> void update(int qi, const T& qval, int v, int l, int r) { if (l == r) { tree[v].apply(qval, l, r); return; } push(v, l, r); int mid = (l + r) / 2; int vl = v * 2, vr = v * 2 + 1; if (qi <= mid) update(qi, qval, vl, l, mid); else update(qi, qval, vr, mid+1, r); tree[v] = merge(tree[vl], tree[vr]); } template<typename T> void update(int ql, int qr, const T& qval, int v, int l, int r) { if (ql <= l && r <= qr) { tree[v].apply(qval, l, r); return; } push(v, l, r); int mid = (l + r) / 2; int vl = v * 2, vr = v * 2 + 1; if (ql <= mid) update(ql, qr, qval, vl, l, mid); if (mid+1 <= qr) update(ql, qr, qval, vr, mid+1, r); tree[v] = merge(tree[vl], tree[vr]); } Node query(int ql, int qr, int v, int l, int r) { if (ql <= l && r <= qr) return tree[v]; push(v, l, r); int mid = (l + r) / 2; int vl = v * 2, vr = v * 2 + 1; if (qr <= mid) return query(ql, qr, vl, l, mid); if (mid+1 <= ql) return query(ql, qr, vr, mid+1, r); return merge(query(ql, qr, vl, l, mid), query(ql, qr, vr, mid+1, r)); } // INTERFACE template<typename T> void update(int i, const T& val) { update(i, val, 1, 0, n-1); } template<typename T> void update(int l, int r, const T& val) { update(l, r, val, 1, 0, n-1); } Node query(int l, int r) { return query(l, r, 1, 0, n-1); } }; int solve() { int n; cin >> n; if (!cin) return 1; vector<pair<int,int>> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i].first >> a[i].second >> b[i].first >> b[i].second; } map<int,int> comp; for (auto [i, j] : a) comp[i] = comp[j] = 0; for (auto [i, j] : b) comp[i] = comp[j] = 0; int k = 0; for (auto& i : comp) i.second = k++; for (auto& [i, j] : a) i = comp[i], j = comp[j]; for (auto& [i, j] : b) i = comp[i], j = comp[j]; debug(a); debug(b); bool res = true; for (int rev = 0; rev < 2; rev++) { vector<tuple<int,int,int,int>> q; q.reserve(2*n); for (int i = 0; i < n; i++) { q.emplace_back(a[i].first, 1, b[i].first, b[i].second); q.emplace_back(a[i].second+1, 0, b[i].first, b[i].second); } sort(q.begin(), q.end()); SegmentTree tree(k); for (auto [y, t, a, b]: q) { if (t == 1) { if (tree.query(a, b).sum) res = false; } else { tree.update(a, b, 1); } } swap(a, b); } cout << (res ? "YES\n" : "NO\n"); return 0; } signed main() { int t = 1; #ifdef ONPC t = 10000; #else if (fileio.size()) {freopen((fileio+".in").c_str(),"r",stdin);freopen((fileio+".out").c_str(),"w",stdout);} #endif cin.tie(0)->sync_with_stdio(0); if (tests) cin >> t; while (t-- && cin) { if (solve()) break; #ifdef ONPC cout << "____________________" << endl; #endif } return 0; } /* █████ █████ ███ ████ ▒▒███ ▒▒███ ▒▒▒ ▒▒███ ███████ ████████ ███████ ████ ▒███ █████ ████ ██████ ████████ ███▒▒███ ▒▒███▒▒███ ███▒▒███ ▒▒███ ▒███ ▒▒███ ▒███ ███▒▒███▒▒███▒▒███ ▒███ ▒███ ▒███ ▒▒▒ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒▒▒ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒███ ▒▒████████ █████ ▒▒████████ █████ █████ ▒▒███████ ▒▒██████ █████ ▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒███ ▒▒▒▒▒▒ ▒▒▒▒▒ ███ ▒███ ▒▒██████ ▒▒▒▒▒▒ */
cpp
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
[ "graphs", "hashing", "math", "number theory" ]
// LUOGU_RID: 95932192 #include<bits/stdc++.h> using namespace std; #define int long long int const N=5e5+10; int c[N]; set<int>a[N]; map< set<int>,int >mp; inline void solve(){ mp.clear(); int n,m;cin>>n>>m; for (int i=1;i<=n;++i) cin>>c[i],a[i].clear(); while (m--){ int u,v;cin>>u>>v; a[v].insert(u); } for (int i=1;i<=n;++i) if (!a[i].empty()) mp[a[i]]+=c[i]; int res=0; for (auto i:mp) res=__gcd(res,i.second); cout<<res<<'\n'; return; } signed main(){ ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int t;cin>>t; while (t--) 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" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define mod 1e9 + 7 void solve(){ string s; cin >> s; vector<ll> cnt(26); vector<vector<ll>> dp(26ll, vector<ll>(26)); for(int i=0; i<s.size(); ++i){ int x = s[i] - 'a'; for(int j=0; j<26; ++j){ dp[j][x] += cnt[j]; } cnt[x]++; } ll res = 0; for(int i=0; i<26; ++i){ res = max(res, cnt[i]); } for(int i=0; i<26; ++i){ for(int j=0; j<26; ++j){ res = max(res, dp[i][j]); } } cout << res << "\n"; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); //#ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); //#endif ll t = 1; //cin >> t; while(t--){ solve(); } return 0; }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> #include <random> #include <bitset> #include <array> // #include <bits/stdc++.h> using namespace std; using ll = long long; using lld = long double; using ull = unsigned long long; using vll = vector<ll>; using pll = pair<ll, ll>; using vpll = vector<pll>; #ifndef ONLINE_JUDGE #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; #else #define debug(x) ((void)0); #endif #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define loop(i,k,n) for(ll i = k; i < n;i++) #define MOD 1000000007 #define MOD1 998244353 #define nl "\n" #define pb push_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define PI 3.141592653589793238462 #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define UNIQUE(X) X.erase(unique(all(X)),X.end()) const ll INF = 1e18; template<class A> void read(vector<A>& v); template<class T> void read(T& x) { cin >> x; } template<class H, class... T> void read(H& h, T&... t) { read(h); read(t...); } template<class A> void read(vector<A>& x) { for (auto& a: x) read(a); } template<class A> void read1(vector<A>& x) { for(ll i = 1; i <= sz(x) - 1; i++){ read(x[i]); } } 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(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } void google(int t) {cout << "Case #" << t << ": ";} ll mul(ll a, ll b, ll m) { if (a < (1 << 14)) { return (a * b) % m; } ll c = mul(a >> 14, b, m); c <<= 14; c %= m; c = (c + (a % (1 << 14)) * b) % m; return c; } ll fast_power(ll p, ll e, ll m) { if (e == 0) { return 1 % m; } if (e % 2 == 0) { return fast_power(mul(p, p, m), e / 2, m); } else { return mul(fast_power(p, e - 1, m), p, m); } } // #define N 200005 // change N here // vector<vll> adjl(N); // vll visited(N); // ll n, m; // vector<ll> adj[N]; // void dfs(ll u){ // visited[u] = 1; // for(ll v: adj[u]){ // if(!visited[v]){ // dfs(v); // } // } // } // vll dist; // void bfs(ll s) { // dist.assign(n + 1, -1); // n must be defined(i.e global) // queue<ll> q; // dist[s] = 0; q.push(s); // while (q.size()) { // ll u = q.front(); q.pop(); // for (ll v : adj[u]) { // if (dist[v] == -1) { // dist[v] = dist[u] + 1; // q.push(v); // } // } // } // } // const ll maxn = 1000; // set maxn accordingly // ll C[maxn + 1][maxn + 1]; // void makenCr(){ // C[0][0] = 1; // for (ll n = 1; n <= maxn; ++n) { // C[n][0] = C[n][n] = 1; // for (ll k = 1; k < n; ++k) // C[n][k] = C[n - 1][k - 1] + C[n - 1][k]; // // C[n][k] %= MOD; // } // } ll nbit(ll x, ll i){ return ((x >> i) & 1ll); } void solve(){ ll n; cin >> n; vll v(n); read(v); ll AND = 1; for(auto x: v) AND = (AND & (~x)); ll idx = 0; for(ll k = 30; k >= 0; k --){ ll cnt = 0; loop(i, 0, n){ if(nbit(v[i], k)){ cnt++; idx = i; } } if(cnt == 1) break; } cout << v[idx] << " "; ll f = 1; for(auto x: v){ if(x == v[idx] && f) f = 0; else cout << x << " "; } cout << nl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); cout << "---------------------" << nl; cout << "OUTPUT:" << nl; freopen("error.txt", "w", stderr); #endif int t = 1; // cin>>t; for(ll i = 1; i <= t; i ++) { // google(i); solve(); // cout << "\n"; } return 0; }
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 <iostream> #include <ranges> #include <algorithm> #include <numeric> #include <vector> #include <array> #include <set> #include <map> #include <bit> #include <sstream> #include <list> #include <stack> #include <queue> #include <cmath> typedef long long integerType; typedef integerType z; typedef std::vector<integerType> v; typedef std::vector<v> V; typedef std::set<integerType> s; typedef std::multiset<integerType> S; typedef std::string r; typedef std::vector<r> R; typedef std::vector<bool> b; struct RHEXAOCrocks { RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); } template<class T> operator T() const { T n; std::cin >> n; return n; } std::string operator()() { std::string s; std::cin >> s; return s; } v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; } R operator()(integerType n, char del) { R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c; for (integerType i{}; i < n;++i) while ((c = std::cin.get()) != del) vec[i].push_back(c); return vec; } V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; } template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; } RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) { for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) { for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this; } }o; #define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__) #define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__) #define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__) #define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__) #define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A) #define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B) #define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C) #define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D) #define z(a) (integerType)((a).size()) #define ff(...) auto f = [&](__VA_ARGS__, const auto& f) #define f(...) f(__VA_ARGS__, f) #define gg(...) auto g = [&](__VA_ARGS__, const auto& g) #define g(...) g(__VA_ARGS__, g) #define hh(...) auto h = [&](__VA_ARGS__, const auto& h) #define h(...) h(__VA_ARGS__, h) using namespace std; namespace ra = ranges; inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); } inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); } z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; } #define w(...) if(__VA_ARGS__) #define _ else #define W(...) while(__VA_ARGS__) #define A(...) for(auto __VA_ARGS__) #define O while(true) void solve_test_case() { z n{ o }; vector<pair<z, z>> a(n + 1); a[0] = { (z)0, (z)0 }; i(1, n + 1) a[i] = { (z)o, (z)o }; ra::sort(a); r r{ "YES\n" }; i(1, n + 1) if (a[i].second < a[i - 1].second) { o["NO\n"]; return; } else r += string(a[i].first - a[i - 1].first, 'R') + string(a[i].second - a[i - 1].second, 'U'); o[r]['\n']; } int main() { z t{ o }; while (t--) solve_test_case(); }
cpp
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
#include<bits/stdc++.h> using namespace std; #define X ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define int long long void solve() { int n, m; cin >> n >> m; string s; cin >> s; vector<int> arr(n); int one = 0; int zero = 0; for (int e = 0; e < n; e++) { if (s[e] == '0')zero++; else one++; arr[e] = zero - one; } int ans = 0; if (m == 0)ans++; int ans1 = 0; for (int e = 0; e < n; e++) { if (s[e] == '0')ans1++; else ans1--; if (ans1 == m && arr[n - 1] == 0) { ans = -1; break; } if (ans1 == m || (((m - ans1) * arr[n - 1] > 0) && ((m - ans1) % arr[n - 1] == 0)))ans++; } cout << ans << "\n"; } int32_t main() { X; int t; cin >> t; while (t--) { solve(); } 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<iostream> #include<vector> #include<cmath> #include<map> #include<unordered_map> #include<unordered_set> #include<set> #include<string> #include<stack> #include<algorithm> #include<bitset> #include<queue> #include<iomanip> #include<cstring> #include <numeric> #include <functional> using namespace std; typedef long long ll; const ll mod=998244353; typedef pair<int,int> pi; vector<pi> f(int val,vector<int>&v,int n){ unordered_map<int,int>p; int sum=0; p[0]=-1; vector<int>dp(n); vector<pi>ans; vector<int>a(n,-1); for(int i=0;i<n;i++){ sum+=v[i]; if(p.count(sum-val)){ if(i==0||(p[sum-val]==-1&&dp[i-1]==0)) ans.push_back(pi(0,i)); else if(p[sum-val]!=-1&&dp[p[sum-val]]+1>dp[i-1]) ans.push_back(pi(p[sum-val]+1,i)); if(p[sum-val]==-1) { if(i==0) dp[i]=1; else dp[i]=max(dp[i-1],1); }else{ dp[i]=max(dp[i-1],dp[p[sum-val]]+1); } }else dp[i]=(i==0?0:dp[i-1]); p[sum]=i; } return ans; } void solve(){ int n; cin>>n; vector<int>v(n); for(int i=0;i<n;i++) cin>>v[i]; map<int,int>p; for(int i=0;i<n;i++){ int sum=0; for(int j=i;j<n;j++){ sum+=v[j]; p[sum]++; } } int res=0; vector<pi>ans; for(auto i:p){ vector<pi>k=f(i.first,v,n); if(k.size()>res){ res=k.size(); ans=k; } } cout<<res<<endl; for(auto i:ans){ cout<<i.first+1<<" "<<i.second+1<<endl; } } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); solve(); system("pause"); }
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> # define ll long long # define fi first # define se second using namespace std; int n, m , k; vector<pair<int, int>> fac; int sub[40003], cub[40003]; void factors(ll a) { for(int i=1; i<=sqrt(a); i++) { if(a%i==0) { if(i<=n && (a/i)<=m) { fac.push_back({i, a/i}); } if(i!=a/i) { if(a/i<=n && i<=m) { fac.push_back({a/i, i}); } } } } } int main() { cin >> n >> m >> k; factors(k); int last=1; for(int i=1; i<=n; i++) { int x; cin >> x; if(x==0) { int p=i-last; for(int j=1; j<=p; j++) { sub[j]+=p-j+1; } last=i+1; } if(i==n && x==1) { int p=i-last+1; for(int j=1; j<=p; j++) { sub[j]+=p-j+1; } } } last=1; for(int i=1; i<=m; i++) { int x; cin >> x; if(x==0) { int p=i-last; for(int j=1; j<=p; j++) { cub[j]+=p-j+1; } last=i+1; } if(i==m && x==1) { int p=i-last+1; for(int j=1; j<=p; j++) { cub[j]+=p-j+1; } last=i+1; } } ll ans=0; for(int i=0; i<fac.size(); i++) { ans+=(sub[fac[i].fi]*cub[fac[i].se]); } cout << ans << endl; }
cpp
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0); cin.tie(0) #define ff first #define ss second #define pb push_back #define pf push_front #define all(s) s.begin(),s.end() typedef long long ll; const double pi = acos(-1),ef=1e-9; const ll N=100+5,M=1e9+7; ll n,a[N],mm[N][N][N][2]; ll rec(ll i,ll one,ll zero,ll lst) { if(i>n){ return 0; } ll &ans=mm[i][one][zero][lst]; if(ans!=-1)return ans; ans=1e15; if(a[i]==-1){ if(one>0){ ans=min(ans,(lst!=1)+rec(i+1,one-1,zero,1)); } if(zero>0){ ans=min(ans,(lst!=0)+rec(i+1,one,zero-1,0)); } } else{ ans=min(ans,(lst!=a[i])+rec(i+1,one,zero,a[i])); } return ans; } void solve() { memset(mm,-1,sizeof mm); ll c[2]={0}; cin>>n; set<ll>st; for(ll i=1;i<=n;i++){ cin>>a[i]; if(a[i]==0){ a[i]=-1; //cout<<a[i]<<' '; continue; } st.insert(a[i]); a[i]%=2; } for(ll i=1;i<=n;i++){ if(st.count(i))continue; c[i%2]++; } //for(auto p:st)cout<<p<<' '; //cout<<c[0]<<' '<<c[1]<<"\n"; ll ans=1e18; ans=min(ans,rec(1,c[1],c[0],0)); ans=min(ans,rec(1,c[1],c[0],1)); cout<<ans<<"\n"; } int main() { fast; ll t=1,tc=1; // cin>>tc; while(tc--){ solve(); } }
cpp
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
#include<bits/stdc++.h> using namespace std; int main(){ int T; long long n,d; for(cin>>T;T--;puts(((ceil(sqrt(d)*2)<=n+1)?("YES"):("NO"))))cin>>n>>d; }
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<iostream> #include<cstdio> #include<bitset> #include<vector> #include<math.h> #include<algorithm> #include<stack> #include<set> #include<map> #include<queue> #include<unordered_set> #include <cstring> #include <iomanip> //#include <bits/stdc++.h> #define BATSY ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define endl '\n' #define DEC(n) cout<<fixed;cout<<setprecision(n); #define LENGTH(n) (floor(log10(max(abs(n),1LL)))+1) #define log_n(number,n) log2(number)/log2(n) #define OO (ll)1e18 #define F first #define S second using namespace std; //_____________________ _____________________ //`-._ \ |\__/| / _.-' // \ \ | | / / // \ `-_______/ \_______-' / // | '||''|. | |''||''| .|'''.| '||' '| ' | // | || || ||| || ||.. ' || | | // | ||'''|. | || || ''|||. || | // / || || .''''|. || . '|| || \ // /________.||...|' .|. .||. .||. |'....|' .||.__________\ // `----._ _.----' // `--. .--' // `-. .-' // \ / // \ / // \/ int main(){ #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); //freopen("out.out", "w", stdout); #endif BATSY int t; cin>>t; while(t--){ vector<ll>v(3);ll n; for(int i=0;i<3;i++)cin>>v[i]; sort(v.begin(),v.end()); cin>>n; bool f=1; for(int i=0;i<3;i++){ ll dif=v[2]-v[i]; if(n>=dif){ v[i]+=dif; n-=dif; } else f=0; } if(!f)cout<<"NO\n"; else if(n%3)cout<<"NO\n"; else cout<<"YES\n"; } }
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" ]
/** * Created by megurine on 2023/02/09 09:14:06. * 诸天神佛,佑我上分! **/ #include <bits/stdc++.h> using namespace std; #define fastIO() ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr) #define itr(it) begin(it), end(it) typedef long long ll; typedef pair<int, int> PII; typedef double db; typedef long double ld; typedef unsigned uint; typedef unsigned long long ull; #define endl '\n' #define YES() void(cout << "YES\n") #define NO() void(cout << "NO\n") template<typename T> void chmax(T &a, T b) { if (b > a) a = b; } template<typename T> void chmin(T &a, T b) { if (b < a) a = b; } void elysia() { int n; cin >> n; vector<int> a(n); for (auto &x: a) cin >> x; map<int, int> g; vector<map<int, int>> f(n); for (int j = n - 1; j >= 0; --j) { for (int i = j, p = 0; i >= 0; --i) { p += a[i]; chmax(f[i][p], g.count(p) ? g[p] + 1 : 1); } for (auto &[x, y]: f[j]) chmax(g[x], y); } int mx = 0, mv = 0; for (auto &[x, y]: g) { if (y > mx) mx = y, mv = x; } cout << mx << endl; map<int, int> mp; mp[0] = 0; vector<int> f1(n + 1); for (int i = 0, p = 0; i < n; ++i) { p += a[i]; f1[i + 1] = f1[i]; if (mp.count(p - mv)) { int cur = mp[p - mv] ? f1[mp[p - mv]] + 1 : 1; if (cur > f1[i + 1]) { f1[i + 1] = cur; cout << mp[p - mv] + 1 << ' ' << i + 1 << endl; } } mp[p] = i + 1; } } int main() { #ifdef MEGURINE #define fr(x) freopen(x, "r", stdin) #define fw(x) freopen(x, "w", stdout) fr("../input.txt"); fw("../output.txt"); clock_t start = clock(); #endif fastIO(); int T = 1; // cin >> T; cout << fixed << setprecision(12); while (T--) { elysia(); } cout.flush(); #ifdef MEGURINE clock_t end = clock(); cout << "\n\nRunning Time : " << (double) (end - start) / CLOCKS_PER_SEC * 1000 << "ms" << endl; #endif return 0; }
cpp
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
#include<bits/stdc++.h> using namespace std; const int MAXN = 2.1e5; int N, M, K; vector<int> adj[MAXN]; int dist[MAXN][2]; int A[MAXN]; pair<int, int> val[MAXN]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> N >> M >> K; for (int i = 0; i < K; i++) { cin >> A[i]; A[i]--; } for (int e = 0; e < M; e++) { int x, y; cin >> x >> y; x--, y--; adj[x].push_back(y); adj[y].push_back(x); } for (int z = 0; z < 2; z++) { for (int i = 0; i < N; i++) dist[i][z] = -1; int st = z ? N-1 : 0; vector<int> q; q.reserve(N); dist[st][z] = 0; q.push_back(st); for (int t = 0; t < int(q.size()); t++) { int cur = q[t]; for (int nxt : adj[cur]) { if (dist[nxt][z] != -1) continue; dist[nxt][z] = dist[cur][z]+1; q.push_back(nxt); } } } for (int i = 0; i < K; i++) { val[i] = pair<int, int>(dist[A[i]][0] - dist[A[i]][1], dist[A[i]][1]); } sort(val, val + K); for (int i = 0; i < K; i++) { val[i].first += val[i].second; } // want to maximize val[i].first + val[j].second + 1 int ans = 0; int bestFirst = -1; for (int i = 0; i < K; i++) { if (i) { ans = max(ans, min(dist[N-1][0], bestFirst + val[i].second + 1)); } bestFirst = max(bestFirst, val[i].first); } cout << ans << '\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" ]
#ifdef local #define _GLIBCXX_DEBUG 1 #endif #pragma GCC optimize("Ofast", "unroll-loops") #include <bits/stdc++.h> using namespace std; #define int int64_t #define double long double using pii = pair<int, int>; template <typename T> using Prior = std::priority_queue<T>; template <typename T> using prior = std::priority_queue<T, vector<T>, greater<T>>; // #define X first // #define Y second #define eb emplace_back #define ef emplace_front #define ee emplace #define pb pop_back #define pf pop_front #define ALL(x) begin(x), end(x) #define RALL(x) rbegin(x), rend(x) #define SZ(x) ((int)(x).size()) template <size_t D, typename T> struct Vec : vector<Vec<D-1, T>> { static_assert(D >= 1, "Vector dimension must be greater than zero!"); template <typename... Args> Vec(int n = 0, Args... args) : vector<Vec<D-1, T>>(n, Vec<D-1, T>(args...)) {} }; template <typename T> struct Vec<1, T> : vector<T> { Vec(int n = 0, const T& val = T()) : vector<T>(n, val) {} }; #ifdef local #define fastIO() void() #define debug(...) \ _color.eb("\u001b[31m"), \ fprintf(stderr, "%sAt [%s], line %d: (%s) = ", _color.back().c_str(), __FUNCTION__, __LINE__, #__VA_ARGS__), \ _do(__VA_ARGS__), _color.pop_back(), \ fprintf(stderr, "%s", _color.back().c_str()) deque<string> _color{"\u001b[0m"}; template <typename T> concept is_string = is_same_v<T, string&> or is_same_v<T, const string&>; template <typename T> concept is_iterable = requires (T _t) {begin(_t);}; template <typename T> inline void _print_err(T &&_t); template <typename T> inline void _print_err(T &&_t) requires is_iterable<T> and (not is_string<T>); template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(const tuple<U...> &); template <size_t I = 0, typename ...U> inline typename enable_if<I < sizeof...(U), void>::type _print_err(const tuple<U...> &_t); template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(tuple<U...> &); template <size_t I = 0, typename ...U> inline typename enable_if<I < sizeof...(U), void>::type _print_err(tuple<U...> &_t); template <typename T, typename U> ostream& operator << (ostream &os, const pair<T, U> &_tu); inline void _do() {cerr << "\n";}; template <typename T> inline void _do(T &&_t) {_print_err(_t), cerr << "\n";} template <typename T, typename ...U> inline void _do(T &&_t, U &&..._u) {_print_err(_t), cerr << ", ", _do(_u...);} #else #define fastIO() ios_base::sync_with_stdio(0), cin.tie(0) #define debug(...) void() #endif mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); inline int getRand(int L, int R) { if (L > R) swap(L, R); return (int)(rng() % ((uint64_t)R - L + 1) + L); } template <typename T, typename U> bool chmin(T &lhs, U rhs) {return lhs > rhs ? lhs = rhs, 1 : 0;} template <typename T, typename U> bool chmax(T &lhs, U rhs) {return lhs < rhs ? lhs = rhs, 1 : 0;} void solve() { int N, X, Y; cin >> N >> X >> Y; int min_place = min(max(X+Y-N, (int)0) + 1, N); int max_place = min(X+Y-1, N); cout << min_place << " " << max_place << "\n"; } int32_t main() { fastIO(); int t = 1; cin >> t; for (int _ = 1; _ <= t; ++_) { // cout << "Case #" << _ << ": "; solve(); } return 0; } /// below are Fast I/O and _print_err templates /// /* /// Fast I/O by FHVirus /// /// https://fhvirus.github.io/blog/2020/fhvirus-io/ /// #include <unistd.h> const int S = 65536; int OP = 0; char OB[S]; inline char RC() { static char buf[S], *p = buf, *q = buf; return p == q and (q = (p = buf) + read(0, buf, S)) == buf ? -1 : *p++; } inline int RI() { static char c; int a; while (((c = RC()) < '0' or c > '9') and c != '-' and c != -1); if (c == '-') { a = 0; while ((c = RC()) >= '0' and c <= '9') a *= 10, a -= c ^ '0'; } else { a = c ^ '0'; while ((c = RC()) >= '0' and c <= '9') a *= 10, a += c ^ '0'; } return a; } inline void WI(int n, char c = '\n') { static char buf[20], p; if (n == 0) OB[OP++] = '0'; p = 0; if (n < 0) { OB[OP++] = '-'; while (n) buf[p++] = '0' - (n % 10), n /= 10; } else { while (n) buf[p++] = '0' + (n % 10), n /= 10; } for (--p; p >= 0; --p) OB[OP++] = buf[p]; OB[OP++] = c; if (OP > S-20) write(1, OB, OP), OP = 0; } /// Fast I/O by FHVirus /// /// https://fhvirus.github.io/blog/2020/fhvirus-io/ /// */ #ifdef local template <typename T> inline void _print_err(T &&_t) {cerr << _t;} template <typename T> inline void _print_err(T &&_t) requires is_iterable<T> and (not is_string<T>) { string _tmp_color = _color.back(); ++_tmp_color[3], _color.eb(_tmp_color); cerr << _color.back() << "["; for (bool _first = true; auto &_x : _t) { if (!_first) cerr << ", "; _print_err(_x), _first = false; } cerr << "]" << (_color.pb(), _color.back()); } template <typename T, typename U> ostream& operator << (ostream &os, const pair<T, U> &_tu) { string _tmp_color = _color.back(); ++_tmp_color[3], _color.eb(_tmp_color); cerr << _color.back() << "("; _print_err(_tu.first), cerr << ", ", _print_err(_tu.second); cerr << ")" << (_color.pb(), _color.back()); return os; } template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(const tuple<U...> &) { cerr << ")" << (_color.pb(), _color.back()); } template <size_t I = 0, typename ...U> inline typename enable_if<I < sizeof...(U), void>::type _print_err(const tuple<U...> &_t) { if (!I) { string _tmp_color = _color.back(); ++_tmp_color[3], _color.eb(_tmp_color); cerr << _color.back(); } cerr << (I ? ", " : "("), _print_err(get<I>(_t)), _print_err<I+1, U...>(_t); } template <size_t I = 0, typename ...U> inline typename enable_if<I == sizeof...(U), void>::type _print_err(tuple<U...> &) { cerr << ")" << (_color.pb(), _color.back()); } template <size_t I = 0, typename ...U> inline typename enable_if<I < sizeof...(U), void>::type _print_err(tuple<U...> &_t) { if (!I) { string _tmp_color = _color.back(); ++_tmp_color[3], _color.eb(_tmp_color); cerr << _color.back(); } cerr << (I ? ", " : "("), _print_err(get<I>(_t)), _print_err<I+1, U...>(_t); } #endif
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; typedef long long int ll; typedef string str; typedef long double ld; typedef vector<ll> vll; typedef pair<ll,ll> pll; typedef vector<pair<ll,ll>> vpll; #define en "\n" #define pb push_back #define popb pop_back #define F first #define S second #define in insert #define mp make_pair #define f(i,n) for(ll i=0;i<n;i++) #define all(x) (x).begin(), (x).end() int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } bool comp(pair<ll,ll> &a, pair<ll,ll>&b) { if(a.first!=b.first) { return (a.first>b.first); } else{ return(a.second<b.second); } } int deleteElement(int arr[], int n, int x) { int i; for (i=0; i<n; i++) if (arr[i] == x) break; if (i < n) { n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1]; } return n; } bool isPalindrome(string S) { string P = S; reverse(P.begin(), P.end()); if (S == P) { return true; } else { return false; } } ll highestPowerof2(ll n) { ll res = 0; for (ll i=n; i>=1; i--) { // If i is a power of 2 if ((i & (i-1)) == 0) { res = i; break; } } return res; } // Returns true if s1 is substring of s2 int isSubstring(string s1, string s2) { int M = s1.length(); int N = s2.length(); /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (s2[i + j] != s1[j]) break; if (j == M) return i; } return -1; } /*Returns true if s1 is subsequence of s2*/ bool issubsequence(string& s1, string& s2) { int n = s1.length(), m = s2.length(); int i = 0, j = 0; while (i < n && j < m) { if (s1[i] == s2[j]) i++; j++; } /*If i reaches end of s1,that mean we found all characters of s1 in s2, so s1 is subsequence of s2, else not*/ return i == n; } bool isSquare(int x) { int y=sqrt(x); return y*y==x; } bool isVowel(char c) { return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U'); } bool isprime(int n) { if(n==1) return false; else { bool f=true; for(int i=2;i*i<=n;i++){ if(n%i==0) { f=false; break; } } return f; } } vector <ll> prime_factors(ll n) { vector<ll> p; for(ll i=2;i*i<=n;i++) { while(n%i==0) { p.pb(i); n/=i; } } if(n>1) p.pb(n); return p; } const int M=1e9+7; int binExpItr(int a,int b) // cal a^b assuming a,b<1e9 { int ans=1; while(b) { if(b&1) //checking set bit { ans=(ans*1LL*a)%M; } a=(a*1LL*a)%M; b>>=1; } return ans; } const int N=200004; vector<int> isPrime(N+1,1); const int Mo=1e9+7; vector <ll> Fact(1000006); int binExp(int a,ll b,int m) { int ans=1; while(b>0) { if(b&1) { ans=(ans*1LL*a)%m; } a=(a*1LL*a)%m; b>>=1; } return ans; } bool sortByval(pair<int,int> &a,pair<int,int> &b) { if(a.S!=b.S) return(a.S<b.S); else return(a.F<b.F); } vector <int> lc(23,0); ll func(ll n) { if(n==1) return 1; else return n+func(n/2); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); // int l=1; // for(int i=1;i<23;i++) // { // l=(l*i)/gcd(l,i); // lc[i]=l; // } // // int f=1; // for(ll i=1;i<1000006;i++) // { // f=(f*1LL*i)%Mo; // Fact[i]=f; // // } isPrime[0]=isPrime[1]=1; for(int i=2;i*i<=N;i++) { if(isPrime[i]==1) { for(int j=2*i;j<=N;j+=i) isPrime[j]=0; } } //int t=1; int t; cin>>t; while(t--) { ll n; cin>>n; vector<pair<ll,ll>> v; f(i,n) { ll x,y; cin>>x>>y; v.pb(mp(y,x)); } sort(all(v)); bool f=true; for(ll i=1;i<n;i++) { if(v[i].F!=v[i-1].F) { if(v[i].S<v[i-1].S) { f=false; break; } } } if(f) { cout<<"YES"<<en; str ans; for(ll i=0;i<(v[0].S);i++) { ans.pb('R'); } for(ll i=0;i<(v[0].F);i++) ans.pb('U'); for(ll i=1;i<n;i++) { for(ll j=0;j<(v[i].S-v[i-1].S);j++) ans.pb('R'); for(ll j=0;j<(v[i].F-v[i-1].F);j++) ans.pb('U'); } cout<<ans; } else cout<<"NO"; cout<<en; } 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; using vi = vector<int>; int main() { cin.tie(0), ios::sync_with_stdio(0); int t, n, x; cin >> t; while (t--) { cin >> n; int m = n+1, M = -1; for (int i = 0; i < n; i++) { cin >> x; if (x - i < 0) m = min(m, i); if (x - (n - i - 1) < 0) M = max(M, i); } cout << (m - M > 1 ? "Yes\n" : "No\n"); } }
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" ]
//Athour : 7amok4a #include <ext/pb_ds/assoc_container.hpp> #include <bits/stdc++.h> using namespace __gnu_pbds; using namespace std; typedef long long ll; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define mod_mul(a,b,m) ((a%m)*(b%m))%m #define mod_add(a,b,m) ((a%m)+(b%m))%m #define mod_sub(a,b,m) ((a%m)-(b%m))%m #define gcd(a,b) __gcd(a, b) #define lcm(a,b) a/__gcd(a, b )*b #define fixed(n) cout<<fixed<<setprecision(n) #define all(x) x.begin(),x.end() #define el "\n" int dx[] = { -1, 0, 0, 1, -1, -1, 1, 1}; int dy[] = { 0, 1, -1, 0, -1, 1, 1, -1}; const ll N = 100, M = 100 , mod = 1e9 + 7 , OO = 2 * 1e9 , OOLL = 6 * 1e18,sz=1e6+1; const double pi=3.1415926535897932384626433832795028841971693993751058; #ifndef ONLINE_JUDGE #include "debug.h" #else #define debug(...) #endif //\//\//\//\//\//\//\//\//\//\//\//\//\//\//\// void A7med_YU(){ ll n; cin>>n; vector<ll>v(n+5); vector<ll>pref(n+7); for(ll i=1;i<=n;++i){ cin>>v[i]; } for(ll i=1;i<=n;++i){ pref[i]=pref[i-1]+v[i]; } for(ll i=1;i<=n;i++){ if(pref[i]<=0) return void(cout<<"NO"<<el); } for(ll i=1;i<n;++i){ if(pref[i]>=pref[n])return void(cout<<"NO"<<el); } cout<<"YES"<<el; } int32_t main() { #ifndef ONLINE_JUDGE Matter(); #endif ll t = 1; cin >> t; while (t--) { A7med_YU(); } #ifndef ONLINE_JUDGE end_clock(); #endif }
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 int long long signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector <pair <pair <int, int>, int > > events, events1; vector <pair <int, int> > qw(n); vector <pair <int, int> > qw1(n); for(int i = 0; i < n; i++) { int l, r, l1, r1; cin >> l >> r >> l1 >> r1; qw[i] = {l1, r1}; qw1[i] = {l, r}; events1.push_back({{l1, -1}, i}); events1.push_back({{r1, 1}, i}); events.push_back({{l, -1}, i}); events.push_back({{r, 1}, i}); } sort(events1.begin(), events1.end()); sort(events.begin(), events.end()); set <pair <int, int> > t1; set <pair <int, int> > t2; for(int i = 0; i < events.size(); i++) { int l1 = qw[events[i].second].first; int r1 = qw[events[i].second].second; set <pair <int, int> > :: iterator it; it = t1.upper_bound({r1, n * 2}); if(it != t1.end()) { cout << "NO"; return 0; } it = t2.upper_bound({-l1, n * 2}); if(it != t2.end()) { cout << "NO"; return 0; } if(events[i].first.second == 1) { t1.erase({l1, events[i].second}); t2.erase({-r1, events[i].second}); } else { t1.insert({l1, events[i].second}); t2.insert({-r1, events[i].second}); } } for(int i = events.size() - 1; i >= 0; i--){ int l1 = qw[events[i].second].first; int r1 = qw[events[i].second].second; set <pair <int, int> > :: iterator it; it = t1.upper_bound({r1, n * 2}); if(it != t1.end()) { cout << "NO"; return 0; } it = t2.upper_bound({-l1, n * 2}); if(it != t2.end()) { cout << "NO"; return 0; } if(events[i].first.second == -1) { t1.erase({l1, events[i].second}); t2.erase({-r1, events[i].second}); } else { t1.insert({l1, events[i].second}); t2.insert({-r1, events[i].second}); } } for(int i = 0; i < events1.size(); i++) { int l1 = qw1[events1[i].second].first; int r1 = qw1[events1[i].second].second; set <pair <int, int> > :: iterator it; it = t1.upper_bound({r1, n * 2}); if(it != t1.end()) { cout << "NO"; return 0; } it = t2.upper_bound({-l1, n * 2}); if(it != t2.end()) { cout << "NO"; return 0; } if(events1[i].first.second == 1) { t1.erase({l1, events1[i].second}); t2.erase({-r1, events1[i].second}); } else { t1.insert({l1, events1[i].second}); t2.insert({-r1, events1[i].second}); } } for(int i = events1.size() - 1; i >= 0; i--){ int l1 = qw1[events1[i].second].first; int r1 = qw1[events1[i].second].second; set <pair <int, int> > :: iterator it; it = t1.upper_bound({r1, n * 2}); if(it != t1.end()) { cout << "NO"; return 0; } it = t2.upper_bound({-l1, n * 2}); if(it != t2.end()) { cout << "NO"; return 0; } if(events1[i].first.second == -1) { t1.erase({l1, events1[i].second}); t2.erase({-r1, events1[i].second}); } else { t1.insert({l1, events1[i].second}); t2.insert({-r1, events1[i].second}); } } cout << "YES"; return 0; }
cpp
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
#include <bits/stdc++.h> 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>; using qii = queue<ii>; int n; vvi xs, ys, zs; vvi s; bool dfs(int y, int x) { s[y][x] = 1; int dys[] = {-1,0,1,0}; int dxs[] = {0,-1,0,1}; for (int i = 0; i < 4; i++) { int dy = y+dys[i]; int dx = x+dxs[i]; if (dy < 0 || dy >= n) continue; if (dx < 0 || dx >= n) continue; if (xs[dy][dx] != -2 || ys[dy][dx] != -2) continue; if (s[dy][dx]) { if (i==0) zs[y][x] = 'U'; else if (i==1) zs[y][x] = 'L'; else if (i==2) zs[y][x] = 'D'; else zs[y][x] = 'R'; return true; } if (zs[dy][dx]) continue; if (dfs(dy, dx)) { if (i==0) zs[y][x] = 'U'; else if (i==1) zs[y][x] = 'L'; else if (i==2) zs[y][x] = 'D'; else zs[y][x] = 'R'; return true; } } return false; } int main() { cin.tie(0), ios::sync_with_stdio(0); int x, y; cin >> n; xs = vvi(n, vi(n)), ys = vvi(n, vi(n)), zs = vvi(n, vi(n)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> y >> x, xs[i][j]=x-1, ys[i][j]=y-1; qii q; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (ys[i][j] == i && xs[i][j] == j) zs[i][j] = 'X', q.push({i, j}); while (!q.empty()) { tie(y, x) = q.front(); q.pop(); int dys[] = {-1,0,1,0}; int dxs[] = {0,-1,0,1}; for (int i = 0; i < 4; i++) { int dy = y+dys[i]; int dx = x+dxs[i]; if (dy < 0 || dy >= n) continue; if (dx < 0 || dx >= n) continue; if (zs[dy][dx]) continue; if (xs[dy][dx] != xs[y][x]) continue; if (ys[dy][dx] != ys[y][x]) continue; if (i==0) zs[dy][dx] = 'D'; else if (i==1) zs[dy][dx] = 'R'; else if (i==2) zs[dy][dx] = 'U'; else zs[dy][dx] = 'L'; q.push({dy, dx}); } } s = vvi(n, vi(n)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (zs[i][j]) continue; if (xs[i][j] != -2 || ys[i][j] != -2) { cout << "INVALID\n"; return 0; } if (!dfs(i, j)) { cout << "INVALID\n"; return 0; } } cout << "VALID\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << char(zs[i][j]); cout << endl; } }
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 <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef vector<int> vi; typedef pair<int, int> pii; #define IOS ios::sync_with_stdio(0) #define For(i,a,b) for (int i=(a),_b=(b);i<=_b;i++) #define FOr For #define Iter(i,a,b) for (int i=(a),_b=(b);i<_b;i++) #define Downto(i,a,b) for (int i=(a),_b=(b);i>=_b;i--) #define set0(a) memset(a,0,sizeof(a)) #define set0n(a,n) memset(a,0,sizeof((a)[0])*(n+1)) #define pb push_back #define mkp make_pair #define all(a) (a).begin(),(a).end() template <class T1, class T2> inline void getmin(T1& x, const T2& y) {if (y < x) x = y;} template <class T1, class T2> inline void getmax(T1& x, const T2& y) {if (x < y) x = y;} //char NY[2][10]={"NO\n","YES\n"};//capital? #ifdef DEBUG #define SHOW(x) (cerr<<#x"="<<(x)<<endl,(x)) #define MSG(s) (cerr<<"MESSAGE: "<<(s)<<endl,0) #else #define SHOW(x) (x) #define MSG(s) 0 #endif const int N = 303, NN = N * N, Q = 2e6 + 10; const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; int n, m, q; int first[Q], last[Q]; int dt[Q]; struct Query { int x, y, c; } a[Q]; vi cover[Q]; int cc[N][N];//current color int fa[NN]; int find(int x) {return fa[x] == x ? x : (fa[x] = find(fa[x]));} inline void merge(int x, int y) {fa[find(y)] = find(x);} #define pt(x,y) ((x)*m+(y)) inline bool in(int x, int y) {return 1 <= x && x <= n && 1 <= y && y <= m;} inline int add(int x, int y, int c) { if (!x && !y) { return 0; } int cnt = 0, x2, y2; cc[x][y] = c; For(d, 0, 3) if (in(x2 = x + dx[d], y2 = y + dy[d]) && cc[x2][y2] == c && find(pt(x, y)) != find(pt(x2, y2))) { cnt++, merge(pt(x, y), pt(x2, y2)); } return 1 - cnt; } signed main() { IOS; cin >> n >> m >> q; For(i, 1, q) { int x, y, c; cin >> x >> y >> c; if (cc[x][y] == c) {x = y = 0;} else { cover[cc[x][y]].pb(i); } a[i] = (Query) {x, y, c}; last[cc[x][y] = c] = i; if (c != a[i - 1].c) { first[c] = i; } } dt[0] = 1, last[0] = -1; For(c, 0, a[q].c) { if (!last[c]) { continue; } if (c) { iota(fa, fa + 1 + (n + 1)*m, 0); For(i, 1, n) set0n(cc[i], m); For(i, first[c], last[c]) { dt[i] += add(a[i].x, a[i].y, c); } } iota(fa, fa + 1 + (n + 1)*m, 0); reverse(all(cover[c])); for (auto i : cover[c]) { cc[a[i].x][a[i].y] = -1; } if (c) { For(i, first[c], last[c]) if (cc[a[i].x][a[i].y] != -1) add(a[i].x, a[i].y, c); } //only merging else { For(x, 1, n) For(y, 1, m) if (cc[x][y] != -1) add(x, y, 0); } //beware braces!!! for (auto i : cover[c]) { dt[i] -= add(a[i].x, a[i].y, c); } } For(i, 1, q) dt[i] += dt[i - 1], cout << dt[i] << '\n'; return cout << flush, 0; }
cpp