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
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
#include <bits/stdc++.h> #define x first #define y second #define TLE ios::sync_with_stdio(0),cin.tie(0) using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<double, double> PDD; typedef unsigned long long ULL; const int N = 3e5 + 10, M = 2 * N, mod = 1e9 + 7; const double eps = 1e-8; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; int h[N], ne[M], e[M], w[M]; LL T, n, m, k; int a[N], s[N]; int main() { TLE; cin >> n; for (int i = 1; i <= n; i ++ ) cin >> a[i], s[i] = s[i - 1] + a[i]; unordered_map<int, vector<PII>> hash; for (int i = 1; i <= n; i ++ ) for (int j = 1; j <= i; j ++ ) hash[s[i] - s[j - 1]].push_back({j, i}); //for (auto& c : hash[3]) cout << c.x << " " << c.y << endl; int st = -2e9, ed = -2e9; vector<PII> ans; for (auto& v : hash){ st = -2e9, ed = -2e9; vector<PII> tmp; for (auto& c : v.y){ if (c.x > ed){ if (ed != -2e9) tmp.push_back({st, ed}); st = c.x, ed = c.y; } } tmp.push_back({st, ed}); if (tmp.size() > ans.size()) ans = tmp; } cout << ans.size() << "\n"; for (auto& c : ans) cout << c.x << " " << c.y << "\n"; }
cpp
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
#include<bits/stdc++.h> using namespace std; void dbg_out() { cout << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cout << ' ' << H; dbg_out(T...); } #ifdef LOCAL #define debug(...) cout << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define debug(...) "zzz" #endif using LL = long long; using LD = long double; using pii = pair<LL,LL>; #define FOR(i, n) for(int i = 1; i<=n; i++) #define F0R(i, n) for(int i = 0; i<n; i++) #define all(x) x.begin(), x.end() #define mp make_pair #define pb push_back #define f first #define s second template<typename T, typename = void> struct is_iterable : false_type {}; template<typename T> struct is_iterable<T, void_t<decltype(begin(declval<T>())),decltype(end(declval<T>()))>> : true_type {}; template<typename T> typename enable_if<is_iterable<T>::value&&!is_same<T, string>::value,ostream&>::type operator<<(ostream &cout, T const &v); template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p) { return cout << "(" << p.f << ", " << p.s << ")"; } template<typename T> typename enable_if<is_iterable<T>::value&&!is_same<T, string>::value,ostream&>::type operator<<(ostream &cout, T const &v) { cout << "["; for (auto it = v.begin(); it != v.end();) { cout << *it; if (++it != v.end()) cout << ", "; } return cout << "]"; } //var LL T; vector<int> graham_scan(vector<pii>& points) { int N = points.size(); vector<int> process(N); iota(all(process), 0); sort(all(process), [&points](int a, int b) { return points[a] < points[b]; }); //debug(points); vector<int> hull(N + 1); int idx = 0; auto cross = [&](int a, int b, int c) -> LL { return 1LL * (points[b].first - points[a].first) * (points[c].second - points[a].second) - 1LL * (points[b].second - points[a].second) * (points[c].first - points[a].first); }; for (int i = 0; i < N; i++) { while (idx >= 2 && cross(hull[idx - 2], hull[idx - 1], process[i]) >= 0) { idx--; } hull[idx++] = process[i]; } int half = idx; for (int i = N - 2; i >= 0; i--) { while (idx > half && cross(hull[idx - 2], hull[idx - 1], process[i]) >= 0) idx--; hull[idx++] = process[i]; } idx--; vector<int> ret; for (int i = half; i < idx; i++) ret.pb(hull[i]); ret.pb(hull[0]); return ret; } void solve() { LL n; cin >> n; vector<LL> a(n); for (auto& u : a) cin >> u; vector<pii> b(n + 1); FOR (i, n) { b[i].f = i; b[i].s = a[i - 1]; b[i].s += b[i - 1].s; } vector<int> lower = graham_scan(b); LL starting_point = 1; lower.pop_back(); reverse(all(lower)); vector<LD> ans(n); for (auto u : lower) { LD running = 0; LL cnt = 0; for (int i = starting_point; i <= u; i++) { running += a[i - 1]; cnt++; } for (int i = starting_point; i <= u; i++) { ans[i - 1] = running / cnt; } starting_point = u + 1; } LD running = 0; LL cnt = 0; for (int i = starting_point; i <= n; i++) { running += a[i - 1]; cnt++; } for (int i = starting_point; i <= n; i++) { ans[i - 1] = running / cnt; } cout << fixed << setprecision(10); for (auto& u : ans) cout << u << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); T = 1; //cin >> T; FOR(t, T) solve(); cout.flush(); return 0; }
cpp
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
#include <bits/stdc++.h> #define f first #define S second #define pb push_back #define msk(x , y) (x >> y) & 1 #define all(x) x.begin() , x.end() using namespace std; typedef long long int ll; const int N = 5e5 + 7 ; const ll mod = 998244353; const int dx[] = {-1, -1 , -1 , 0, 0 , -1 , 1 , 1}; const int dy[] = {-1 , 0 , 1 , -1, 1 , 1 , 0 , 1}; int n , m ,a[N] , b , Mx; void solve(){ cin >> n ; int sum = 0 , mx = 0; for(int i = 1 ; i <= n ; i++){ cin >> a[i]; if(a[i] == 0) mx++; sum += a[i]; } if(mx == 0){ if(sum == 0) cout << "1\n"; else cout << "0\n"; } else{ if(sum + mx != 0) cout << mx << "\n"; else cout << mx + 1 << "\n"; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int test = 1 ; cin >> test ; for(int i = 1; i <= test ; i++) { // cout << "Case " << i << ":\n"; solve(); } }
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(adj[x].size()==1) adj[x].clear(); if(adj[x].empty()) continue; if (vis[x]) continue; vis[x]=1; dist[x] = d; bool skip=0; for (int i: adj[x]) if (i != p || skip) { if (vis[i]) ans = min(ans, dist[i] + dist[x] + 1); else next1.push({d + 1, {i, x}}); } else skip = 1; } adj[j].clear(); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); prime.reserve(170); prime.push_back(1); for(int i=2;i<=1e3;i++) { if(pvis[i]) continue; prime.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) bfs(j); cout << (ans == MN ? -1 : ans) <<'\n'; }
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 <cstdio> #include <vector> #include <cassert> #include <queue> #include <algorithm> const int INF=1e9+7; std::vector<int> edges[400005]; int anc[19][400005]; int depth[400005]; void dfs(int node){ for(int child:edges[node]){ edges[child].erase(std::find(edges[child].begin(),edges[child].end(),node)); anc[0][child]=node; for(int k=1;k<19;k++){ anc[k][child]=anc[k-1][anc[k-1][child]]; } depth[child]=depth[node]+1; dfs(child); } } int la(int node,int len){ for(int k=19-1;k>=0;k--){ if(len&(1<<k)){ node=anc[k][node]; } } return node; } int lca(int a,int b){ if(depth[a]<depth[b]) std::swap(a,b); a=la(a,depth[a]-depth[b]); if(a==b) return a; for(int k=19-1;k>=0;k--){ if(anc[k][a]!=anc[k][b]){ a=anc[k][a]; b=anc[k][b]; } } return anc[0][a]; } //move x steps from a to b //assumes x<=dist(a,b) int walk(int a,int b,int x){ int c=lca(a,b); if(x<=depth[a]-depth[c]){ return la(a,x); } int excess=x-(depth[a]-depth[c]); assert(excess<=(depth[b]-depth[c])); return la(b,depth[b]-depth[c]-excess); } int uf[400005]; int dist[400005];//dist[x]=0 iff x is rest stop int find(int a){ while(a!=uf[a]){ a=uf[a]=uf[uf[a]]; } return a; } bool query(int K){ int A,B; scanf("%d %d",&A,&B); A--,B--; int C=lca(A,B); if(depth[A]+depth[B]-2*depth[C]<=2*K){ return true; }else{ return find(walk(A,B,K))==find(walk(B,A,K)); } } int main(){ int N,K,R; scanf("%d %d %d",&N,&K,&R); int oldN=N; for(int i=0;i<oldN-1;i++){ int X,Y; scanf("%d %d",&X,&Y); X--,Y--; edges[X].push_back(N); edges[N].push_back(X); edges[Y].push_back(N); edges[N].push_back(Y); N++; } for(int i=0;i<N;i++){ uf[i]=i; } std::fill(dist,dist+N,INF); std::queue<int> frontier; for(int i=0;i<R;i++){ int X; scanf("%d",&X); X--; dist[X]=0; frontier.push(X); } while(!frontier.empty()){ int x=frontier.front(); if(dist[x]>K-1) break; frontier.pop(); for(int y:edges[x]){ uf[find(y)]=find(x); if(dist[y]==INF){ dist[y]=dist[x]+1; frontier.push(y); } } } dfs(0); int V; scanf("%d",&V); while(V--){ if(query(K)){ printf("YES\n"); }else{ printf("NO\n"); } } } /* did anyone just use binary jumping here */
cpp
13
D
D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7
[ "dp", "geometry" ]
#include <iostream> #include <algorithm> #define int long long using namespace std; struct point{ int x,y; }p[501],p2[501]; inline point operator-(point a, point b){ return {a.x-b.x,a.y-b.y}; } inline int operator*(point a, point b){ return a.x*b.y-a.y*b.x; } int f(point a, point b, point c){ return abs(a*b+b*c+c*a); } int n,m,dp[501][501],mn,res; signed main(){ ios_base::sync_with_stdio(NULL);cin.tie(nullptr); cin >> n >> m; for (int i=1;i<=n;i++){ cin >> p[i].x >> p[i].y; mn=min(mn,p[i].y); } sort(p+1,p+n+1,[](point a, point b){ return (a.x==b.x?(a.y<b.y):(a.x<b.x)); }); for (int i=1;i<=m;i++){ cin >> p2[i].x >> p2[i].y; mn=min(mn,p2[i].y); } for (int i=1;i<=n;i++) p[i]={p[i].x,p[i].y-mn}; for (int i=1;i<=m;i++) p2[i]={p2[i].x,p2[i].y-mn}; for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++){ int area=(p[i].y+p[j].y)*abs(p[i].x-p[j].x); point a=p[i],b={p[i].x,0},c={p[j].x,0},d=p[j]; for (int k=1;k<=m;k++) dp[i][j]+=(p2[k].x!=p[i].x&&f(p2[k],a,b)+f(p2[k],b,c)+f(p2[k],c,d)+f(p2[k],d,a)==area); } for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++) for (int k=j+1;k<=n;k++) if (abs(dp[i][j]+dp[j][k]-dp[i][k])==0) res++; cout << res; }
cpp
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
#include <bits/stdc++.h> #define itn long long #define int long long #define double long double //#define endl '\n' #define p_b push_back #define fi first #define se second #define pii std::pair<int, int> #define oo LLONG_MAX #define big INT_MAX #define elif else if using namespace std; int input() { int x; cin>>x; return x; } void solve() { string s, t; cin>>s>>t; map<char, bool>mp; for(char c:s)mp[c]=true; for(char c:t)if(!mp[c]) { cout<<-1; return; } itn n=s.size(); vector<vector<int>>vc(26, vector<int>(n+1)); for(int i=0;i<26;i++) { vc[i][n]=-1; for(int j=n-1;j>=0;j--) { if(s[j]-'a'==i)vc[i][j]=j; else vc[i][j]=vc[i][j+1]; } } // for(int i=0;i<26;i++) // { // for(int j=0;j<n;j++) // cout<<vc[i][j]<<' '; // cout<<endl; // } itn ans=0; int cur=0; for(int i=0;i<t.size();i++) { if(cur==0){ans++;} if(vc[t[i]-'a'][cur]==-1){ cur=n; i--; } else cur=vc[t[i]-'a'][cur]+1; if(cur>=n) cur=0; } cout<<ans; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); // freopen("network.in", "r", stdin); // freopen("magic.txt", "w", stdout); int t=1; cin>>t; while(t--) { solve(); cout<<endl<<endl; } }
cpp
1290
D
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "constructive algorithms", "graphs", "interactive" ]
/* Wei Wai Wei Wai Zumigat nan damu dimi kwayt rayt */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; /*typedef __uint128_t L; struct FastMod { ull b, m; FastMod(ull b) : b(b), m(ull((L(1) << 64) / b)) {} ull reduce(ull a) { ull q = (ull)((L(m) * a) >> 64); ull r = a - q * b; // can be proven that 0 <= r < 2*b return r >= b ? r - b : r; } }; FastMod FM(2);*/ typedef pair<int,int> pii; typedef pair<ll,ll> pll; void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...); } #define debug(...) cerr << "(" << #__VA_ARGS__ << "):", debug_out(__VA_ARGS__) #define all(x) x.begin(), x.end() #define MP(x, y) make_pair(x, y) #define F first #define S second //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int maxn = 2e3 + 10; int n, k; bool vis[maxn]; bool ask(int x){ cout << "? " << x << endl; char res; cin >> res; return (res == 'Y'? true: false); } int md(int x){ return (x <= 0? x + n / k: (x > n / k? x - n / k: x)); } int main(){ //ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> k; if (n == 1){ return cout << "! 1" << endl, 0; } if (k > 1){ k >>= 1; } for (int i = 1; i <= n/k/2; i++){ cout << "R" << endl; for (int j = 1; j <= n/k; j++){ int tmp = j / 2 * (j & 1? -1: 1); int blc = md(i + tmp); for (int idx = (blc-1) * k + 1; idx <= blc * k; idx++){ if (!vis[idx]){ vis[idx] = ask(idx); } } } } int ans = 0; for (int i = 1; i <= n; i++){ ans += (!vis[i]); } cout << "! " << ans << '\n'; return 0; }
cpp
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
//author: TomoriNao #include<bits/stdc++.h> #define all(x) x.begin(), x.end() #define ll long long //#include<time.h> using namespace std; int main(){ // freopen("1.inp","r",stdin); //freopen("1.ans","w",stdout); ios::sync_with_stdio(0); cin.tie(0); int t; cin >>t; while (t--) { ll a; string b; cin >>a>>b; bool ok = true; for (int i =0;i<b.size();i++) { if (b[i]-'0'<9) { ok = false; break; } } int so =0; if (ok) { so =b.size(); } else { so =b.size()-1; } ll sodau=1; cout <<a*so<<endl; } return 0; }
cpp
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
#include<iostream> using namespace std; int main() { int t; cin>>t; int a[t+2]; for(int i=0; i<t; i++) { int n,m; cin>>n>>m; if(n%m == 0)a[i]=1; else a[i] =0; } for(int i=0; i<t; i++) { if(a[i] == 1)cout<<"YES\n"; else cout<<"NO\n"; } }
cpp
1284
G
G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1). For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1) For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4 2 2 OO OO 3 3 OOO XOO OOO 4 4 OOOX XOOX OOXO OOOO 5 6 OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OutputCopyYES OOO O OOO NO YES OOOOO X O O X O O X O OOO X O O O O O OOOOO YES OOOOOOOOOOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO
[ "graphs" ]
#include<bits/stdc++.h> #define re register using namespace std; inline int read(){ re int t=0;re char v=getchar(); while(v<'0')v=getchar(); while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar(); return t; } int A[805],B[805],pre[805],S,T,n,m,fa[805],dis[805],Q[805],hd,tl,d[805],col[805],k; char vis[805],usd[805],inq[805],G[805][805],s[22][22],ans[805][805]; inline int root(re int x){return x==fa[x]?x:fa[x]=root(fa[x]);} inline void Merge(re int x,re int y){ x=root(x),y=root(y); if(x==y)++vis[x]; else fa[x]=y,vis[y]+=vis[x]; } inline bool ck1(){ for(re int i=1;i<=n;++i)fa[i]=i,vis[i]=0; for(re int i=1;i<=m;++i) if(usd[i]){ Merge(A[i],B[i]); if(vis[root(A[i])])return 0; } return 1; } inline bool ck2(){ for(re int i=1;i<=n;++i)d[i]=col[i]?(col[i]-1):-114514; for(re int i=1;i<=m;++i) if(usd[i]){ ++d[A[i]],++d[B[i]]; if(d[A[i]]>2||d[B[i]]>2)return 0; } return 1; } int main(){ int t=read(); while(t--){ n=read(),k=read(),m=0; for(re int i=1;i<=n;++i)scanf("%s",s[i]+1); int tt=0,nn=0;memset(usd,0,sizeof(usd)); for(re int i=1;i<=n;++i) for(re int j=1;j<=k;++j){ col[++tt]=(i+j+1)&1; if(s[i][j]=='X')col[tt]=0; if(col[tt])nn+=s[i][j]=='O'; if(s[i][j]=='O'&&s[i][j+1]=='O'&&j!=k)A[++m]=(i-1)*k+j,B[m]=(i-1)*k+j+1; if(s[i][j]=='O'&&s[i+1][j]=='O'&&i!=n)A[++m]=(i-1)*k+j,B[m]=i*k+j; } col[1]=2,S=m+1,T=m+2,n*=k,--nn; while(1){ for(re int i=1;i<=T;++i)dis[i]=0;dis[S]=1; for(re int i=1;i<=T;++i)for(re int j=1;j<=T;++j)G[i][j]=0; int nn=0; for(re int i=1;i<=m;++i) if(!usd[i]){ usd[i]=1; if(ck1())G[S][i]=1; if(ck2())G[i][T]=1; usd[i]=0; }else ++nn; for(re int i=1;i<=m;++i) if(usd[i]){ usd[i]=0; ck1(); for(re int j=1;j<=m;++j) if((i^j)&&(!usd[j])){ re int x=root(A[j]),y=root(B[j]); if(x^y)G[i][j]=1; } ck2(); for(re int j=1;j<=m;++j) if((i^j)&&(!usd[j])) if(d[A[j]]+1<=2&&d[B[j]]+1<=2)G[j][i]=1; usd[i]=1; } Q[hd=tl=1]=S; while(hd<=tl){ re int x=Q[hd++]; for(re int i=1;i<=T;++i)if(G[x][i]&&!dis[i])dis[i]=dis[x]+1,pre[i]=x,Q[++tl]=i; } if(!dis[T])break; re int x=T; while(x^S)usd[x]^=1,x=pre[x]; } for(re int i=1;i<=n;++i)fa[i]=i;re int ss=0; for(re int i=1;i<=m;++i)if(usd[i])Merge(A[i],B[i]),++ss; ck2(); re bool ia=1; for(re int i=2;i<=n;++i)if(col[i])ia&=d[i]==2; if(!ia){ puts("NO"); continue; } for(re int i=1;i<=m;++i)if(root(A[i])^root(B[i]))usd[i]=1,Merge(A[i],B[i]); n/=k; for(re int i=1;i<=n+n;++i) for(re int j=1;j<=k+k;++j) ans[i][j]=' '; for(re int i=1;i<=n;++i) for(re int j=1;j<=k;++j) ans[i*2-1][j*2-1]=s[i][j]; for(re int i=1;i<=m;++i) if(usd[i]){ re int px=(A[i]-1)/k+1,py=(A[i]-1)%k+1; if(B[i]==A[i]+1)ans[px*2-1][py*2]='O'; else ans[px*2][py*2-1]='O'; } puts("YES"); for(re int i=1;i<=n+n-1;++i,puts("")) for(re int j=1;j<=k+k-1;++j) putchar(ans[i][j]); } }
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; struct pt { int x, y; }; long long sq(int x) { return 1LL*x*x; } long long norm(pt& a) { return sq(a.x)+sq(a.y); } int quadrant(pt a) { if (a.y >= 0 && a.x > 0) return 0; else if (a.x <= 0 && a.y > 0) return 1; else if (a.y <= 0 && a.x < 0) return 2; else return 3; } bool operator < (pt& a, pt& b) { // for the purposes we need it for, a and b are nonzero and at different angles int qa = quadrant(a); int qb = quadrant(b); if (qa != qb) return qa < qb; if (qa % 2 == 0) { return static_cast<__int128>(sq(a.x))*norm(b) > static_cast<__int128>(sq(b.x))*norm(a); } else { return static_cast<__int128>(sq(a.x))*norm(b) < static_cast<__int128>(sq(b.x))*norm(a); } } bool within_half_rotation(pt& a, pt& b) { return (1LL*a.x*b.y >= 1LL*b.x*a.y); } int main () { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<pt> pts(n); for (pt& p: pts) cin >> p.x >> p.y; // for each point, calculate how many triangles enclose it long long ans = 0; for (int i = 0; i < n; i++) { vector<pt> rel; rel.reserve(n-1); for (int j = 0; j < n; j++) { if (j == i) continue; rel.emplace_back(pt{pts[j].x-pts[i].x, pts[j].y-pts[i].y}); } sort(rel.begin(), rel.end()); long long triangles = 1LL*(n-1)*(n-2)*(n-3)/6; int r = 0; for (int l = 0; l < n-1; l++) { while (within_half_rotation(rel[l], rel[r])) { r++; if (r == n-1) r = 0; if (r == l) break; } int k = r-l-1; if (k < 0) k += n-1; triangles -= k*(k-1)/2; if (r == l) r++; if (r == n-1) r = 0; } ans += triangles; } ans = (n-4)*ans/2; cout << ans << '\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" ]
#pragma GCC optimize(2) #pragma GCC optimize(3) #include <bits/stdc++.h> #define rep(i, a, b) for (int i = a; i <= b; i++) #define per(i, a, b) for (int i = a; i >= b; i--) using namespace std; typedef unsigned long long ull; typedef pair <int, int> pii; typedef long long ll; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); } f *= fu; } template <typename T> void print(T x) { if (x < 0) putchar('-'), x = -x; if (x < 10) putchar(x + 48); else print(x / 10), putchar(x % 10 + 48); } template <typename T> void print(T x, char t) { print(x); putchar(t); } const int N = 250005; vector <int> adj[N]; int ch[N][2], fa[N], rev[N], st[N], f[N]; int n, top; int find(int x) { return !f[x] ? x : f[x] = find(f[x]); } bool isroot(int u) { return ch[fa[u]][0] != u && ch[fa[u]][1] != u; } bool get(int u) { return ch[fa[u]][1] == u; } void rotate(int u) { int old = fa[u], oldd = fa[old], k = get(u); if (!isroot(old)) { ch[oldd][get(old)] = u; } fa[u] = oldd; ch[old][k] = ch[u][k ^ 1]; fa[ch[u][k ^ 1]] = old; ch[u][k ^ 1] = old; fa[old] = u; } void pushdown(int u) { if (rev[u]) { swap(ch[u][0], ch[u][1]); rev[ch[u][0]] ^= 1; rev[ch[u][1]] ^= 1; rev[u] = 0; } } void splay(int u) { st[top = 1] = u; for (int i = u; !isroot(i); i = fa[i]) st[++top] = fa[i]; for (int i = top; i >= 1; i--) pushdown(st[i]); for (; !isroot(u); rotate(u)) if (!isroot(fa[u])) rotate(get(u) == get(fa[u]) ? fa[u] : u); } void access(int u) { for (int i = 0; u; i = u, u = fa[u]) { splay(u); ch[u][1] = i; } } void makeroot(int u) { access(u); splay(u); rev[u] ^= 1; } void link(int u, int v) { makeroot(u); fa[u] = v; } void cut(int u, int v) { makeroot(u); access(v); splay(v); fa[u] = ch[v][0] = 0; } pair <int, int> query(int u, int v) { makeroot(u); access(v); splay(v); pair <int, int> ans; int las; while (v) { las = v; pushdown(v); if (find(v) != find(u)) { ans.first = v; v = ch[v][0]; } else { ans.second = v; v = ch[v][1]; } } splay(las); return ans; } void dfs1(int u, int fa) { for (int i = 0; i < (int)adj[u].size(); i++) { int v = adj[u][i]; if (v == fa) continue; dfs1(v, u); } if (fa) { pair <int, int> ans = query(u, fa); print(u, ' '); print(fa, ' '); print(ans.first, ' '); print(ans.second, '\n'); f[find(u)] = find(fa); cut(ans.first, ans.second); link(u, fa); } } int main() { read(n); for (int i = 1; i < n; i++) { int u, v; read(u); read(v); adj[u].push_back(v); adj[v].push_back(u); } for (int i = 1; i < n; i++) { int u, v; read(u); read(v); link(u, v); } print(n - 1, '\n'); dfs1(1, 0); return 0; }
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> #define timetaken cerr<<"Compile successful\n";cerr<<fixed<<setprecision(10);cerr<<"Time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl #define Fast() ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>t;while(t--) #define tou(s) transform(s.begin(),s.end(),s.begin(),::toupper); #define tol(s) transform(s.begin(),s.end(),s.begin(),::tolower); #define up(a,x) (upper_bound(a.begin(),a.end(),x)-a.begin()) #define lp(a,x) (lower_bound(a.begin(),a.end(),x)-a.begin()) #define Psum(r) partial_sum(r.begin(), r.end(), r.begin()); #define MNE(c) *min_element(c.begin(),c.end()) #define MXE(c) *max_element(c.begin(),c.end()) #define upn(a,n,x) (upper_bound(a,a+n,x)-a) #define lpn(a,n,x) (lower_bound(a,a+n,x)-a) #define YON(f) cout<<(f?"YES":"NO")<<Endl; #define re(a) reverse(a.begin(),a.end()); #define pas1 {cout<<-1<<Endl;continue;} #define pas2 {cout<<-1<<Endl;return 0;} #define bitsN(n) __builtin_popcount(n); #define so(a) sort(a.begin(),a.end()); #define MAX(a,b) a=max(a,b) #define PB(a) push_back(a) #define sz(a) a.size() #define ll long long #define Endl '\n' #define S second #define F first using namespace std; const double eps=1e-6; int gcd(int a, int b){return(!b ? a : gcd(b, a % b));} int lcm(int a, int b){return((a * b) / gcd(a, b));} ll n,m,c,f=1; int main(){ cin>>n>>m; if(m%n!=0) f=0; while(m>n){ if(m/n%3==0) m/=3,c++; else if(m/n%2==0) m/=2,c++; else {f=0;break;} } cout<<(f&&m==n?c:-1); }
cpp
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
#include <bits/stdc++.h> using namespace std; #define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0) #define getTest int t; cin >> t #define eachTest for (int _var=0;_var<t;_var++) #define get(name) int (name); cin >> (name) #define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); } #define out(o) cout << (o) #define int long long int signed main() { improvePerformance; get(n); map<int, vector<int>> lists; vector<int> beginners; for (int _=0;_<n;_++) { get(m); getList(m, cur); bool downsorted = true; for (int i = 0; i < m - 1; i++) { if (cur[i] < cur[i + 1]) { downsorted = false; break; } } if (lists.find(cur[0]) == lists.end()) { if (downsorted) { lists[cur[0]]={(cur[cur.size() - 1])}; } } else { if (downsorted) { lists[cur[0]].push_back(cur[cur.size() - 1]); } } } for (map<int, vector<int>>::iterator it = lists.begin(); it != lists.end(); it++) { beginners.push_back(it->first); } sort(beginners.begin(), beginners.end()); vector<int> prefixSums; prefixSums.push_back(0ll); int invalidPairs = 0ll; for (int beginner: beginners) { prefixSums.push_back(prefixSums[prefixSums.size() - 1] + lists[beginner].size()); for (int val: lists[beginner]) { int lowerBound = 0ll; int upperBound = prefixSums.size() - 1ll; while (upperBound - lowerBound > 1) { int middle = (lowerBound + upperBound) / 2; if (beginners[middle - 1] <= val) { lowerBound = middle; } else { upperBound = middle; } } invalidPairs += prefixSums[lowerBound]; if (val == beginner) invalidPairs += lists[beginner].size(); } } out(n * n - invalidPairs); }
cpp
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
#include <iostream> #include<bits/stdc++.h> #include<deque> #include<algorithm> #include<math.h> #include<sstream> #include<stdio.h> #include<bitset> #include<string> #include<vector> #include<unordered_map> #include<queue> #include<set> #include<fstream> #include<map> #define int long long int #define ld long double #define pi 3.1415926535897932384626433832795028841971 #define MOD1 998244353 using namespace std; random_device seed_gen; mt19937_64 engine(seed_gen()); int inf = 1e18; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; template <typename T, typename U> void debug(std::vector<pair<T, U>> v) {for (int i = 0; i < v.size(); i++) cout << "[ " << v[i].first << " " << v[i].second << " ]\n"; cout << "\n";} template <typename T> void debug(std::vector<T> v) {cout << "[ "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "]\n";} template <typename T> void debug(std::set<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(std::multiset<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(vector<vector<T>> v) {int n = v.size(), m = v[0].size(); for (int i = 0; i < n; i++) {cout << "[ "; for (int j = 0; j < m; j++) cout << v[i][j] << " "; cout << "]\n";}} template <typename T> void debug(T i) {cout << "[ " << i << " ]\n";} template <typename T, typename U> void debug(T i, U j) {cout << "[ " << i << " " << j << " ]\n";} template <typename T, typename U, typename V> void debug(T i, U j, V k) {cout << "[ " << i << " " << j << " " << k << " ]\n";} template <typename T, typename U, typename V, typename X> void debug(T i, U j, V k, X l) {cout << "[ " << i << " " << j << " " << k << " " << l << " ]\n";} template <typename T, typename U> void debug(pair<T, U> x) {cout << "[ " << x.first << " " << x.second << " ]\n";} int expo(int a, int b, int mod) { int res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b = b >> 1; } return res; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int mminvprime(int a, int b) { return expo(a, b, b + 2); } const int N = 1e5 + 12; int a[N], ind[N]; bool cmp(int x, int y) { return a[x] > a[y]; } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int n, p, k; cin >> n >> p >> k; vector<vector<int>> s(n + 1, vector<int>(p, 0)); for (int i = 1; i <= n; ++i) { cin >> a[i]; ind[i] = i; } sort(ind + 1, ind + n + 1, cmp); for (int i = 1; i <= n; ++i) { for (int j = 0; j < p; j++) { int x; cin >> x; s[i][j] = x; } } int all = 1 << p; vector<vector<int>> dp(all, vector<int>(n + 1, -1)); dp[0][0] = 0; for (int i = 1; i <= n; ++i) { int curind = ind[i]; for (int mask = 0; mask < all; mask++) { int cur = (i - 1) - __builtin_popcount(mask); if (cur < k) { if (dp[mask][i - 1] != -1) dp[mask][i] = dp[mask][i - 1] + a[curind]; } else { if (dp[mask][i - 1] != -1) dp[mask][i] = dp[mask][i - 1]; } for (int j = 0; j < p; j++) { if (!(mask & (1 << j))) continue; if (dp[mask ^ (1 << j)][i - 1] != -1) dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << j)][i - 1] + s[curind][j]); } } } cout << dp[all - 1][n]; return 0; }
cpp
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
#include <iostream> #include <fstream> #include <stack> #include <set> #include <map> #include <stack> #include <vector> #include <queue> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <array> #include <bitset> #include <queue> //#define int long long #define all(v) begin(v), end(v) #define ve vector #define vi vector<int> #define vd vector<double> #define pb push_back #define pii pair<int,int> #define rep(i, n) for(int i = 0; i < (n); i++) using namespace std; using ll = long long; using ull = unsigned long long; const double pi = atan(1) * 4; void fast() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed; cout.precision(10); } void solve() { int n; cin >> n; string s; cin >> s; int l = 0, r = 0; for (int i = 0; i < n; i++) { if (s[i] == 'L') l--; else r++; } cout << r - l + 1 << "\n"; } signed main() { #ifdef LOCAL freopen("local.in", "r", stdin); freopen("local.out", "w", stdout); #endif fast(); int T = 1; //cin >> T; while (T--) solve(); return 0; }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define YES cout << "YES" << endl #define NO cout << "NO" << endl #define all(_) _.begin(), _.end() #define rall(_) _.rbegin(), _.rend() #define sz(_) (int)_.size() #define fs first #define se second #define Odd(_x) ((_x) & 1) using i64 = long long; using ll = long long; //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int inf = 1e9 + 10; const ll mod = 1e9 + 7; void solve() { int n, m, k; cin >> n >> m >> k; if (k > 4 * n * m - 2 * n - 2 * m) { cout << "NO\n"; return ; } YES; vector<pair<int, string>> ans; for (int i = 1; i < n && k; i++, k--) { if (sz(ans) && ans.back().second == "D") ans.back().first++; else ans.push_back({1, "D"}); } for (int i = n - 1; i > 0 && k; i--, k--) { if (ans.back().second == "U") ans.back().first++; else ans.push_back({1, "U"}); } if (k <= 0) { cout << sz(ans) << "\n"; for (auto &[x, y] : ans) { cout << x << " " << y << "\n"; } return ; } ans.push_back({1, "R"}), k--; for (int i = 1; i < m && k; i++) { int op = 0; for (int j = 1; j < n && k; k--) { if (op == 0) { ans.push_back({1, "D"}); } else if (op == 1) { ans.push_back({1, "L"}); } else if (op == 2) { ans.pop_back(); ans.pop_back(); if (ans.back().second == "DLR") ans.back().first += 1; else ans.push_back({1, "DLR"}); j++; } (op += 1) %= 3; } for (int j = n - 1; j > 0 && k; j--, k--) { if (ans.back().second == "U") ans.back().first++; else ans.push_back({1, "U"}); } if (k && i + 1 < m) ans.push_back({1, "R"}), k--; } for (int i = m - 1; i > 0 && k; i--, k--) { if (ans.back().second == "L") ans.back().first++; else ans.push_back({1, "L"}); } cout << sz(ans) << "\n"; int sum = 0; for (auto &[x, y] : ans) { cout << x << " " << y << "\n"; sum += x * sz(y); } // cout << sum << "\n"; } //#define MULTI_INPUT int main() { #ifndef ONLINE_JUDGE freopen(R"(D:\source files\source file2\input.txt)", "r", stdin); freopen(R"(D:\source files\source file2\output.txt)", "w", stdout); #endif std::ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(20); #ifdef MULTI_INPUT int T; cin >> T; while (T--) { solve(); } #else solve(); #endif return 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
// <3 // #include<bits/stdc++.h> #define ll long long #define out return 0; #define str string #define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); using namespace std; int main() { FAST int n, k = 0, m = 0, l = 0; cin>>n; int a[n], b[n]; for (int i = 0; i < n; i ++) { cin>>a[i]; m += a[i]; } for (int i = 0; i < n; i ++) { cin>>b[i]; l += b[i]; if (b[i] == 0 && a[i] == 1) k ++; } if (k == 0) { cout<<-1; out } int ans; ans = (l - m + 1) / k; if ((l - m + 1) % k > 0) ans ++; cout<<max(0, ans) + 1; out }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> #define mll map<ll,ll> #define cinv(v) ll x; cin>>x; v.push_back(x); #define floop(i,b) for(ll i=0;i<b;i++) #define fr(i,a,b) for(ll i=a;i<b;i++) #define sortv(v) sort(v.begin(),v.end()) #define ayk ll t; cin>>t; while(t--) int main(){ ayk{ ll n; cin>>n; vll b; mll m; ll mx=0; floop(i,n){ cinv(b); m[b[i]]=1; } vll ans; floop(i,n){ ans.push_back(b[i]); fr(j,b[i]+1,(2*n) +1){ if(m[j]==0){ ans.push_back(j); m[j]=1; break; } } } if(ans.size() != 2*n) cout<<"-1\n"; else{ floop(i,ans.size()){ cout<<ans[i]<<" "; } cout<<endl; } } }
cpp
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
#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; char str[220]; pair<char,char> w[30]; bool sign; char ans[30]; bool st[30]; bool path(char ch,char t) { int p=ch-'a'; if(w[p].fi==t||w[p].se==t) return true; if(w[p].fi==0) { w[p].fi=t; return true; }else if(w[p].se==0) { w[p].se=t; return true; }else return false; } void dfs(int u) { if(u==3) { int res=0; if(w[ans[1]-'a'].fi!=0) res++; if(w[ans[1]-'a'].se!=0) res++; if(res==2) return ; if(res==1&&w[ans[1]-'a'].fi!=ans[2]) return ; } if(u>3&&u<=27) { char a=w[ans[u-2]-'a'].fi,b=w[ans[u-2]-'a'].se; if(a!=0&&b==0) { if(!(a==ans[u-3]||a==ans[u-1])) { return ; } }else if(a!=0&&b!=0) { if(!((a==ans[u-3]&&b==ans[u-1])||(a==ans[u-1]&&b==ans[u-3]))) { return ; } } } if(u>26) { if(w[ans[u-1]-'a'].se!=0) return ; if(w[ans[u-1]-'a'].fi!=0&&ans[u-2]!=w[ans[u-1]-'a'].fi) return ; sign=true; return ; } for(int i='a';i<='z';i++) { if(!st[i-'a']) { ans[u]=i; st[i-'a']=true; dfs(u+1); if(sign) return ; st[i-'a']=false; } } } void solve() { scanf("%s",str+1); n=strlen(str+1); if(n==1) { printf("YES\n"); for(int i='a';i<='z';i++) printf("%c",i); printf("\n"); return ; } memset(w,0,sizeof w); memset(st,false,sizeof st); memset(ans,0,sizeof ans); bool flag=true; sign=false; for(int i=2;i<=n;i++) { char a=str[i-1],b=str[i]; if(!path(a,b)) { flag=false; break; } if(!path(b,a)) { flag=false; break; } } int x=0,y=0; for(int i=0;i<26;i++) { if(w[i].se!=0) x++; if(w[i].fi!=0) y++; } if(y-x<2) flag=false; if(!flag) printf("NO\n"); else { dfs(1); if(!sign) printf("NO\n"); else { printf("YES\n"); for(int i=1;i<=26;i++) printf("%c",ans[i]); printf("\n"); } } } int main() { // init(); // stin(); scanf("%d",&T); // T=1; while(T--) solve(); return 0; }
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> #define pb push_back #define sz(v) ((int)(v).size()) using namespace std; using ll = long long; class Task { public: void solve() { int l; cin >> l; vector<ll> arr(l); for (int i = 0; i < l; i++) { cin >> arr[i]; } map<ll, vector<ll>> count_to_prize; ll tmp; for (int i = 0; i < l; i++) { cin >> tmp; count_to_prize[arr[i]].pb(tmp); } vector<pair<ll, vector<ll>>> book; for (auto p : count_to_prize) { book.pb({p.first, p.second}); } reverse(book.begin(), book.end()); ll result = 0; priority_queue<ll> q; ll q_total = 0; ll now_check = 0; while (!book.empty()) { if (q_total == 0 && book.back().first > now_check) { now_check = book.back().first; continue; } else if (book.back().first > now_check) { q_total -= q.top(); q.pop(); result += q_total; } else { for (int i : book.back().second) { q_total += i; q.push(i); } book.pop_back(); q_total -= q.top(); q.pop(); result += q_total; } now_check++; } while (!q.empty()) { q_total -= q.top(); q.pop(); result += q_total; } cout << result << endl; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); Task solver; solver.solve(); return 0; }
cpp
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; vector<int> func(vector<vector<int>> &roads, int x) { int n = roads.size(); queue<int> q; vector<int> dist(n, 1e9); q.push(x); dist[x] = 0; while (q.size()) { int a = q.front(); q.pop(); int d = dist[a]; for (int child : roads[a]) { if (dist[child] < 1e9) continue; dist[child] = d + 1; q.push(child); } } return dist; } // long loooooooooooooooong; void solve(ll kkkk, ll tttt) { int n, m, k; cin >> n >> m >> k; vector<vector<int>> roads(n); vector<int> ks(k); for (int i = 0; i < k; i++) cin >> ks[i], ks[i]--; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; x--, y--; roads[x].push_back(y); roads[y].push_back(x); } vector<int> d1 = func(roads, 0); vector<int> d2 = func(roads, n - 1); vector<pair<int, int>> v1(k); for (int i = 0; i < k; i++) v1[i].first = d1[ks[i]], v1[i].second = ks[i]; sort(v1.begin(), v1.end()); map<int, int> mapp; for (int i = 0; i < k; i++) mapp[d2[v1[i].second]]++; int ans = 0; for (int i = 0; i < k - 1; i++) { int f = v1[i].second; mapp[d2[f]]--; if (mapp[d2[f]] == 0) mapp.erase(d2[f]); ans = max(ans, d1[f] + mapp.rbegin()->first + 1); } ans = min(ans, d2[0]); cout << ans << endl; } void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main() { fast(); int t = 0, i = 0; // int t; cin >> t; // for (int i = 1; i <= t; i++) solve(t, 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> using namespace std; #define lb long double int n,m,Q,cnt,xl[51][2]; lb ans; inline int rd(){ int s=0;char ch=getchar();bool f=0; while(ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar(); while(ch>='0'&&ch<='9') s=(s<<3)+(s<<1)+(ch^48),ch=getchar(); return f?-s:s; } struct fyl{ #define NN 500 #define MM 200000 struct edge{ int ne,to,fl,di; }a[2*MM]; int num=1,head[NN],pr[NN],flow[NN],dis[NN]; bool vis[NN]; inline void clear(){ for(int i=2;i<=num;i++) head[a[i].to]=0; num=1; } inline void add(int u,int v,int w,int fl,bool tp=0){ a[++num]=(edge){head[u],v,fl,w}; head[u]=num;if(!tp) add(v,u,-w,0,1); } inline bool spfa(int u,int t){ queue<int> q; for(int i=1;i<=t;i++) dis[i]=0x3f3f3f3f; q.push(u),dis[u]=0,flow[u]=0x3f3f3f3f; while(!q.empty()){ u=q.front(),q.pop(),vis[u]=0; for(int v,i=head[u];i;i=a[i].ne){ v=a[i].to;if(!a[i].fl) continue; if(dis[v]>dis[u]+a[i].di){ dis[v]=dis[u]+a[i].di,pr[v]=i^1,flow[v]=min(flow[u],a[i].fl); if(!vis[v]) vis[v]=1,q.push(v); } } } return dis[t]!=0x3f3f3f3f; } inline void wll(int s,int t){ int fl=0,co=0; while(spfa(s,t)){ co+=dis[t]*flow[t],fl+=flow[t]; int u=t; while(u!=s){ a[pr[u]].fl+=flow[t],a[pr[u]^1].fl-=flow[t]; u=a[pr[u]].to; } //cout<<'['<<co<<','<<fl<<']'<<endl; xl[++cnt][1]=co,xl[cnt][0]=fl; } } }T; int main(){ n=rd(),m=rd(); for(int u,v,w,i=1;i<=m;i++){ u=rd(),v=rd(),w=rd(); T.add(u,v,w,1); } T.wll(1,n); Q=rd(); while(Q--){ int x=rd();ans=1000000000; for(int i=1;i<=cnt;i++){ lb res=1.0*(xl[i][1]+x)/xl[i][0]; if(ans-res>1e-7) ans=res; } printf("%.7Lf\n",ans); } return 0; }
cpp
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
/* B. Food Buying time limit per test: 1 second memory limit per test: 256 megabytes input: standard input output: standard output - Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. - Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s, buy food that costs exactly x burles and obtain ⌊x10⌋ burles as a cashback (in other words, Mishka spends x burles and obtains ⌊x10⌋ back). The operation ⌊ab⌋ means a divided by b rounded down. - It is guaranteed that you can always buy some food that costs x for any possible value of x. - Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. - For example, if Mishka has s=19 burles then the maximum number of burles he can spend is 21. Firstly, he can spend x=10 burles, obtain 1 burle as a cashback. Now he has s=10 burles, so can spend x=10 burles, obtain 1 burle as a cashback and spend it too. - You have to answer t independent test cases. -Input: The first line of the input contains one integer t (1≤t≤10^4) — the number of test cases. The next t lines describe test cases. Each test case is given on a separate line and consists of one integer s (1≤s≤10^9) — the number of burles Mishka initially has. -Output: For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally. -Example: input: 6 1 10 19 9876 12345 1000000000 output: 1 11 21 10973 13716 1111111111 */ #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = (cin >> t, t); while (t--) { int s = (cin >> s, s); if (s < 10) cout << s << endl; else { if (s % 9) cout << s / 9 << s % 9 << endl; else cout << (s / 9) - 1 << 9 << endl; } } return 0; }
cpp
1286
E
E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string SS, initially empty, and an array WW, also initially empty.There are nn queries to process, one at a time. Query ii consists of a lowercase English letter cici and a nonnegative integer wiwi. First, cici must be appended to SS, and wiwi must be appended to WW. The answer to the query is the sum of suspiciousnesses for all subsegments of WW [L, R][L, R], (1≤L≤R≤i)(1≤L≤R≤i).We define the suspiciousness of a subsegment as follows: if the substring of SS corresponding to this subsegment (that is, a string of consecutive characters from LL-th to RR-th, inclusive) matches the prefix of SS of the same length (that is, a substring corresponding to the subsegment [1, R−L+1][1, R−L+1]), then its suspiciousness is equal to the minimum in the array WW on the [L, R][L, R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 00.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer nn (1≤n≤600000)(1≤n≤600000) — the number of queries.The ii-th of the following nn lines contains the query ii: a lowercase letter of the Latin alphabet cici and an integer wiwi (0≤wi≤230−1)(0≤wi≤230−1).All queries are given in an encrypted form. Let ansans be the answer to the previous query (for the first query we set this value equal to 00). Then, in order to get the real query, you need to do the following: perform a cyclic shift of cici in the alphabet forward by ansans, and set wiwi equal to wi⊕(ans & MASK)wi⊕(ans & MASK), where ⊕⊕ is the bitwise exclusive "or", && is the bitwise "and", and MASK=230−1MASK=230−1.OutputPrint nn lines, ii-th line should contain a single integer — the answer to the ii-th query.ExamplesInputCopy7 a 1 a 0 y 3 y 5 v 4 u 6 r 8 OutputCopy1 2 4 5 7 9 12 InputCopy4 a 2 y 2 z 0 y 2 OutputCopy2 2 2 2 InputCopy5 a 7 u 5 t 3 s 10 s 11 OutputCopy7 9 11 12 13 NoteFor convenience; we will call "suspicious" those subsegments for which the corresponding lines are prefixes of SS, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string SS is equal to "abacaba", and all wi=1wi=1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 11. Let's see how the answer is obtained after each request:1. SS = "a", the array WW has a single subsegment — [1, 1][1, 1], and the corresponding substring is "a", that is, the entire string SS, thus it is a prefix of SS, and the suspiciousness of the subsegment is 11.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] and [1, 2][1, 2], total 22.3. SS = "aba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3] and [3, 3][3, 3], total 44.4. SS = "abac", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] and [3, 3][3, 3], total 55.5. SS = "abaca", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [3, 3][3, 3] and [5, 5][5, 5], total 77.6. SS = "abacab", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [3, 3][3, 3], [5, 5][5, 5] and [5, 6][5, 6], total 99.7. SS = "abacaba", suspicious subsegments: [1, 1][1, 1], [1, 2][1, 2], [1, 3][1, 3], [1, 4][1, 4] , [1, 5][1, 5], [1, 6][1, 6], [1, 7][1, 7], [3, 3][3, 3], [5, 5][5, 5], [5, 6][5, 6], [5, 7][5, 7] and [7, 7][7, 7], total 1212.In the second example, after all requests SS = "aaba", W=[2,0,2,0]W=[2,0,2,0].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (suspiciousness 22), totaling 22.2. SS = "aa", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [2, 2][2, 2] ( 00), totaling 22.3. SS = "aab", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [2, 2][2, 2] (00), totaling 22.4. SS = "aaba", suspicious subsegments: [1, 1][1, 1] (22), [1, 2][1, 2] (00), [1, 3][1, 3] ( 00), [1, 4][1, 4] (00), [2, 2][2, 2] (00), [4, 4][4, 4] (00), totaling 22.In the third example, from the condition after all requests SS = "abcde", W=[7,2,10,1,7]W=[7,2,10,1,7].1. SS = "a", suspicious subsegments: [1, 1][1, 1] (77), totaling 77.2. SS = "ab", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), totaling 99.3. SS = "abc", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), totaling 1111.4. SS = "abcd", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), totaling 1212.5. SS = "abcde", suspicious subsegments: [1, 1][1, 1] (77), [1, 2][1, 2] (22), [1, 3][1, 3] ( 22), [1, 4][1, 4] (11), [1, 5][1, 5] (11), totaling 1313.
[ "data structures", "strings" ]
#include <algorithm> #include <iostream> #include <vector> #include <cstdio> #include <map> #define int long long #define maxn 600005 using namespace std; inline int read(){ int x = 0, flag = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') flag = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); } return x * flag; } inline int readc(){ char ch = getchar(); while(ch < 'a' || ch > 'z') ch = getchar(); return ch - 'a' + 1; } const int MASK = (1 << 30) - 1; int n, nxt[maxn], lst[maxn][30], s[maxn], w[maxn], SUM; __int128 lstans; bool vis[maxn]; map <int, int> mp; int q[maxn], top; vector <int> tmp; int getlst(int x, int c){ if(!x) return 0; if(!vis[x]) return x; return lst[x][c] = getlst(lst[x][c], c); } void write(__int128 x){ if(x / 10) write(x / 10); putchar(x % 10 + '0'); return; } signed main(){ n = read(); for(int i = 1, j = 0; i <= n; ++i){ s[i] = readc(), w[i] = read(); s[i] = ((s[i] + lstans - 1) % 26) + 1; w[i] = w[i] ^ (lstans & MASK); // cout<<s[i]<<' '<<w[i]<<endl; int now = i - 1; while(now = getlst(lst[now][s[i]], s[i])){ vis[now] = 0; int mn = w[q[lower_bound(q + 1, q + top + 1, i - now) - q]]; SUM -= mn; --mp[mn]; if(!mp[mn]) mp.erase(mn); // cout<<"del "<<mn<<endl; } int cnt = 0; for(auto id = mp.end(); id != mp.begin(); --id){ auto x = id; --x; if(x -> first > w[i]){ // cout << "change "<<x.first<<endl; cnt += x -> second; SUM -= x -> second * x -> first; tmp.push_back(x -> first); }else break; } for(auto x : tmp) mp.erase(x); tmp.clear(); mp[w[i]] += cnt; SUM += cnt * w[i]; while(top && w[q[top]] >= w[i]) --top; q[++top] = i; if(s[i] == s[1]) ++mp[w[i]], SUM += w[i]; lstans += SUM; write(lstans), putchar('\n'); if(i == 1) continue; while(j && s[i] != s[j + 1]) j = nxt[j]; if(s[i] == s[j + 1]) ++j; nxt[i] = j; for(int c = 1; c <= 26; ++c){ if(s[nxt[i] + 1] != c) lst[i][c] = nxt[i]; else lst[i][c] = lst[nxt[i]][c]; // cout << "lst "<<i<<' '<<c<<" = "<<lst[i][c]<<endl; } } 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"bits/stdc++.h" using namespace std; #define endl '\n' #define ll long long const ll mod = 1e9 + 7; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll a, fa, sum=0; cin>>a; fa = a; for (ll i=2; i<a; i++) { fa=a; while (fa>0) { sum+=fa%i; fa/=i; } } cout<<sum/(__gcd(sum, a-2))<<"/"<<(a-2)/(__gcd(sum, a-2)); }
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> #include <fstream> #include <cstdlib> #include<conio.h> #include <windows.h> #include <stdlib.h> #include <time.h> #define pb push_back #define ll long long #define dbl double #define srt(massiv) sort(massiv.begin(),massiv.end()) #define rvrs(massiv) reverse(massiv.begin(),massiv.end()) #define srtr(massiv) sort(massiv.rbegin(),massiv.rend()) #define yes cout<<"yes"<<endl #define no cout<<"no"<<endl #define Yes cout<<"Yes"<<endl #define No cout<<"No"<<endl #define YES cout<<"YES"<<endl #define NO cout<<"NO"<<endl #define en "\n" #define Minecraft for(cin>>MC;MC--;) #define ReallyWorld ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); using namespace std; /// cout << fixed << X ; ///ifstream cin("input.txt"); ///ofstream cout("output.txt") ; ll cnt,qnt,cns,qns,n,m,k,i,j,T,x,y,z,a,b,MC; ll arr1 [100005]; ll arr2 [100005]; main() { ReallyWorld for(cin>>T; T--; puts(((ceil(sqrt(m)*2)<=n+1)?("YES"):("NO")))) cin>>n>>m; } /** ███╗ ███╗███████╗██████╗ ██╗███╗ ██╗███████╗███████╗███████╗███╗ ███╗ ████╗ ████║██╔════╝██╔══██╗██║████╗ ██║██╔════╝██╔════╝██╔════╝████╗ ████║ ██╔████╔██║█████╗ ██████╦╝██║██╔██╗██║█████╗ █████╗ █████╗ ██╔████╔██║ ██║╚██╔╝██║██╔══╝ ██╔══██╗██║██║╚████║██╔══╝ ██╔══╝ ██╔══╝ ██║╚██╔╝██║ ██║ ╚═╝ ██║███████╗██████╦╝██║██║ ╚███║███████╗███████╗███████╗██║ ╚═╝ ██║ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═╝╚═╝ ╚══╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝ ▄▄▄ ▄▄██▄▄ ████▄ ███████ █████▄████████ ▀█████████████ ▄▄ ▀▀▀██████▄██████▄▄ ▄████ ███ ▀████████████ ▄██████ ▀▀▀ ▄█ ▀███████████ ▀▀ █▄▄███ █████████▀ ▀█████ ▀███▀▀ ██████▀ ██▄ ███████▄ █████ ████████▄ ▄██████ ▀███████▀ ████████ ▀████▀ █████████ ████████▀ ▀██████▀ ▀▀▀ **/
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<long long> vll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; const double PI = acos(-1); const ll mod7 = 1e9 + 7; const ll mod9 = 998244353; const ll INF = 2 * 1024 * 1024 * 1023; const char nl = '\n'; #define forn(i, n) for (int i = 0; i < int(n); i++) #define all(v) v.begin(),v.end() #pragma GCC optimize("O2") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") ll l, r, k, n, m, p, q, u, v, w, x, y, z; string s, t; vi d4x = {1, 0, -1, 0}; vi d4y = {0, 1, 0, -1}; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // uniform_int_distribution<int>(1, 20)(rng) //////////////////// LIBRARY CODE //////////////////// #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update>; /////////////////////////////////////////////////////// bool multiTest = 0; void solve(int tt){ cin >> n; map<int, vi> val; vector<pii> pubs(n); forn(i, n) cin>> pubs[i].first; forn(i, n) cin >> pubs[i].second; forn(i, n) { val[pubs[i].first].push_back(pubs[i].second); } ll ans = 0; priority_queue<int> nums; ll cur = 0; ll lastVal = -1e9; for(auto [y,z] : val) { while(nums.size() && lastVal != y) { cur -= nums.top(); ans += cur; nums.pop(); lastVal++; } for(auto z1 : z) { nums.push(z1); cur += z1; } lastVal = y; } while(nums.size()) { cur -= nums.top(); ans += cur; nums.pop(); lastVal++; } cout << ans << nl; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifdef yangster freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); // #else // freopen("cowpatibility.in", "r", stdin); // freopen("cowpatibility.out", "w", stdout); #endif cout << fixed << setprecision(14); int t = 1; if (multiTest) cin >> t; for (int ii = 0; ii < t; ii++) { solve(ii + 1); } }
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" ]
//Your worst fear owns this #include <bits/stdc++.h> #define ll long long int #define srv(v) sort(v.begin(),v.end()) #define rrv(s1) sort(s1.begin(),s1.end(),greater<ll>()) #define str string #define sz size() #define dv(v) vector<ll> v #define ds(s) set<ll> s #define dm(mp) map<ll,ll> mp #define MOD 1000000007 #define debug(x) cout<<#x<<" "<<x<<endl int binpow(int a, int b){if (b==1){return a;}else if (b==0){return 1;}ll one = binpow(a,b/2);if (b%2==0){return one*one;}else{return a*one*one;}} using namespace std; int dp[2001][2001]; int knap(vector<int> &v, int st,int cur, int h,int l, int r){ if (st>=v.sz) { if (l<=cur&&cur<=r) { return 1; } return 0; } if (dp[st][cur]!=-1) { return dp[st][cur]; } int tot=0; if (l<=cur&&cur<=r&&st!=0) { tot++; } int ne1 = cur+v[st]; ne1%=h; int ne2 = cur+(v[st]-1); ne2%=h; tot+=max(knap(v,st+1,ne1,h,l,r),knap(v,st+1,ne2,h,l,r)); return dp[st][cur] = tot; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,h,l,r; cin>>n>>h>>l>>r; vector<int> v; memset(dp,-1,sizeof(dp)); for (int i = 0; i < n; i++) { int x; cin>>x; v.push_back(x); } knap(v,0,0,h,l,r); cout<<dp[0][0]<<endl; return 0; }
cpp
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
using namespace std; #include <bits/stdc++.h> #define int long long #define repp(n) for(int i=0;i<n;i++) #define mod 1000000007 void solve() { int n,k,ans=0;cin>>n>>k; string a[n]; repp(n)for(int j=0;j<k;j++){ char c;cin>>c; a[i]+=c; } map<string,int> m; repp(n)m[a[i]]++; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ string temp; for(int f=0;f<k;f++){ int a1=0,a2=0,a3=0; if(a[i][f]=='S') a1++; if(a[i][f]=='E') a2++; if(a[i][f]=='T') a3++; if(a[j][f]=='S') a1++; if(a[j][f]=='E') a2++; if(a[j][f]=='T') a3++; if(a1==2) temp+='S'; else if(a2==2) temp+='E'; else if(a3==2) temp+='T'; else if(a1==0) temp+='S'; else if(a2==0) temp+='E'; else if(a3==0) temp+='T'; } //cout<<i+1<<" "<<j+1<<" "<<temp<<endl<<endl; if(m.find(temp)!=m.end() && temp!=a[i] && temp!=a[j]) ans++; } } cout<<ans/3<<endl; } #define int int int main() { std::ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0); //int t;cin>>t;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" ]
// LUOGU_RID: 99815778 #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
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<iostream> using namespace std; int main(){ int t; cin>>t; while(t--){ string s; cin>>s; bool flag=false; int first_index=0; for(int i=0;i<s.length();i++){ if(s[i]=='1'){ first_index=i; break; } } int second_index=0; for(int i=s.length()-1;i>=0;i--){ if(s[i]=='1'){ second_index=i; break; } } int c=0; for(int i=first_index;i<second_index;i++){ if(s[i]=='0') c++; } cout<<c<<endl; } 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> #include <random> #include <chrono> using namespace std; //#pragma GCC optimize("Ofast") //#pragma GCC optimize ("unroll-loops") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int,int> pii; typedef pair<ll,ll> pll; //typedef pair<double,double> pdd; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); template<typename T> void _do(T x){cerr<<x<<"\n";} template<typename T,typename ...U> void _do(T x,U ...y){cerr<<x<<", ";_do(y...);} #define dbg(...) cerr<<#__VA_ARGS__<<" = ";_do(__VA_ARGS__); const int MOD1=1e9+7; const int MOD2=998244353; const ll INF=3e18; const ld PI=3.14159265358979323846; ll gcd(ll a,ll b){if(b==0) return a; return gcd(b,a%b);} ll fpow(ll a,ll b,ll m) { if(!b) return 1; ll ans=fpow(a*a%m,b/2,m); return (b%2?ans*a%m:ans); } ll inv(ll a,ll m) {return fpow(a,m-2,m);} #define MottoHayaku ios::sync_with_stdio(false);cin.tie(0); //#define int ll #define rep(i,n) for(int i=0;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define repk(i,m,n) for(int i=m;i<n;i++) #define F first #define S second #define pb push_back #define uni(c) c.resize(distance(c.begin(),unique(c.begin(),c.end()))) #define unisort(c) sort(c.begin(),c.end()),uni(c) #define X first #define Y second typedef pair<ll,ll> pdd; const double eps=1e-9; pdd operator+(pdd a,pdd b){return pdd(a.X+b.X,a.Y+b.Y);} pdd operator-(pdd a,pdd b){return pdd(a.X-b.X,a.Y-b.Y);} pdd operator*(pdd a,double b){return pdd(a.X*b,a.Y*b);} pdd operator/(pdd a,double b){return pdd(a.X/b,a.Y/b);} double dot(pdd a,pdd b){return a.X*b.X+a.Y*b.Y;} double cross(pdd a,pdd b){return a.X*b.Y-a.Y*b.X;} double abs2(pdd a){return dot(a,a);} double abs(pdd a){return sqrt(dot(a,a));} int sign(double a){return fabs(a)<eps?0:a>0?1:-1;} int ori(pdd a,pdd b,pdd c){return sign(cross(b-a,c-a));} bool collinear(pdd a,pdd b,pdd c){return sign(cross(a-c,b-c))==0;} bool btw(pdd a,pdd b,pdd c){return !collinear(a,b,c)?0:sign(dot(a-c,b-c))<=0;}//is C between AB pdd proj(pdd a,pdd b,pdd c){return (b-a)*dot(c-a,b-a)/abs2(b-a);}//ac projection on ab double dist(pdd a,pdd b,pdd c){return abs(cross(c-a,b-a))/abs(b-a);}//distance from C to AB bool cmp(pdd a,pdd b)//polar angle sort { #define is_neg(k) (sign(k.Y)<0||(sign(k.Y)==0&&sign(k.X)<0)) int A=is_neg(a),B=is_neg(b); if(A!=B) return A<B; if(sign(cross(a,b))==0) return abs2(a)<abs2(b); return sign(cross(a,b))>0; } vector<pdd> convex_hull(vector<pdd> dots) { sort(dots.begin(),dots.end()); vector<pdd> hull(1,dots[0]); for(int ct=0;ct<=1;ct++) { int t=hull.size(); for(int i=1;i<dots.size();i++) { while(hull.size()>t&&ori(hull[hull.size()-2],hull.back(),dots[i])<=0) hull.pop_back(); hull.pb(dots[i]); } reverse(dots.begin(),dots.end()); } hull.pop_back(); return hull; } bool seg_sect(pdd p1,pdd p2,pdd p3,pdd p4)//does p1p2 intersect p3p4 { int a123=ori(p1,p2,p3); int a124=ori(p1,p2,p4); int a341=ori(p3,p4,p1); int a342=ori(p3,p4,p2); if(a123==0&&a124==0) return btw(p1,p2,p3)||btw(p1,p2,p4)||btw(p3,p4,p1)||btw(p3,p4,p2); else return a123*a124<=0&&a341*a342<=0; } signed main() { MottoHayaku ll n; cin>>n; vector<pll> p(n); rep(i,n) cin>>p[i].F>>p[i].S; ll ans=0; rep(i,n) { //dbg(i); vector<pll> tmp; rep(j,n) if(i!=j) tmp.pb(p[j]-p[i]); sort(tmp.begin(),tmp.end(),cmp); rep(j,n-1) tmp.pb(tmp[j]); vector<ll> pos(n-1,0); ll cur=0; rep(j,n-1) { //dbg(tmp[j].F,tmp[j].S); cur=max(cur,(ll)j); while(cur+1<j+(n-1)&&cross(tmp[j],tmp[(cur+1)])>=0) cur++; pos[j]=cur; //dbg(pos[j]); } ll tot=0; rep1(j,pos[0]) tot+=pos[j%(n-1)]-pos[0]; rep(j,n-1) { //dbg(j,tot); ans+=tot; if(j==n-2) break; ll d=pos[j]-j; //dbg(d); tot-=d*(pos[j+1]-pos[j]); for(int k=pos[j]+1;k<=pos[j+1];k++) { if(k>=n-1) tot+=pos[k%(n-1)]+n-1-pos[j+1]; else tot+=pos[k]-pos[j+1]; } } //dbg(ans); } cout<<ans*(n-4)/6<<"\n"; }
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> #define sz(v) ((int)(v).size()) #define all(v) (v).begin(), (v).end() using namespace std; typedef long long lint; typedef pair<lint, int> pi; const int MAXN = 300005; vector<int> gph[MAXN]; int dist[2][MAXN]; void bfs(int x, int *dist){ dist[x] = 0; queue<int> que; que.push(x); while(sz(que)){ int x = que.front(); que.pop(); for(auto &j : gph[x]){ if(dist[j] > dist[x] + 1){ que.push(j); dist[j] = dist[x] + 1; } } } } int main(){ int n; scanf("%d",&n); int m, k; scanf("%d %d",&m,&k); vector<int> v(k); for(auto &i : v){ scanf("%d",&i); } for(int i=1; i<=m; i++){ int s, e; scanf("%d %d",&s,&e); gph[s].push_back(e); gph[e].push_back(s); } memset(dist, 0x3f, sizeof(dist)); bfs(1, dist[0]); bfs(n, dist[1]); sort(all(v), [&](const int &a, const int &b){ return dist[0][a] - dist[1][a] < dist[0][b] - dist[1][b]; }); int cur = -1e9; int ret = -1e9; for(int i=0; i<sz(v); i++){ ret = max(ret, 1 + dist[1][v[i]] + cur); cur = max(cur, dist[0][v[i]]); } cout << min(dist[1][1], ret) << 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" ]
#include<cstdio> #include<cstdlib> #include<utility> #include<vector> #include<random> #define mod 998244353 std::mt19937 seed(*new int); std::pair<long long,int> operator +(std::pair<long long,int> x,std::pair<long long,int> y) {return std::make_pair(x.first+y.first,x.second+y.second);} struct tree { std::pair<long long,int> s[2100005]; void pushup(int k){s[k]=s[k*2]+s[k*2+1];} void update(int k,int l,int r,int x) { if (l==r) return s[k]=s[k]+std::make_pair(1ll*x,1),void(); int mid=(l+r)/2; if (x<=mid) update(k*2,l,mid,x); if (mid<x) update(k*2+1,mid+1,r,x); pushup(k); } long long ask(int k,int l,int r,int x) { if (x<=l) return s[k].first-1ll*s[k].second*(x-1); int mid=(l+r)/2; long long ans=0; if (x<=mid) ans=ans+ask(k*2,l,mid,x); ans=ans+ask(k*2+1,mid+1,r,x); return ans; } }; tree tt; int n,m; char s[500005],t[500005],p[1000005]; int f[500005],g[500005]; long long sh[500005],th[500005],ph[1000005],pw[1000005],base,ans=0; std::vector<long long> add[1000005],del[1000005]; int getrd(int l,int r){std::uniform_int_distribution<int> rd(l,r);return rd(seed);} long long getph(int l,int r){return ((ph[r]-ph[l-1]*pw[r-l+1])%mod+mod)%mod;} long long getsh(int l,int r){return ((sh[r]-sh[l-1]*pw[r-l+1])%mod+mod)%mod;} long long getth(int l,int r){return ((th[r]-th[l-1]*pw[r-l+1])%mod+mod)%mod;} int lcp(int k,int l,int r) { if (l==r) return l; int mid=(l+r+1)/2; if (getph(1,mid)==getsh(k,k+mid-1)) return lcp(k,mid,r); return lcp(k,l,mid-1); } int lcs(int k,int l,int r) { if (l==r) return l; int mid=(l+r+1)/2; if (getph(m-mid+1,m)==getth(k-mid+1,k)) return lcs(k,mid,r); return lcs(k,l,mid-1); } int main() { base=getrd(10000,20000); scanf("%d%d",&n,&m); scanf("%s",s+1); scanf("%s",t+1); scanf("%s",p+1); pw[0]=1;for (int i=1;i<=n;i++) pw[i]=pw[i-1]*base%mod; for (int i=1;i<=n;i++) sh[i]=(sh[i-1]*base+s[i])%mod,th[i]=(th[i-1]*base+t[i])%mod; for (int i=1;i<=m;i++) ph[i]=(ph[i-1]*base+p[i])%mod; for (int i=1;i<=n;i++) { f[i]=(s[i]!=p[1]?0:lcp(i,1,n-i+1)); g[i]=(t[i]!=p[m]?0:lcs(i,1,i)); } for (int i=1;i<=n;i++) { add[i].push_back(std::max(m-f[i],1)); if (i+m-1<=n) del[i+m-1].push_back(std::max(m-f[i],1)); } for (int i=n;i>=1;i--) { tt.update(1,0,m,std::min(g[i],m-1)); for (int d=0;d<(int)add[i].size();d++) ans=ans+tt.ask(1,0,m,add[i][d]); for (int d=0;d<(int)del[i].size();d++) ans=ans-tt.ask(1,0,m,del[i][d]); } printf("%lld\n",ans); return 0; }
cpp
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" ]
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> #include <ext/rope> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/hash_policy.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_cxx; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>; using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>; // template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>; template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>; #define ll long long #define i128 __int128 #define ld long double #define ui unsigned int #define ull unsigned long long #define pii pair<int, int> #define pll pair<ll, ll> #define pdd pair<ld, ld> #define vi vector<int> #define vvi vector<vector<int>> #define vll vector<ll> #define vvll vector<vector<ll>> #define vpii vector<pii> #define vpll vector<pll> #define lb lower_bound #define ub upper_bound #define pb push_back #define pf push_front #define eb emplace_back #define fi first #define se second #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 each(x, v) for(auto& x: v) #define len(x) (int)x.size() #define elif else if #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define mst(x, a) memset(x, a, sizeof(x)) #define lowbit(x) (x & (-x)) #define bitcnt(x) (__builtin_popcountll(x)) #define endl "\n" mt19937 rng( chrono::steady_clock::now().time_since_epoch().count() ); #define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a) 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); } size_t operator()(pair<uint64_t,uint64_t> x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1); } }; const i128 ONE = 1; istream &operator>>(istream &in, i128 &x) { string s; in >> s; bool minus = false; if (s[0] == '-') { minus = true; s.erase(s.begin()); } x = 0; for (auto i : s) { x *= 10; x += i - '0'; } if (minus) x = -x; return in; } ostream &operator<<(ostream &out, i128 x) { string s; bool minus = false; if (x < 0) { minus = true; x = -x; } while (x) { s.push_back(x % 10 + '0'); x /= 10; } if (s.empty()) s = "0"; if (minus) out << '-'; reverse(s.begin(), s.end()); out << s; return out; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const set<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) { os << p.first << " " << p.second; return os; } ll gcd(ll x,ll y) { if(!x) return y; if(!y) return x; int t = __builtin_ctzll(x | y); x >>= __builtin_ctzll(x); do { y >>= __builtin_ctzll(y); if(x > y) swap(x, y); y -= x; } while(y); return x<<t; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) return x = 1, y = 0, a; ll d = exgcd(b, a % b, x, y); ll t = x; x = y; y = t - a / b * x; return d; } ll max(ll x, ll y) { return x > y ? x : y; } ll min(ll x, ll y) { return x < y ? x : y; } ll Mod(ll x, int mod) { return (x % mod + mod) % mod; } ll pow(ll x, ll y, ll mod){ ll res = 1, cur = x; while (y) { if (y & 1) res = res * cur % mod; cur = ONE * cur * cur % mod; y >>= 1; } return res % mod; } ll probabilityMod(ll x, ll y, ll mod) { return x * pow(y, mod-2, mod) % mod; } vvi getGraph(int n, int m, bool directed = false) { vvi res(n); rep(_, 0, m) { int u, v; cin >> u >> v; u--, v--; res[u].emplace_back(v); if(!directed) res[v].emplace_back(u); } return res; } vector<vpii> getWeightedGraph(int n, int m, bool directed = false) { vector<vpii> res(n); rep(_, 0, m) { int u, v, w; cin >> u >> v >> w; u--, v--; res[u].emplace_back(v, w); if(!directed) res[v].emplace_back(u, w); } return res; } const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const int N = 1e6 + 10; void solve() { int n; cin >> n; vi a(n); each(i, a) cin >> i; auto calc = [&] (int bit) -> int { vi h; each(i, a) h.pb(i % (1 << bit + 1)); sort(all(h)); int res = 0; each(i, h) { res += ub(all(h), (1 << bit + 1) - 1 - i) - lb(all(h), (1 << bit) - i); if ((1 << bit) - i <= i && i <= (1 << bit + 1) - 1 - i) res -= 1; res += ub(all(h), (1 << bit + 2) - 2 - i) - lb(all(h), (0b11 << bit) - i); if ((0b11 << bit) - i <= i && i <= (1 << bit + 2) - 2 - i) res -= 1; } return res >> 1 & 1; }; int ans = 0; rep(bit, 0, 25) ans |= calc(bit) << bit; cout << ans << endl; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }
cpp
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4 ababcd abcba a b defi fed xyz x OutputCopyYES NO NO YES
[ "dp", "strings" ]
#pragma GCC optimize("O2") #pragma GCC target("avx,avx2,fma") #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 ll long long #define test int _TEST; cin>>_TEST; while(_TEST--) #define ff first #define ss second #define pb push_back #define ppb pop_back #define pf push_front #define ppf pop_front template <typename T> using Ordered_Set_Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> using Ordered_Multiset_Tree = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename A, typename B> ostream& operator<<(ostream& s, const pair<A, B>& self) {s << self.first << ' ' << self.second << ' '; return s; } template <typename T> ostream& operator<<(ostream& s, const vector<T>& self) { for (auto e : self) { s << e << '\n'; } return s; } template <typename T> ostream& operator<<(ostream& s, tuple<T, T, T>& self) { s << get<0>(self) << ' ' << get<1>(self) << ' ' << get<2>(self); return s; } template <typename A, typename B> istream& operator>>(istream& s, pair<A, B>& self) { s >> self.first >> self.second; return s; } template <typename T> istream& operator>>(istream& s, tuple<T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self); return s; } template <typename T> istream& operator>>(istream& s, tuple<T, T, T, T>& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self) >> get<3>(self); return s; } template <typename T> istream& operator>>(istream& s, vector<T>& self) { for (size_t i = 0; i < self.size(); ++i) { s >> self[i]; } return s; } ///DEBUG void _Print(int t) {cerr << t;} void _Print(string t) {cerr << t;} void _Print(char t) {cerr << t;} void _Print(long long t) {cerr << t;} void _Print(double t) {cerr << t;} void _Print(unsigned long long t) {cerr << t;} template <class T, class V> void _Print(pair <T, V> &p); template <class T> void _Print(list <T> &v); template <class T> void _Print(vector <T> &v); template <class T> void _Print(deque <T> &v); template <class T, class V> void _Print(T *v, V sz); template <class T, class V, class P> void _Print(T *v, V sz, P sm); 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 << "}\n\n";} template <class T> void _Print(list <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} template <class T> void _Print(vector <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} template <class T> void _Print(deque <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} template <class T, class V> void _Print(T *v, V sz) {cerr << "[ "; for(int i=0; i<sz; i++) {_Print(v[i]); cerr << " ";} cerr << "]\n\n";} template <class T, class V, class P> void _Print(T *v, V sz, P sm) {cerr << "[\n"; for(int i=0; i<sz; i++) { for(int j=0; j<sm; j++) {_Print(v[i][j]); cerr << " ";} cerr << "\n";} cerr << "]\n\n";} template <class T> void _Print(set <T> &v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} template <class T> void _Print(multiset <T>& v) {cerr << "[ "; for (T i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} template <class T, class V> void _Print(map <T, V> &v) {cerr << "[ "; for (auto i : v) {_Print(i); cerr << " ";} cerr << "]\n\n";} #define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__) vector<string> vec_splitter(string s) { s += ','; vector<string> res; while(!s.empty()) { res.push_back(s.substr(0, s.find(','))); s = s.substr(s.find(',') + 1); } return res; } void debug_out(vector<string> __attribute__ ((unused)) args, __attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; } template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) { if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") "; stringstream ss; ss << H; cerr << args[idx] << " = " << ss.str(); debug_out(args, idx + 1, LINE_NUM, T...); } ///DEBUG int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); test { string s, t; cin>>s>>t; vector<vector<int>> nextPos(s.size()+1, vector<int> (26, 1e9)); for(int i=0; i<s.size(); i++) { for(int j=i; j<s.size(); j++) nextPos[i][s[j]-'a'] = min(nextPos[i][s[j]-'a'], j); } vector<vector<int>> dp(s.size()+2, vector<int> (s.size()+2)); auto cal = [&](string a, string b) { for(int i=0; i<=a.size(); i++) { for(int j=0; j<=b.size(); j++) dp[i][j] = 1e9; } dp[0][0] = 0; for(int i=0; i<=a.size(); i++) { for(int j=0; j<=b.size(); j++) { if(dp[i][j] > s.size()) continue; int lenS = dp[i][j]; if(i<a.size() && nextPos[lenS][a[i]-'a']<1e9) dp[i+1][j] = min(dp[i+1][j], nextPos[lenS][a[i]-'a']+1); if(j<b.size() && nextPos[lenS][b[j]-'a']<1e9) dp[i][j+1] = min(dp[i][j+1], nextPos[lenS][b[j]-'a']+1); } } return (dp[a.size()][b.size()] <= s.size()); }; int poss = 0; for(int i=0; i<t.size(); i++) { if(cal(t.substr(0, i), t.substr(i, t.size()-i))) { poss = 1; break; } } if(poss) cout<<"YES\n"; else cout<<"NO\n"; } }
cpp
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
#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; const ll N = 4e5+500 , LOG = 22 , inf = 1e8 , SQ= 550 , mod= 1e9+7;//998244353; 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; } template <typename T> using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>; ll mul (ll a, ll b){ return ( ( a % mod ) * ( b % mod ) ) % mod; } ll add (ll a , ll b) { return (a + b + mod) % mod; } template< typename T > using min_heap = priority_queue <T , vector <T > , greater < T > > ; void hi(int tc) { ll h , n; cin >> h >> n; vector <ll> a(n); for (ll &i : a) cin >> i; ll sum = 0; ll mn= 0; for (int i = 0; i < n; ++i){ sum+=a[i]; if (sum+h <= 0){cout << i+1 << nd;return;} mn = min(mn , sum); } if(sum >= 0){cout << -1 << nd; return;} ll temp = h + mn; ll nume = abs(sum); ll k = temp/nume; h+= k * sum; int i = -1; ll ans = k * n; while (h > 0){ ++i , ans++; h+=a[i % n]; } cout << ans <<nd; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int tt = 1 , tc = 0; //cin >> tt; while(tt--) hi(++tc); 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" ]
// LUOGU_RID: 92279710 #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
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> //#include<ext/pb_ds/assoc_container.hpp> //#include<ext/pb_ds/tree_policy.hpp> #pragma GCC optimize("unroll-loops,no-stack-protector,Ofast") using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef pair<ll, ll> pll; typedef long double ld; //typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define pb push_back #define mp make_pair #define fi first #define se second #define lwb lower_bound #define setp setprecision #define SZ(_a) (ll)(_a).size() #define SQ(_a) ((_a)*(_a)) #define all(_a) (_a).begin(), (_a).end() #define chmax(_a, _b) _a = max(_a, _b) #define chmin(_a, _b) _a = min(_a, _b) template <class T> inline ostream& operator << (ostream& out, vector<T> v) { for (int i = 0;i < SZ(v); ++i) out << v[i] << (i == SZ(v)-1 ? "" : " "); return out; } template <class T> inline ostream& operator << (ostream& out, pair<T, T> p) { out << "(" << p.fi << ", " << p.se << ")"; return out; } template <class A, class B> inline pair<A, B> operator + (pair<A, B> pA, pair<A, B> pB) { return make_pair(pA.fi+pB.fi, pA.se+pB.se); } template <class A, class B> inline pair<A, B> operator - (pair<A, B> pA, pair<A, B> pB) { return make_pair(pA.fi-pB.fi, pA.se-pB.se); } template <class A, class B, class C> inline pair<A, B> operator * (pair<A, B> pA, C pB) { return make_pair(pA.fi*pB, pA.se*pB); } const ll N = 4e2 + 5; const ll MOD = 1e9 + 7; const ld pi = acos(-1); const ll INF = 1e9; struct edge { ll y, c, f, cost; edge() {}; edge(ll y, ll c, ll f, ll cost): y(y), c(c), f(f), cost(cost) {}; }; ll bal[N][N], u[N], v[N]; ll s, t, os, ot, V; vector<ll> g[N]; vector<edge> e; ll n1, n2, r, b, m; string s1, s2; void add(ll x, ll y, ll cap, ll cost) { g[x].pb(SZ(e)); e.pb(edge(y, cap, 0, cost)); g[y].pb(SZ(e)); e.pb(edge(x, 0, 0, -cost)); } void add_LR(ll x, ll y, ll lcap, ll rcap, ll cost) { ll last = rcap - lcap; if (lcap > 0) { add(s, y, lcap, cost); add(x, t, lcap, cost); } if (last > 0) add(x, y, last, cost); } void ins_l(ll x) { if (s1[x] == 'R') { add_LR(os, x, 1, m, 0); } else if (s1[x] == 'B') { add_LR(x, ot, 1, m, 0); } else { add(os, x, m, 0); add(x, ot, m, 0); } } void ins_r(ll x) { if (s2[x] == 'R') { add_LR(x+n1, ot, 1, m, 0); } else if (s2[x] == 'B') { add_LR(os, x+n1, 1, m, 0); } else { add(os, x+n1, m, 0); add(x+n1, ot, m, 0); } } ll rem(ll id) { return e[id].c - e[id].f; } ll d[N], p[N], pe[N], inq[N]; ll enlarge() { for (int i = 0; i < V; ++i) { d[i] = INF; p[i] = -1; pe[i] = -1; inq[i] = 0; } d[s] = 0; queue<ll> q; q.push(s); while (!q.empty()) { ll now = q.front(); q.pop(); inq[now] = 0; for (auto i : g[now]) { if (!rem(i)) continue; if (d[e[i].y] > d[now] + e[i].cost) { p[e[i].y] = now; pe[e[i].y] = i; d[e[i].y] = d[now]+e[i].cost; if (!inq[e[i].y]) { q.push(e[i].y); inq[e[i].y] = 1; } } } } if (p[t] == -1) { return 0; } ll cur = t; while (cur != s) { ++e[pe[cur]].f; --e[pe[cur]^1].f; cur = p[cur]; } return 1; } void construct_bal() { for (ll i = 0;i < n1; ++i) { for (auto j : g[i]) { if (e[j].y >= n1 && e[j].y < n1 + n2) { bal[i][e[j].y-n1] += e[j].f; } } } } void find_ans() { ll res = 0; string w = ""; for (auto i : g[s]) { if (rem(i)) { cout << "-1\n"; return ; } } for (ll i = 0;i < m; ++i) { if (bal[u[i]][v[i]] > 0) { --bal[u[i]][v[i]]; res += r; w += "R"; } else if (bal[u[i]][v[i]] < 0) { ++bal[u[i]][v[i]]; res += b; w += "B"; } else w += "U"; } cout << res << "\n" << w << "\n"; } void solve() { cin >> n1 >> n2 >> m >> r >> b; cin >> s1 >> s2; for (ll i = 0;i < m; ++i) { cin >> u[i] >> v[i]; --u[i], --v[i]; } os = n1 + n2; ot = os + 1; s = ot + 1; t = s + 1; V = t + 1; for (ll i = 0;i < n1; ++i) { ins_l(i); } for (ll i = 0;i < n2; ++i) { ins_r(i); } for (ll i = 0;i < m; ++i) { add(u[i], v[i]+n1, 1, r); add(v[i]+n1, u[i], 1, b); } add(ot, os, INF, 0); while (enlarge()); construct_bal(); find_ans(); return ; } int main () { ios_base::sync_with_stdio(0);cin.tie(0); solve(); return 0; } /* Don't forget to check: * special case (n=1?) * array bounds. * hash collision * MOD in every step */
cpp
1312
G
G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10 0 i 1 q 2 g 0 k 1 e 5 r 4 m 5 h 3 p 3 e 5 8 9 1 10 6 OutputCopy2 4 1 3 3 InputCopy8 0 a 1 b 2 a 2 b 4 a 4 b 5 c 6 d 5 2 3 4 7 8 OutputCopy1 2 2 4 4 NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.
[ "data structures", "dfs and similar", "dp" ]
#pr\ agma optimize("Ofast") #include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/priority_queue.hpp> #define f(i,x,y) for(int i=x, i##end=y; i<=i##end; ++i) #define d(i,x,y) for(int i=y, i##end=x; i>=i##end; --i) #define uf(i,x,y) for(int i=x, i##end=y; i<i##end; ++i) #define ll long long #define pir pair<int, int> #define fir first #define sec second #define mp make_pair #define pb push_back char ch; int rd() { int f=1, x=0; ch=getchar(); while(!isdigit(ch)) { f=((ch=='-')?-1:f); ch=getchar(); } while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar(); } return x*f; } void rd(int& x) { x=rd(); } using namespace std; const int _ = 2e6 + 5; int tr[_][26], sz[_], n, k, inq[_], dis[_], q[_]; vector< pair<int, int > > edge[_]; void insert(int p, char ch, int id) { tr[p][ch - 'a'] = id; } void addedge(int u, int v, int w) { // cerr << "add : " << u << " -> " << v << " " << w << endl; edge[u].pb(mp(v, w)); } void dfs(int u) { if(inq[u]) ++sz[u], addedge(u+n+1, u, 1); f(i,'a','z') { if(tr[u][i - 'a']) { dfs(tr[u][i - 'a']); addedge(u+n+1, tr[u][i - 'a']+n+1, sz[u]); sz[u] += sz[tr[u][i - 'a']]; } } } __gnu_pbds::priority_queue< pir , greater< pir > , __gnu_pbds::pairing_heap_tag > Q; void dijkstra(int u) { memset(dis, 0x3f, sizeof(dis)); dis[u] = 0; Q.push(mp(-dis[u], u)); while(Q.size()) { int u = Q.top().sec; Q.pop(); // cerr << "at " << u << endl; for(auto [v, w] : edge[u]) { if(dis[v] > dis[u]+w) { Q.push(mp(-dis[v], v)); dis[v] = dis[u] + w; } } } } int main() { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); rd(n); f(i,1,n) { int p = rd(); char c = 0; while(!(c >= 'a' && c <= 'z')) c=getchar(); // cerr << p << ' ' << ch << endl; insert(p, c, i); addedge(p, i, 1); addedge(i, i+n+1, 0); } addedge(0, n+1, 0); rd(k); f(i,1,k) { rd(q[i]); inq[q[i]] = 1; } dfs(0); dijkstra(0); f(i,1,k) cout << dis[q[i]] << " \n"[i == k]; 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" ]
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int32_t n; cin >> n; string str; cin >> str; cout << n+1; 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" ]
#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=6e5+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; char str[110]; bool st[110]; int ans; void solve() { n=read(); scanf("%s",str+1); for(int i='z';i>='b';i--) { bool flag=false; for(int j=1;j<=n;j++) { if(str[j]==i&&!st[j]) { int l=j-1,r=j+1; while(l>=1&&st[l]) l--; while(r<=n&&st[r]) r++; if((l>=1&&str[l]==i-1)||(r<=n&&str[r]==i-1)) st[j]=true,flag=true,ans++; } } if(flag) i++; } printf("%d\n",ans); } int main() { // init(); // stin(); // scanf("%d",&T); T=1; while(T--) 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" ]
#include <iostream> using namespace std; void solve(){ int n,a=2,b=3,c=4; cin>>n; if (n<24){ cout<<"NO\n"; return ; } while(a*b*c<=n){ while(a*b*c<=n) { c=n/(a*b); if (a*b*c==n && c!=a && c!=b){ cout<<"YES\n"<<a<<' '<<b<<' '<<c<<endl; return ; } b++; c=b+1; } a++; b=a+1; c=b+1; } cout<<"NO\n"; } int main (){ int n; cin>>n; while(n--) solve(); }
cpp
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
[ "implementation", "strings" ]
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() typedef long long ll; #define range(i, n) for(int i = 0; i < (n); ++i) #define rangex(i, n, x) for(int i = x; i <= (n); ++i) #define vcin(a) for (auto &i : a) cin >> i #define yes cout << "YES\n"; #define no cout << "NO\n"; using namespace std; void solve(){ string a,b,c; cin >> a >> b >> c; range(i,a.size()){ if(a[i]==c[i] or b[i]==c[i]) continue; no; return; } yes; } /* */ int main(int argc, char **argv) { cin.tie(0); ios_base::sync_with_stdio(false); int t;cin >> t;while(t--) solve(); return 0; }
cpp
1303
G
G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4 4 2 3 2 4 1 1 3 3 7 OutputCopy36 NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636.
[ "data structures", "divide and conquer", "geometry", "trees" ]
#include <bits/stdc++.h> using namespace std; using poly = vector <int>; int n, a[150005]; poly g[150005]; bool vis[150005]; int f[150005], siz[150005], sum, rt = 0; long long ans = 0; void findrt(int u, int fa) { f[u] = 0, siz[u] = 1; for (auto v : g[u]) { if (v != fa && !vis[v]) { findrt(v, u); f[u] = max(f[u], siz[v]); siz[u] += siz[v]; } } f[u] = max(f[u], sum - siz[u]); if (!rt or f[u] < f[rt]) { rt = u; } } struct LiChaoTree { struct node { int l, r; long long k, b; } t[600005]; void build(int p, int l, int r) { t[p].l = l, t[p].r = r; t[p].k = 0, t[p].b = -4e18; if (l == r) { return ; } int mid = (l + r) >> 1; build(p << 1, l, mid); build(p << 1 | 1, mid + 1, r); } void clear(int p) { if (t[p].k == 0 && t[p].b == -4e18) { return ; } else { t[p].k = 0, t[p].b = -4e18; } if (t[p].l == t[p].r) { return ; } int mid = (t[p].l + t[p].r) >> 1; clear(p << 1), clear(p << 1 | 1); } void update(int p, long long k, long long b) { if (t[p].l == t[p].r) { if (t[p].k * t[p].l + t[p].b < k * t[p].l + b) { t[p].k = k, t[p].b = b; } return ; } int mid = (t[p].l + t[p].r) >> 1; if (k * t[p].l + b > t[p].k * t[p].l + t[p].b) { if (k * mid + b > t[p].k * mid + b) { update(p << 1 | 1, t[p].k, t[p].b); t[p].k = k, t[p].b = b; } else update(p << 1, k, b); } else if (k * t[p].r + b > t[p].k * t[p].r + t[p].b) { if (k * mid + b > t[p].k * mid + t[p].b) { update(p << 1, t[p].k, t[p].b); t[p].k = k, t[p].b = b; } else update(p << 1 | 1, k, b); } } long long qry(int p, int x) { if (t[p].l == t[p].r) { return t[p].k * x + t[p].b; } int mid = (t[p].l + t[p].r) >> 1; long long ans = t[p].k * x + t[p].b; if (x <= mid) ans = max(ans, qry(p << 1, x)); else ans = max(ans, qry(p << 1 | 1, x)); return ans; } }tree; long long pre_sum[150005], suc_sum[150005]; long long pre_rk_sum[150005], suc_rk_sum[150005]; void dfs(int u, int fa, int len) { siz[u] = 1; for (auto v : g[u]) { if (v != fa && !vis[v]) { pre_sum[v] = pre_sum[u] + a[v]; pre_rk_sum[v] = pre_rk_sum[u] + pre_sum[v]; suc_sum[v] = suc_sum[u] + a[v]; suc_rk_sum[v] = suc_rk_sum[u] + 1ll * len * a[v]; dfs(v, u, len + 1); siz[u] += siz[v]; } } } void calc_dfs(int u, int fa, int len) { ans = max(ans, pre_rk_sum[u]); ans = max(ans, suc_rk_sum[u] + suc_sum[u] + 1ll * a[rt]); ans = max(ans, tree.qry(1, len) + suc_sum[u] * (len + 1) - suc_rk_sum[u]); for (auto v : g[u]) { if (v != fa && !vis[v]) { calc_dfs(v, u, len + 1); } } } void add_dfs(int u, int fa, int len) { tree.update(1, pre_sum[u], pre_sum[u] * (len + 1) - pre_rk_sum[u]); for (auto v : g[u]) { if (v != fa && !vis[v]) { add_dfs(v, u, len + 1); } } } void solve(int u) { vis[u] = true, rt = u; pre_sum[u] = pre_rk_sum[u] = a[u]; suc_sum[u] = suc_rk_sum[u] = 0; ans = max(ans, 1ll * a[u]), dfs(u, 0, 1); tree.clear(1); for (auto v : g[u]) { if (!vis[v]) { calc_dfs(v, u, 1); add_dfs(v, u, 2); } } reverse(g[u].begin(), g[u].end()); tree.clear(1); for (auto v : g[u]) { if (!vis[v]) { calc_dfs(v, u, 1); add_dfs(v, u, 2); } } for (auto v : g[u]) { if (!vis[v]) { rt = 0, sum = siz[v]; findrt(v, u), solve(rt); } } } int main() { ios :: sync_with_stdio(0), cin.tie(0); cin >> n; for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; g[u].push_back(v), g[v].push_back(u); } for (int i = 1; i <= n; ++i) { cin >> a[i]; } sum = n, findrt(1, 0), tree.build(1, 1, n); solve(rt); cout << ans << '\n'; return 0; }
cpp
1322
D
D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4 4 3 1 2 1 1 2 1 2 1 1 2 3 4 5 6 7 8 9 OutputCopy6 InputCopy2 2 1 2 0 0 2 1 -100 -100 OutputCopy2 InputCopy5 4 4 3 2 1 1 0 2 6 7 4 12 12 12 6 -3 -5 3 10 -4 OutputCopy62 NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.
[ "bitmasks", "dp" ]
// LUOGU_RID: 93923800 #include<stdio.h> #include<bits/stdc++.h> #define fir first #define sec second #define all(x) begin(x),end(x) using namespace std; typedef long long ll; typedef unsigned uint; typedef unsigned long long ull; typedef double db; typedef long double ldb; typedef __int128 int128; typedef __uint128_t uint128; typedef pair<int,int> pii; template<typename type> inline void chmin(type &x,const type &y) { if(y<x) x=y; } template<typename type> inline void chmax(type &x,const type &y) { if(x<y) x=y; } constexpr int Max=2100; constexpr ll inf=1e18; int a[Max],b[Max],c[Max*2],n,m; vector<int>d[Max]; ll f[Max*2][Max]; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr),cout.tie(nullptr); cin>>n>>m,m+=n; for(int i=1;i<=n;++i) cin>>b[i]; for(int i=1;i<=n;++i) cin>>a[i]; for(int i=1;i<=m;++i) cin>>c[i]; memset(f,0xcf,sizeof(f)); for(int i=0;i<=m;++i) f[i][0]=0; for(int i=n,x;i;--i) { x=b[i]; for(int j=n;j;--j) chmax(f[x][j],f[x][j-1]-a[i]+c[x]); for(int j=x+1;j<=m;++j) for(int k=0;k<=((j-x)<=30?n>>(j-x):0);++k) chmax(f[j][k],max(f[j-1][k*2],f[j-1][k*2+1])+k*c[j]); } cout<<f[m][0]<<"\n"; return 0; }
cpp
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define el "\n" #define matrix vector<vector<int>> #define pt complex<ld> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; const ll N = 2e5 + 7, LOG = 20; const ld pi = acos(-1); const ll mod = 1e9 + 7; int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; ll n, m, k, x, y; int a[N]; void dowork() { cin >> n; set<int> st; for (int i = 1; i < n; i++) { cin >> a[i]; st.insert(i); } st.insert(n); int sum = 0; for (int i = 1; i < n; i++) { sum += a[i]; while (st.size() && sum + *st.rbegin() > n) { st.erase(prev(st.end())); } while (st.size() && sum + *st.begin() < 1) { st.erase(st.begin()); } } if (st.size() == 0) { cout << -1 << el; return; } vector<int> ans; ans.push_back(*st.begin()); st.clear(); st.insert(ans.back()); for (int i = 1; i < n; i++) { st.insert(ans.back() + a[i]); ans.push_back(ans.back() + a[i]); } // cout<<st.size()<<" "<<*st.rbegin()<<" " if (st.size() != n || *st.rbegin() > n || *st.begin() < 1) { cout << -1 << el; return; } for (auto j: ans) { cout << j << " "; } cout << el; } int main() { fast //freopen("cowland.in", "r", stdin); //freopen("cowland.out", "w", stdout); int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { dowork(); } }
cpp
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
#include<bits/stdc++.h> using namespace std; int n; int fa[2005],rk[2005],rt; vector<int> vec[2005],tmp[2005]; void dfs(int x){ if(!rk[x])tmp[x].push_back(x); for(auto u:vec[x]){ dfs(u); for(auto it:tmp[u]){ tmp[x].push_back(it); if(tmp[x].size()==rk[x])tmp[x].push_back(x); } } if(tmp[x].size()<rk[x]){ puts("NO"); exit(0); } } int ans[2005]; int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d%d",&fa[i],&rk[i]); if(!fa[i])rt=i; else vec[fa[i]].push_back(i); } dfs(rt); for(int i=0;i<n;i++)ans[tmp[rt][i]]=i+1; puts("YES"); for(int i=1;i<=n;i++)printf("%d ",ans[i]); return 0; }
cpp
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; int main(){ int t,n,d,num; cin >> t; while(t--){ cin >> n >> d; int ans=0; for(int i=0;i<n;i++){ cin >> num; if(i==0){ ans=num; }else if(d>=i*num){ ans+=num; d-=i*num; }else{ ans+=d/i; d=0; } } cout << ans << endl; } }
cpp
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
#include "bits/stdc++.h" using namespace std; signed main() { int n, m; scanf("%d%d", &n, &m); vector<string> a(n); for (auto &i: a) cin >> i; int cnt = 0; map<string, int> mp; for (auto i: a) mp[i]++; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { string tmp; for (int k = 0; k < m; k++) { if (a[i][k] == a[j][k]) tmp += a[i][k]; else { for (auto e: {'S', 'T', 'E'}) if (a[i][k] != e and a[j][k] != e) tmp += e; } } cnt += mp[tmp]; } } cout << cnt / 3 << '\n'; }
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" ]
#line 1 "library/my_template.hpp" #if defined(LOCAL) #include <my_template_compiled.hpp> #else #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; using ll = long long; using pi = pair<ll, ll>; using vi = vector<ll>; using u32 = unsigned int; using u64 = unsigned long long; using i128 = __int128; 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 vec(type, name, ...) vector<type> name(__VA_ARGS__) #define vv(type, name, h, ...) \ vector<vector<type>> name(h, vector<type>(__VA_ARGS__)) #define vvv(type, name, h, w, ...) \ vector<vector<vector<type>>> name( \ h, vector<vector<type>>(w, vector<type>(__VA_ARGS__))) #define vvvv(type, name, a, b, c, ...) \ vector<vector<vector<vector<type>>>> name( \ a, vector<vector<vector<type>>>( \ b, vector<vector<type>>(c, vector<type>(__VA_ARGS__)))) // https://trap.jp/post/1224/ #define FOR1(a) for (ll _ = 0; _ < ll(a); ++_) #define FOR2(i, a) for (ll i = 0; i < ll(a); ++i) #define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i) #define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c)) #define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i) #define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i) #define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i) #define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c)) #define overload4(a, b, c, d, e, ...) e #define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__) #define FOR_R(...) \ overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__) #define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s)) #define all(x) x.begin(), x.end() #define len(x) ll(x.size()) #define elif else if #define eb emplace_back #define mp make_pair #define mt make_tuple #define fi first #define se second #define stoi stoll template <typename T, typename U> T SUM(const vector<U> &A) { T sum = 0; for (auto &&a: A) sum += a; return sum; } #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()), x.shrink_to_fit() int popcnt(int x) { return __builtin_popcount(x); } int popcnt(u32 x) { return __builtin_popcount(x); } int popcnt(ll x) { return __builtin_popcountll(x); } int popcnt(u64 x) { return __builtin_popcountll(x); } // (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2) int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); } int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); } int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); } int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); } // (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2) int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); } int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); } int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); } int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); } template <typename T> T pick(deque<T> &que) { T a = que.front(); que.pop_front(); return a; } template <typename T> T pick(pq<T> &que) { T a = que.top(); que.pop(); return a; } template <typename T> T pick(pqg<T> &que) { assert(que.size()); T a = que.top(); que.pop(); return a; } template <typename T> T pick(vc<T> &que) { assert(que.size()); T a = que.back(); que.pop_back(); return a; } template <typename T, typename U> T ceil(T x, U y) { return (x > 0 ? (x + y - 1) / y : x / y); } template <typename T, typename U> T floor(T x, U y) { return (x > 0 ? x / y : (x - y + 1) / y); } template <typename T, typename U> pair<T, T> divmod(T x, U y) { T q = floor(x, y); return {q, x - q * y}; } template <typename F> ll binary_search(F check, ll ok, ll ng) { assert(check(ok)); while (abs(ok - ng) > 1) { auto x = (ng + ok) / 2; tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x)); } return ok; } template <typename F> double binary_search_real(F check, double ok, double ng, int iter = 100) { FOR(iter) { double x = (ok + ng) / 2; tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x)); } return (ok + ng) / 2; } template <class T, class S> inline bool chmax(T &a, const S &b) { return (a < b ? a = b, 1 : 0); } template <class T, class S> inline bool chmin(T &a, const S &b) { return (a > b ? a = b, 1 : 0); } vc<int> s_to_vi(const string &S, char first_char) { vc<int> A(S.size()); FOR(i, S.size()) { A[i] = S[i] - first_char; } return A; } template <typename T, typename U> vector<T> cumsum(vector<U> &A, int off = 1) { int N = A.size(); vector<T> B(N + 1); FOR(i, N) { B[i + 1] = B[i] + A[i]; } if (off == 0) B.erase(B.begin()); return B; } template <typename CNT, typename T> vc<CNT> bincount(const vc<T> &A, int size) { vc<CNT> C(size); for (auto &&x: A) { ++C[x]; } return C; } // stable template <typename T> vector<int> argsort(const vector<T> &A) { vector<int> ids(A.size()); iota(all(ids), 0); sort(all(ids), [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); }); return ids; } // A[I[0]], A[I[1]], ... template <typename T> vc<T> rearrange(const vc<T> &A, const vc<int> &I) { int n = len(I); vc<T> B(n); FOR(i, n) B[i] = A[I[i]]; return B; } #endif #line 1 "library/other/io.hpp" // based on yosupo's fastio #include <unistd.h> namespace fastio { // クラスが read(), print() を持っているかを判定するメタ関数 struct has_write_impl { template <class T> static auto check(T &&x) -> decltype(x.write(), std::true_type{}); template <class T> static auto check(...) -> std::false_type; }; template <class T> class has_write : public decltype(has_write_impl::check<T>(std::declval<T>())) { }; struct has_read_impl { template <class T> static auto check(T &&x) -> decltype(x.read(), std::true_type{}); template <class T> static auto check(...) -> std::false_type; }; template <class T> class has_read : public decltype(has_read_impl::check<T>(std::declval<T>())) {}; struct Scanner { FILE *fp; char line[(1 << 15) + 1]; size_t st = 0, ed = 0; void reread() { memmove(line, line + st, ed - st); ed -= st; st = 0; ed += fread(line + ed, 1, (1 << 15) - ed, fp); line[ed] = '\0'; } bool succ() { while (true) { if (st == ed) { reread(); if (st == ed) return false; } while (st != ed && isspace(line[st])) st++; if (st != ed) break; } if (ed - st <= 50) { bool sep = false; for (size_t i = st; i < ed; i++) { if (isspace(line[i])) { sep = true; break; } } if (!sep) reread(); } return true; } template <class T, enable_if_t<is_same<T, string>::value, int> = 0> bool read_single(T &ref) { if (!succ()) return false; while (true) { size_t sz = 0; while (st + sz < ed && !isspace(line[st + sz])) sz++; ref.append(line + st, sz); st += sz; if (!sz || st != ed) break; reread(); } return true; } template <class T, enable_if_t<is_integral<T>::value, int> = 0> bool read_single(T &ref) { if (!succ()) return false; bool neg = false; if (line[st] == '-') { neg = true; st++; } ref = T(0); while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); } if (neg) ref = -ref; return true; } template <typename T, typename enable_if<has_read<T>::value>::type * = nullptr> inline bool read_single(T &x) { x.read(); return true; } bool read_single(double &ref) { string s; if (!read_single(s)) return false; ref = std::stod(s); return true; } bool read_single(char &ref) { string s; if (!read_single(s) || s.size() != 1) return false; ref = s[0]; return true; } template <class T> bool read_single(vector<T> &ref) { for (auto &d: ref) { if (!read_single(d)) return false; } return true; } template <class T, class U> bool read_single(pair<T, U> &p) { return (read_single(p.first) && read_single(p.second)); } template <size_t N = 0, typename T> void read_single_tuple(T &t) { if constexpr (N < std::tuple_size<T>::value) { auto &x = std::get<N>(t); read_single(x); read_single_tuple<N + 1>(t); } } template <class... T> bool read_single(tuple<T...> &tpl) { read_single_tuple(tpl); return true; } void read() {} template <class H, class... T> void read(H &h, T &... t) { bool f = read_single(h); assert(f); read(t...); } Scanner(FILE *fp) : fp(fp) {} }; struct Printer { Printer(FILE *_fp) : fp(_fp) {} ~Printer() { flush(); } static constexpr size_t SIZE = 1 << 15; FILE *fp; char line[SIZE], small[50]; size_t pos = 0; void flush() { fwrite(line, 1, pos, fp); pos = 0; } void write(const char val) { if (pos == SIZE) flush(); line[pos++] = val; } template <class T, enable_if_t<is_integral<T>::value, int> = 0> void write(T val) { if (pos > (1 << 15) - 50) flush(); if (val == 0) { write('0'); return; } if (val < 0) { write('-'); val = -val; // todo min } size_t len = 0; while (val) { small[len++] = char(0x30 | (val % 10)); val /= 10; } for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; } pos += len; } void write(const string s) { for (char c: s) write(c); } void write(const char *s) { size_t len = strlen(s); for (size_t i = 0; i < len; i++) write(s[i]); } void write(const double x) { ostringstream oss; oss << fixed << setprecision(15) << x; string s = oss.str(); write(s); } void write(const long double x) { ostringstream oss; oss << fixed << setprecision(15) << x; string s = oss.str(); write(s); } template <typename T, typename enable_if<has_write<T>::value>::type * = nullptr> inline void write(T x) { x.write(); } template <class T> void write(const vector<T> val) { auto n = val.size(); for (size_t i = 0; i < n; i++) { if (i) write(' '); write(val[i]); } } template <class T, class U> void write(const pair<T, U> val) { write(val.first); write(' '); write(val.second); } template <size_t N = 0, typename T> void write_tuple(const T t) { if constexpr (N < std::tuple_size<T>::value) { if constexpr (N > 0) { write(' '); } const auto x = std::get<N>(t); write(x); write_tuple<N + 1>(t); } } template <class... T> bool write(tuple<T...> tpl) { write_tuple(tpl); return true; } template <class T, size_t S> void write(const array<T, S> val) { auto n = val.size(); for (size_t i = 0; i < n; i++) { if (i) write(' '); write(val[i]); } } void write(i128 val) { string s; bool negative = 0; if (val < 0) { negative = 1; val = -val; } while (val) { s += '0' + int(val % 10); val /= 10; } if (negative) s += "-"; reverse(all(s)); if (len(s) == 0) s = "0"; write(s); } }; Scanner scanner = Scanner(stdin); Printer printer = Printer(stdout); void flush() { printer.flush(); } void print() { printer.write('\n'); } template <class Head, class... Tail> void print(Head &&head, Tail &&... tail) { printer.write(head); if (sizeof...(Tail)) printer.write(' '); print(forward<Tail>(tail)...); } void read() {} template <class Head, class... Tail> void read(Head &head, Tail &... tail) { scanner.read(head); read(tail...); } } // namespace fastio using fastio::print; using fastio::flush; using fastio::read; #define INT(...) \ int __VA_ARGS__; \ read(__VA_ARGS__) #define LL(...) \ ll __VA_ARGS__; \ read(__VA_ARGS__) #define STR(...) \ string __VA_ARGS__; \ read(__VA_ARGS__) #define CHAR(...) \ char __VA_ARGS__; \ read(__VA_ARGS__) #define DBL(...) \ double __VA_ARGS__; \ read(__VA_ARGS__) #define VEC(type, name, size) \ vector<type> name(size); \ read(name) #define VV(type, name, h, w) \ vector<vector<type>> name(h, vector<type>(w)); \ read(name) void YES(bool t = 1) { print(t ? "YES" : "NO"); } void NO(bool t = 1) { YES(!t); } void Yes(bool t = 1) { print(t ? "Yes" : "No"); } void No(bool t = 1) { Yes(!t); } void yes(bool t = 1) { print(t ? "yes" : "no"); } void no(bool t = 1) { yes(!t); } #line 2 "library/ds/unionfind/unionfind.hpp" struct UnionFind { int n, n_comp; vc<int> dat; // par or (-size) UnionFind(int n = 0) { build(n); } void build(int m) { n = m, n_comp = m; dat.assign(n, -1); } int operator[](int x) { while (dat[x] >= 0) { int pp = dat[dat[x]]; if (pp < 0) { return dat[x]; } x = dat[x] = pp; } return x; } int size(int x) { assert(dat[x] < 0); return -dat[x]; } bool merge(int x, int y) { x = (*this)[x], y = (*this)[y]; if (x == y) return false; if (-dat[x] < -dat[y]) swap(x, y); dat[x] += dat[y], dat[y] = x, n_comp--; return true; } }; #line 4 "main.cpp" void solve() { LL(N, M, Q); int H = N, W = M; const int LIM = max(1000, ceil(2'000'000, N * M)) + 5; // 色 0 :単調減少 // 色 k :単調増加 → 単調減少 // すべて、増加 → 減少 と見なせる // (t,x,y) using T3 = tuple<int, int, int>; vvc<T3> ADD(LIM), RM(LIM); vv(int, A, N, M); FOR(t, Q) { LL(a, b, c); --a, --b; if (A[a][b] == c) continue; RM[A[a][b]].eb(t, a, b); A[a][b] = c; ADD[A[a][b]].eb(t, a, b); } auto idx = [&](int x, int y) -> int { return M * x + y; }; auto isin = [&](ll x, ll y) -> bool { return (0 <= x && x < H && 0 <= y && y < W); }; ll dx[] = {1, 0, -1, 0}; ll dy[] = {0, 1, 0, -1}; UnionFind uf(N); vc<int> C(N * M); int comp = 0; auto reset = [&]() -> void { uf.build(N * M); fill(all(C), 0); comp = 0; }; auto add = [&](int x, int y) -> void { int i = idx(x, y); assert(C[i] == 0); C[i] = 1; ++comp; FOR(d, 4) { int nx = x + dx[d], ny = y + dy[d]; if (isin(nx, ny) && C[idx(nx, ny)] && uf.merge(i, idx(nx, ny))) --comp; } }; vc<int> ANS(Q + 1); FOR(color, LIM) { if (ADD[color].empty() && RM[color].empty()) continue; // クエリ [0,p) の答を計算済 int p = 0; reset(); for (auto&& [t, a, b]: ADD[color]) { ANS[p] += comp, ANS[t] -= comp; add(a, b); p = t; } // クエリ [q, Q) の答を計算済 int q = Q; reset(); FOR(x, N) FOR(y, M) if (A[x][y] == color) add(x, y); reverse(all(RM[color])); for (auto&& [t, a, b]: RM[color]) { ANS[t] += comp, ANS[q] -= comp; q = t; add(a, b); } ANS[p] += comp, ANS[q] -= comp; } ANS = cumsum<int>(ANS, 0); FOR(q, Q) print(ANS[q]); } signed main() { 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 ar array #define vc vector #define ll long long #define db long double #define mk make_pair #define pb push_back #define umap unordered_map #define sz(A) ((int)(A.size())) #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(), x.rend() #define line(k) rep(i, 1, k){cerr<<nl;} #define rep(i,k,n) for(int i=k;i<=n;i++) #define per(i,n,k) for(int i=n;i>=k;i--) #define print(x) {cout << x << endl; return;} #define rprint(x) {cout << x << endl; return 0;} string yes="YES\n",no="NO\n", sp=" ", nl = "\n"; #define trav(A, P) for(auto P=A.begin(); P!=A.end(); P++) void __print(int x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(bool x) {cerr << (x ? "true" : "false");} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T, typename V> void __print(const array<T, 2> &x) {cerr << '{'; __print(x[0]); cerr << ','; __print(x[1]); cerr << '}';} template<typename T, typename V> void __print(const array<T, 3> &x) {cerr << '{'; __print(x[0]); cerr << ','; __print(x[1]); cerr << ','; __print(x[2]); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define _(x...) cerr << "~[" << #x << "] = ["; _print(x) #else #define _(x...) #endif // ar<int,2> template<typename T> istream &operator>>(istream &istream, array<T,2> &p) { return (istream >> p[0] >> p[1]); } template<typename T> ostream &operator<<(ostream &ostream, const array<T,2> &p) { return (ostream << p[0] << " " << p[1]); } // ar<int,3> template<typename T> istream &operator>>(istream &istream, array<T,3> &p) { return (istream >> p[0] >> p[1] >> p[2]); } template<typename T> ostream &operator<<(ostream &ostream, const array<T,3> &p) { return (ostream << p[0] << " " << p[1] << " " << p[2]); } // pair template<typename T1, typename T2> istream &operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); } template<typename T1, typename T2> ostream &operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.first << " " << p.second); } // vector template<typename T> istream &operator>>(istream &istream, vector<T> &v) { for (auto &it : v) { cin >> it; } return istream; } template<typename T> ostream &operator<<(ostream &ostream, const vector<T> &c) { for (auto &it : c) { cout << it << " "; } return ostream; } template<typename T,typename T1>T rmax(T &a,T1 b){if(b>a)a=b;return a;} template<typename T,typename T1>T rmin(T &a,T1 b){if(b<a)a=b;return a;} #define pys(x) cout << ((x)?"YES":"NO") << endl; //fill(a,a+n, num) const ll pinf = 1e12+5, minf = -(2e18+5); const int mod = 1e9+7, MOD = 1e9+7, dom = 998244353, inf = 2e9+5; void E_731(int tc){ ll n, k; cin >> n >> k; vc<ll> a(k), t(k), ans(n+1, pinf); rep(i, 0, k-1)cin >> a[i]; map<ll, ll> f; rep(i, 1, n)f[i] = pinf; rep(i, 0, k-1)cin >> t[i], ans[a[i]] = t[i], f[a[i]] = t[i]; ll temp = pinf; rep(i, 1, n){ temp = min(temp, f[i]); ans[i] = min({ans[i], temp, f[i]}); temp++; } temp = pinf; per(i, n, 1){ temp = min({temp, f[i], ans[i]}); f[i] = min({ans[i], f[i], temp}); ans[i] = min({ans[i], f[i], temp}); temp++; } rep(i, 1, n)cout << ans[i] << " \n"[i==n]; } void D_1553(int tc){ string a, b; cin >> a >> b; int n = a.size(), m = b.size(); int l = n-1, r = m-1; string na = "", nb = "", rb = b; reverse(all(rb)); while(l>=0 && r>=0){ if(a[l]==b[r]){ na += a[l]; nb += b[r]; --l, --r; } else l -= 2; } if(rb==nb && na==nb)print("YES") else print("NO") } void C_1234(int tc){ int n; vc<string> s(2); cin >> n >> s[0] >> s[1]; for(int i=0, j=0; i<n; i++){ if(s[j][i]=='1' || s[j][i]=='2'){ // the flow will be just passed to the next row } if(s[j][i]>='3'){ // the flow is sure to get in the opposite row // not possible if the pipes are of type 1, 2 if(s[1-j][i]=='1' || s[1-j][i]=='2')print("NO") else j = 1-j; // change of row } if(i==n-1 && j==1)print("YES"); } cout << "NO" << nl; } void C_1307(){ string s; cin >> s; int n = s.size(); map<string, ll> f; rep(i, 0, n-1){ string t(1, s[i]); for(char c='a'; c<='z'; c++){ string p(1, c); if(f[p]>0ll){ string q = p + t; f[q] += (ll)f[p]; } } f[t]++; } ll ans = 0; for(pair<string, ll> e: f){ ans = max(ans, e.second); } cout << ans << nl; } int32_t main(){ ios::sync_with_stdio(false);cin.tie(0); int t = 1; // cin >> t; for(int i=1; i<=t; i++){ C_1307(); } 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> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; template <typename T> using pbds = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define int int64_t #define endl '\n' #define inf 2e18 #define vi vector<int> #define pii pair<int, int> #define sz(v) ((int) v.size()) #define all(v) v.begin(), v.end() int max(int x, int y) { return x > y ? x : y; } int min(int x, int y) { return x < y ? x : y; } int __gcd(int x, int y) { return y == 0 ? x : __gcd(y, x % y); } void solve() { int n; cin >> n; vector<vi> a(n, vi(4)); pbds<int> s; for(int i = 0; i < n; i++) { cin >> a[i][0] >> a[i][1] >> a[i][2] >> a[i][3]; s.insert(a[i][0]); s.insert(a[i][1]); s.insert(a[i][2]); s.insert(a[i][3]); } for(int i = 0; i < n; i++) { a[i][0] = s.order_of_key(a[i][0]); a[i][1] = s.order_of_key(a[i][1]); a[i][2] = s.order_of_key(a[i][2]); a[i][3] = s.order_of_key(a[i][3]); } sort(all(a), [&](auto& x, auto& y) { if(x[0] == y[0]) return x[1] < y[1]; return x[0] < y[0]; }); priority_queue<vi, vector<vi>, greater<vi>> q; multiset<int> mn, mx; for(int t = 0, i = 0; t <= 4 * n; t++) { while(i < n) { if(a[i][0] == t) { q.push({a[i][1], a[i][2], a[i][3]}); mx.insert(a[i][2]); mn.insert(a[i][3]); i++; } else break; } while(!q.empty()) { vi p = q.top(); if(p[0] < t) { q.pop(); mx.erase(mx.find(p[1])); mn.erase(mn.find(p[2])); } else break; } if(sz(mn) == 0) continue; if(*mn.begin() < *mx.rbegin()) return void(cout << "NO"); } for(int i = 0; i < n; i++) { swap(a[i][0], a[i][2]); swap(a[i][1], a[i][3]); } sort(all(a), [&](auto& x, auto& y) { if(x[0] == y[0]) return x[1] < y[1]; return x[0] < y[0]; }); assert(q.empty()); assert(mn.empty()); assert(mx.empty()); for(int t = 0, i = 0; t <= 4 * n; t++) { while(i < n) { if(a[i][0] == t) { q.push({a[i][1], a[i][2], a[i][3]}); mx.insert(a[i][2]); mn.insert(a[i][3]); i++; } else break; } while(!q.empty()) { vi p = q.top(); if(p[0] < t) { q.pop(); mx.erase(mx.find(p[1])); mn.erase(mn.find(p[2])); } else break; } if(sz(mn) == 0) continue; if(*mn.begin() < *mx.rbegin()) return void(cout << "NO"); } cout << "YES"; } int32_t main() { int t = 1; ios_base::sync_with_stdio(false); cin.tie(NULL); // cin >> t; while(t--) { solve(); cout << endl; cerr << endl; } return 0; }
cpp
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
#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 n, m; cin >> n >> m; if (n <= 2) { if (m) cout << "-1\n"; else for (int i = 1; i <= n; i++) cout << i << " \n"[i==n]; return 0; } vi r; int i = 1, k = 1; ll c = 0; for (; i <= 2; i++) r.push_back(i); for (; i <= n; i++) { if (c+k>m) break; r.push_back(i); c += k; if (i%2==0) k++; } if (i>n && c<m) { cout << "-1\n"; return 0; } if (c<m) { ll d = m-c; if (d*2 > r.size()) { cout << "-1\n"; return 0; } r.push_back(r[i-2]+r[i-d*2-1]); i++; } ll sum = r[i-2]+1; ll next = r[i-2] + sum; for (; i<=n; i++) { if (next > 1000000000) { cout << "-1\n"; return 0; } r.push_back(next); next += sum; } for (int i = 0; i < n; i++) cout << r[i] << " \n"[i == n-1]; }
cpp
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define AWM() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int main() { AWM(); int t; cin>>t; while(t--) { ll int x,y,a,b,sum; cin>>x>>y>>a>>b; sum=abs(x-y); if(sum%(a+b)==0) cout<<sum/(a+b)<<endl; else cout<<"-1"<<endl; } return 0; }
cpp
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
#include <bits/stdc++.h> #define _CRT_SECURE_NO_WARNINGS #define ll long long #define all(x) (x).begin(), (x).end() #define test_case int t;cin>>t;while(t--) #define endl '\n' ll gcd(ll a, ll b) { return (b == 0 ? a : gcd(b, a % b)); } ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } using namespace std; void Sync() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int binary_search(int arr[], int size, int value) { int low = 0; int high = size - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == value) return mid; else if (arr[mid] < value) low = mid + 1; else high = mid - 1; } return -1; } bool isPrime(int n) { bool ok = 1; if (n < 2) return false; else { for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) { ok = 0; break; } } if (ok) return true; else return false; } } bool ispalindrome(vector<int>vec, int sz){ bool ok = 1; for(int i = 0; i < sz; i++){ if(vec[i] != vec[sz - i -1]){ ok = 0; break; } } if(ok) return true; else return false; } void solve() { bool ok = 0; int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) cin >> *(arr + i); for (int i = 0; i < n; i++) { for (int j = i + 2; j < n; j++) { if (arr[i] == arr[j]) { ok = 1; break; } } } string res = (ok) ? "YES" : "NO"; cout<<res<<'\n'; } void run(){ freopen("Input.txt", "r", stdin); freopen("Output.txt", "w", stdout); freopen("Error.txt", "w", stderr); } int main() { Sync(); //run(); test_case solve(); return 0; }
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" ]
#include<bits/stdc++.h> #define task "C" #define ll long long #define ld long double #define fi first #define se second #define pb push_back using namespace std; const int MAXN = 80 + 5; const ll INF = 1e18 + 5; int n, k; int a[MAXN][MAXN]; void Input() { cin >> n >> k; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cin >> a[i][j]; } } vector<pair<int, int>> in[MAXN][MAXN]; int chon[MAXN], cnt[MAXN]; ll res = INF; void DFS(int id) { if (id == k / 2 + 1) { ll ans = 0; for (int i = 1; i <= k / 2; i++) { bool chk = 0; for (const auto& p : in[chon[i]][chon[i + 1]]) { if (cnt[p.se]) continue; chk = 1; ans += p.fi; break; } if (!chk) { ans = INF; break; } } res = min(res, ans); return; } for (int i = 1; i <= n; i++) { cnt[i]++; chon[id] = i; DFS(id + 1); cnt[i]--; } } void Solve() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { for (int t = 1; t <= n; t++) { if (t == i || t == j) continue; in[i][j].pb({a[i][t] + a[t][j], t}); } sort(in[i][j].begin(), in[i][j].end()); } } chon[1] = 1; chon[k / 2 + 1] = 1; DFS(2); cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); if (fopen(task".INP","r")) { freopen(task".INP","r",stdin); //freopen(task".OUT","w",stdout); } Input(); Solve(); }
cpp
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
#include<bits/stdc++.h> #define int long long #define fa(i,a,n) for(int i=a;i<n;i++) #define pb push_back #define bp pop_back #define mp make_pair #define all(v) v.begin(),v.end() #define vi vector<int> #define faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; void solve(){ int n,s,k; cin >> n >> s >> k; int a[k],f=0; vector<int> v1,v2; for(int i=0;i<k;i++) { cin >> a[i]; if(a[i]<s) v1.push_back(a[i]); else if(a[i]>s) v2.push_back(a[i]); else{ f++; v1.push_back(a[i]); } } if(f==0) { cout << "0" << endl; return; } sort(v1.rbegin(),v1.rend()); sort(v2.begin(),v2.end()); int cnt1=0,cnt2=0,x=s-1,y=s+1,f1=0,f2=0; for(int i=1;i<v1.size();i++) { if(x!=v1[i]) { f1++; cnt1++; break; } cnt1++; x--; } if(!f1 && v1.size()!=s) cnt1++; for(int i=0;i<v2.size();i++) { if(y!=v2[i]) { f2++; cnt2++; break; } cnt2++; y++; } if(!f2 && v2.size()!=(n-s)) cnt2++; if(v1.size()==s) { cout << cnt2 << endl; return; } if(v2.size()==(n-s)) { cout << cnt1 << endl; return; } cout << min(cnt1,cnt2) << endl; return; } signed main() { faster; int t=1; cin>>t; while(t--) solve(); }
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" ]
// Siddharth Ruria //Linkedin: https://www.linkedin.com/in/ruria-siddharth/ //Codeforces: https://codeforces.com/profile/Sw00sh //Codechef: https://www.codechef.com/users/airurdis #include <iostream> #include <bits/stdc++.h> // #include <sys/resource.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 ruria 1 //Speed #define fast ios_base::sync_with_stdio(false); #define input cin.tie(NULL); #define output cout.tie(NULL); //Aliases using ll= long long; using lld= long double; using ull= unsigned long long; //Constants const lld pi= 3.141592653589793238; const ll INF= LONG_LONG_MAX; const ll mod=1e9+7; //TypeDef typedef vector<int> vi; typedef vector<pair<int, int>> vpi; typedef pair<ll, ll> pll; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<string> vs; typedef unordered_map<ll,ll> umll; typedef map<ll,ll> mll; // Macros #define F first #define S second #define pb push_back #define mp make_pair #define fl(i, n) for(int i= 0; i< n; ++i) #define rtl(i, m, n) for(int i= n;i>= m; --i) #define yes cout<<"YES\n" #define no cout<<"NO\n" #define minus cout << "-1\n" #define all(v) v.begin(),v.end() //Debug #ifdef ruria #define debug(x) cerr << #x << " "; cerr << x << " "; cerr << endl; #else #define debug(x); #endif // Operator overloads template<typename T1, typename T2> // cin >> pair<T1, T2> istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.first >> p.second); } template<typename T> // cin >> vector<T> istream& operator>>(istream &istream, vector<T> &v){ for (auto &it: v)cin >> it; return istream; } template<typename T1, typename T2> // cout << pair<T1, T2> ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.F << " " << p.S); } template<typename T> // cout << vector<T> ostream& operator<<(ostream &ostream, const vector<T> &c) { for (auto &it: c) cout << it << " "; return ostream; } // Utility functions template <typename T> void print(T &&t) { cout << t << "\n"; } void printarr(int arr[], int n){ fl(i, n) cout << arr[i] << " "; cout << "\n"; } template<typename T> void printvec(vector<T>v){ ll n= v.size(); fl(i, n) cout << v[i] << " "; cout << "\n"; } template<typename T> ll sumvec(vector<T>v){ ll n= v.size(); ll s= 0; fl(i, n) s+= v[i]; return s; } // Mathematical functions ll gcd(ll a, ll b){ if (b == 0) return a; return gcd(b, a % b); } //__gcd ll lcm(ll a, ll b){ return (a/gcd(a,b)*b); } ll moduloMultiplication(ll a,ll b,ll mod){ ll res = 0; a %= mod; while (b){ if(b & 1) res = (res + a) % mod; b >>= 1; } return res; } ll powermod(ll x, ll y, ll p){ ll res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if(y & 1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; } //Graph-dfs // bool gone[MN]; // vector<int> adj[MN]; // void dfs(int loc){ // gone[loc]=true; // for(auto x:adj[loc])if(!gone[x])dfs(x); // } //Sorting bool sorta(const pair<int,int> &a,const pair<int,int> &b){return (a.second < b.second);} bool sortd(const pair<int,int> &a,const pair<int,int> &b){return (a.second > b.second);} //Bits string decToBinary(int n){string s="";int i = 0;while (n > 0) {s =to_string(n % 2)+s;n = n / 2;i++;}return s;} ll binaryToDecimal(string n){string num = n;ll dec_value = 0;int base = 1;int len = num.length();for(int i = len - 1; i >= 0; i--){if (num[i] == '1')dec_value += base;base = base * 2;}return dec_value;} //Check bool isPrime(ll n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} bool isPowerOfTwo(ll n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));} bool isPerfectSquare(ll x){if (x >= 0) {ll sr = sqrt(x);return (sr * sr == x);}return false;} //Code void solve() { int n; cin >> n; string s; cin >> s; if(n< 2) { cout << -1 << "\n"; return; } bool check= false; int ct= 0; int fi= 0; int se= 0; for(int i= 0; i< n; ++i) { int val= (int)s[i]-'0'; if(val&1 and fi== 0) { ct++; fi= val; } else if(val&1 and se== 0) { ct++; se= val; } if(ct== 2) { check= true; break; } } if(!check) cout << -1 << "\n"; else cout << fi << se << "\n"; } //Main int main() { fast input output int tt= 1; cin >> tt; while(tt--) { solve(); } //Uncomment for Kickstart // fl(i,t) { // cout<<"Case #"<<i+1<<": "; // solve(); // cout<<"\n"; // } } // End
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
// LUOGU_RID: 101076511 #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 2e5 + 5; const int M = 1e6 + 5; int n, prime[M], tot; ll a[N]; mt19937 rnd(19260817); bool vis[M]; inline void Euler() { for (int i = 2; i <= M - 5; i++) { if (!vis[i]) prime[++tot] = i; for (int j = 1; j <= tot && 1ll * i * prime[j] <= M - 5; j++) { vis[i * prime[j]] = true; if (!(i % prime[j])) break; } } } set<ll> s; inline void solve(ll x) { for (int i = 1; i <= tot && x > 1; i++) if (!(x % prime[i])) { s.insert(prime[i]); while (!(x % prime[i])) x /= prime[i]; } if (x > 1) s.insert(x); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); Euler(); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= 50; i++) { int x = rnd() % n + 1; if (a[x] > 2) solve(a[x] - 1); solve(a[x]), solve(a[x] + 1); } ll ans = n; for (ll x : s) { ll cur = 0; for (int i = 1; i <= n; i++) cur += a[i] < x ? x - a[i] : min(a[i] % x, x - a[i] % x); ans = min(ans, cur); } cout << ans; return 0; }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
#include <bits/stdc++.h> #include <algorithm> #include <iostream> #include <numeric> #include <cmath> #include <conio.h> #include <iomanip> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ll long long #define ld long double #define el '\n' #define pi 3.14159265358979323846 #define NumOfDigit(w) (int)(log10(w) + 1) #define fr(p_) for(auto &p__ : p_) cout<<p__<<" "; #define debug(x) cout<<"[" << #x << " is:" << x << "]"<<el; #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); // decimal --> fixed << setprecision #define orderedset template<class T> using ordered_set = tree<T, null_type, std::less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define tree typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set; //member functions : //1. order_of_key(k) : number of elements strictly lesser than k //2. find_by_order(k) : k-th element in the set bool sortbyPair(const pair<int, int> &a, const pair<int, int> &b) { if (a.second != b.second) return (a.second > b.second); else return (a.first < b.first); } ll fast_power(ll base, ll exp) { if (!exp) return 1; ll ans = fast_power(base, exp / 2); ans = (ans % 1000000007 * ans % 1000000007) % 1000000007; if (exp & 1) ans = (ans % 1000000007 * base % 1000000007) % 1000000007; return ans; } ll convert_binary_to_decimal(long long n) { int dec = 0, i = 0, rem; while (n != 0) { rem = n % 10; n /= 10; dec += rem * pow(2, i); i++; } return dec; } bool is_prime(ll n) { if (n == 0 or n == 1) return 0; for (int i = 2; i < n; ++i) { if (n % i == 0) return 0; } return 1; } ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll lcm(ll a, ll b) { return ((((a / gcd(a, b)) % 1000000009) * (b % 1000000009)) % 1000000009); } //ll ncr2(ll n, ll r) { // ll ans = 1, fact = 2; // for (ll i = n - r + 1; i <= n; i++) { // ans *= i; // if (ans % fact == 0 and fact <= r) // ans /= fact++; // } // return ans; //} //ll factorial[1000006], inversefactorial[1000006]; // //void calcFacAndInv(ll n) { // factorial[0] = inversefactorial[0] = 1; // for (ll i = 1; i <= n; i++) { // factorial[i] = (i * factorial[i - 1]) % 1000000007; // inversefactorial[i] = fast_power(factorial[i], 1000000007 - 2); // } //} // //ll ncr1(ll n, ll r) { // return ((factorial[n] % 1000000007 * // ((inversefactorial[n - r] % 1000000007 * inversefactorial[r] % 1000000007) % 1000000007) % 1000000007) % // 1000000007); //} // // //ll npr(ll n, ll r) { // return ((factorial[n] % 1000000007 * inversefactorial[n - r] % 1000000007) % 1000000007); //} //vector<bool> sieve(ll n) { // vector<bool> isPrime(n + 1, 1); // isPrime[0] = isPrime[1] = 0; // for (ll i = 2; i <= n; i++) // if (isPrime[i]) // for (ll j = 2 * i; j <= n; j += i) // isPrime[j] = 0; // return isPrime; //} //vector<pair<ll, ll>> factorize(ll n) { // vector<pair<ll, ll>> fact; // for (ll i = 2; i * i <= n; i++) { // int cnt = 0; // while (n % i == 0) { // n /= i; // cnt++; // } // if (cnt) fact.push_back({i, cnt}); // } // if (n > 1) fact.push_back({n, 1}); // return fact; //} //vector<ll> getdivisors(ll n) { // vector<ll> divs; // for (ll i = 2; i * i <= n; i++) { // if (n % i == 0) { // divs.push_back(i); // if (i != n / i) divs.push_back(n / i); // } // } // return divs; //} // upper_bound -->(greater than only) -->return iterator // lower_bound -->(greater than or equal) -->return iterator //vector<ll> factorize(ll n) { // vector<ll> fact; // for (ll i = 2; i * i <= n; i++) { // while (n % i == 0) { // n /= i; // fact.push_back(i); // } // } // if (n > 1) fact.push_back(n); // return fact; //} //ll arr[200][200]; //int n; //ll res = -1; // // //void solve(ll sm, int i, int j) { // cout << i << " " << j << " --> " << sm << el; // if (i == n - 1 and j == n - 1) { // res = max(sm, res); //// cout << sm << " "; // return; // } // // // go right // if (j < n - 1) { // solve(sm + arr[i][j + 1], i, j + 1); // }else{ // solve(sm + arr[i][0], i, 0); // } // // // go down // if (i < n - 1) { // solve(sm + arr[i + 1][j], i + 1, j); // }else{ // solve(sm + arr[0][j], 0, j); // } // // res = max(res, sm); // //} int main() { fast int t = 1; cin >> t; while (t--) { string str; cin >> str; int cnt = 0; for (int i = str.find('1'); i < str.rfind('1'); i++) { if (str[i] == '0') cnt++; } cout << cnt << el; } return 0; }
cpp
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
#include <bits/stdc++.h> #define f first #define s second #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 vi = vector<int>; using vp = vector <pii>; using vl = vector<ll>; const int inf = INT_MAX; const ll linf = LLONG_MAX; const int mod = 1e9+7; int mex(vi v) { sort(all(v)); v.resize(unique(all(v)) - v.begin()); for(int i = 0; i < sz(v); i++) if(i != v[i]) return i; return sz(v); } vector <vector<array<int, 3>>> step[6][6][6]; vector <vector<array<int, 3>>> period[6][6][6]; void solve() { int n, x, y, z; scanf("%d %d %d %d", &n, &x, &y, &z); vl a(n); auto sg = [&](ll v, int j) -> int { ll b = v / 5; int r = v % 5; if(b < sz(step[x][y][z])) { return step[x][y][z][b][r][j]; } else { b -= sz(step[x][y][z]); b %= sz(period[x][y][z]); return period[x][y][z][b][r][j]; } }; ll tot = 0; for(auto &v : a) { scanf("%lld", &v); tot ^= sg(v, 0); } int ans = 0; array <int, 3> w = {x, y, z}; for(auto &v : a) { ll cur = tot ^ sg(v, 0); for(int j : {0, 1, 2}) { if(cur == sg(max(0ll, v - w[j]), j)) ans++; } } printf("%d\n", ans); } int main() { //the lcm idea i had was wrong but this is small enough so that proof by hardcoding is ok :8 for(int x = 1; x <= 5; x++) { for(int y = 1; y <= 5; y++) { for(int z = 1; z <= 5; z++) { set <vector<array<int, 3>>> S; //funny ds. i guess i could hash + unordered map, or remember floyd cycle finding? vector <array<int, 3>> sg; vector <vector<array<int, 3>>> block_sg; array <int, 3> w = {x, y, z}; for(int j = 0; ; j += 5) { //[j, j + 5) vector <array<int, 3>> block; for(int k = j; k < j + 5; k++) { array <int, 3> nsg; if(k == 0) nsg = {0, 0, 0}; else for(int i : {0, 1, 2}) { vi v; for(int j : {0, 1, 2}) { if(!i || i != j) { v.pb(sg[max(0, k - w[j])][j]); } } nsg[i] = mex(v); } block.pb(nsg); sg.pb(nsg); } if(S.count(block)) { bool f = false; for(int q = 0; q < sz(block_sg); q++) { if(!f && block_sg[q] == block) f = true; if(!f) { step[x][y][z].pb(block_sg[q]); } else { period[x][y][z].pb(block_sg[q]); } } break; } block_sg.pb(block); S.insert(block); } } } } int tc; scanf("%d", &tc); while(tc--) { solve(); } return 0; }
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" ]
//#pragma GCC optimize(2) #include <bits/stdc++.h> using namespace std; /*测量运行时间 #include <windows.h> DWORD star_time = GetTickCount(); DWORD end_time = GetTickCount(); cout << (end_time - star_time) << "ms." << endl; */ typedef long long ll; typedef pair<int,int> PII; typedef double db; #define pb push_back #define fi first #define SZ(x) ((int)(x).size()) #define se second #define int128 __int128 #define endl '\n' #define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); template <class T> inline bool in(T &ret) { char c;T sgn; if(c=getchar(),c==EOF) return 0; while(c!='-'&&(c<'0'||c>'9')) c=getchar(); sgn=(c=='-')?-1:1; ret=(c=='-')?0:(c-'0'); while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0'); ret*=sgn; return 1; } template <class T> inline void out(T x) { if(x<0) { putchar('-'); x=-x; } if(x>9) out(x/10); putchar(x%10+'0'); } const int N = 4e5 + 100; PII a[N]; int ans[N]; int main() { int T = 1; cin >> T; while(T -- ) { int n;cin >> n; memset(ans, 0, sizeof ans); for(int i = 1;i <= n;i ++ ) { int l, r;cin >> l >> r; a[i * 2 - 1] = {l, -i}; a[2 * i] = {r, i}; } multiset<int> s; sort(a+1, a + n*2+1); int c = 0; for(int i = 1;i <= 2 * n;i ++ ) { if(a[i].se < 0) { s.insert(-a[i].se); } else { s.erase(s.find(a[i].se)); } if(SZ(s) == 0) c ++; if(SZ(s) == 1 && a[i].se > 0 && a[i+1].se < 0 && a[i+1].fi > a[i].fi) { ans[*s.begin()] ++; } if(SZ(s) == 1 && a[i].se < 0 && a[i+1].se > 0) { ans[*s.begin()] --; } } int Ans = -n; for(int i = 1;i <= n;i ++ ) { Ans = max(Ans, ans[i]); } cout << c + Ans << endl; } return 0; }
cpp
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
#include<iostream> #include<cstring> using namespace std; using LL = long long; const int maxn = 3e5 + 5; int n, a, b, c; int f[1005][3]; int sg[maxn], val[maxn]; int dp(int x, int y){ if (~f[x][y]) return f[x][y]; int s[4] = {0}; s[dp(max(0, x - a), 0)] = 1; if (y != 1) s[dp(max(0, x - b), 1)] = 1; if (y != 2) s[dp(max(0, x - c), 2)] = 1; int ans = 0; while(s[ans]) ans++; return f[x][y] = ans; } int solve(){ memset(f, -1, sizeof f); f[0][0] = f[0][1] = f[0][2] = 0; for(int len = 1; ; len++){ bool success = 1; for(int i = 1000; i >= 500; i--){ for(int j = 0; j < 3; j++) if (dp(i, j) != dp(i - len, j)){ success = 0; break; } if (!success) break; } if (success) return len; } return -1; } int main(){ #ifdef LOCAL freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif cin.tie(0); cout.tie(0); ios::sync_with_stdio(0); int T; cin >> T; while(T--){ cin >> n >> a >> b >> c; int len = solve(); int ans = 0; for(int i = 1; i <= n; i++){ LL x; cin >> x; if (x > 1000) x = 500 / len * len + x % len; val[i] = x; ans ^= (sg[i] = dp(x, 0)); } int cnt = 0; for(int i = 1; i <= n; i++){ int t = dp(max(0, val[i] - a), 0); if ((t ^ ans ^ sg[i]) == 0) cnt++; t = dp(max(0, val[i] - b), 1); if ((t ^ ans ^ sg[i]) == 0) cnt++; t = dp(max(0, val[i] - c), 2); if ((t ^ ans ^ sg[i]) == 0) cnt++; } cout << cnt << '\n'; } }
cpp
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
#include "bits/stdc++.h" using namespace std; #define ll long long const int MAXN = 100100; const int LOG = 20; int n; vector<int> g[MAXN]; int dep[MAXN]; int jp[LOG][MAXN]; void dfs(int c, int l, int d) { dep[c] = d; jp[0][c] = l; for (int i : g[c]) { if (i == l) continue; dfs(i, c, d + 1); } } int lca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); int k = dep[x] - dep[y]; for (int i = 0; i < LOG; i++) { if (k & (1 << i)) { x = jp[i][x]; } } if (x == y) return x; for (int i = LOG - 1; i >= 0; i--) { if (jp[i][x] == jp[i][y]) continue; x = jp[i][x]; y = jp[i][y]; } return jp[0][x]; } int dist(int x, int y) { int L = lca(x, y); return (dep[x] - dep[L]) + (dep[y] - dep[L]); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i < n; i++) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(1, 1, 0); for (int i = 1; i < LOG; i++) { for (int j = 1; j <= n; j++) { jp[i][j] = jp[i - 1][jp[i - 1][j]]; } } auto check = [](int x, int y) { return ((x & 1) == (y & 1)) && x <= y; }; int q; cin >> q; while (q--) { int x, y, a, b, k; cin >> x >> y >> a >> b >> k; int ans = check(dist(a, b), k) || check(dist(a, x) + 1 + dist(y, b), k) || check(dist(a, y) + 1 + dist(x, b), k); cout << (ans ? "YES\n" : "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" ]
#include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define ll long long #define vvll vector<vector<ll>> #define all(v) v.begin(),v.end() #define vvc vector<vector<char>> #define vss vector<string> #define emp emplace #define pb push_back #define pf push_front #define dq deque #define llmn LONG_LONG_MIN #define llmx LONG_LONG_MAX #define umll unordered_map<ll> #define mll map<ll,ll> #define sll set<ll> #define usll unordered_set<ll> #define vll vector<ll> #define vpll vector<pair<ll,ll>> #define pll pair<ll,ll> #define mk make_pair #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define fr(i,a,b) for(ll i=a;i<b;++i) #define rev(i,a,b) for(ll i=a;i>=b;--i) #define tr(it,m) for(auto it:m) #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> const int M=998244353; long long mod(long long x) { return ((x%M + M)%M); } long long add(long long a, long long b) { return mod(mod(a)+mod(b)); } long long mul(long long a, long long b) { return mod(mod(a)*mod(b)); } using namespace std; // this is mod exp ll modexp(ll a, ll b) { ll ans=1; while(b>0){ if((b%2)==1){ ans=mul(ans,a); } a=mul(a,a); b/=2; } return ans; } // this is disjointset class DisjointSet { vector<int> rank, parent, size; public: DisjointSet(int n) { rank.resize(n+1, 0); parent.resize(n+1); size.resize(n+1); for(int i = 0;i<=n;i++) { parent[i] = i; size[i] = 1; } } int findUPar(int node) { if(node == parent[node]) return node; return parent[node] = findUPar(parent[node]); } void unionByRank(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if(ulp_u == ulp_v) return; if(rank[ulp_u] < rank[ulp_v]) { parent[ulp_u] = ulp_v; } else if(rank[ulp_v] < rank[ulp_u]) { parent[ulp_v] = ulp_u; } else { parent[ulp_v] = ulp_u; rank[ulp_u]++; } } void unionBySize(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if(ulp_u == ulp_v) return; if(size[ulp_u] < size[ulp_v]) { parent[ulp_u] = ulp_v; size[ulp_v] += size[ulp_u]; } else { parent[ulp_v] = ulp_u; size[ulp_u] += size[ulp_v]; } } }; void ngr(vll& v,vll& ans) { stack<ll> s; ll n=v.size(); s.emp(v[n-1]); ans.pb(-1); rev(i,n-2,0) { while(s.size()!=0&&s.top()<v[i]) s.pop(); if(s.size()==0){ans.pb(-1);} else ans.pb(s.top()); s.emp(v[i]); } reverse(ans.begin(),ans.end()); return; } void ngl(vll& v,vll& ans) { ll n=v.size(); stack<ll> s; ans.pb(-1); s.emp(v[0]); fr(i,1,n) { while(s.size()!=0&&s.top()<v[i]) s.pop(); if(s.size()==0) ans.pb(-1); else ans.pb(s.top()); s.emp(v[i]); } return; } void primefact(ll n,vll& v) { ll temp=2; while(temp<sqrtl(n)) { while(n%temp==0) { n=n/temp; v.pb(temp); } ++temp; } if(n>1) v.pb(n); } ll power(ll a,ll b,ll c=M) { if(a==0) return 0; if(b==0) return 1; if(b%2==0){ ll ans=power(a,b/2,c); ll final=mul(ans,ans); return final; } else return mul(a,power(a,b-1,c)); } ll power(ll x,int y, int p) { ll res = 1; // Initialize result x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } ll modInverse(unsigned long long n,int p) { return power(n, p - 2, p); } ll nCrModPFermat(ll n,ll r,ll p) { if (n < r) return 0; if (r == 0) return 1; ll fac[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p)% p; } int main() { fastio; ll t; cin>>t; while(t--) { ll n;cin>>n; vll v(2*n); fr(i,0,2*n) cin>>v[i]; sort(all(v));cout<<(v[n]-v[n-1])<<"\n"; } return 0; }
cpp
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
#include<iostream> using namespace std; #include <cmath> #include <algorithm> #define ll long long #define fi first #define se second #define sst string #define pb push_back #ifndef _GLIBCXX_NO_ASSERT #include <cassert> #endif #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #if __cplusplus >= 201103L #include <ccomplex> #include <cfenv> #include <cinttypes> #include <cstdbool> #include <cstdint> #include <ctgmath> #include <cwchar> #include <cwctype> #endif #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> #if __cplusplus >= 201103L #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <forward_list> #include <future> #include <initializer_list> #include <mutex> #include <random> #include <ratio> #include <regex> #include <scoped_allocator> #include <system_error> #include <thread> #include <tuple> #include <typeindex> #include <type_traits> #include <unordered_map> #include <unordered_set> #endif #define maxco 100000+5 #define lld long double #define cha ios_base::sync_with_stdio(false); #define mod 1000000007 #define ffl cout.flush(); #define phi acos(-1) // //ll a[200069]; //sst t=""; //void precom(){ // for(ll i=0;i<1000;i++){ // t+=(phi%10); // phi/ // } //} //int main(){ // ll tc; // // cin>>tc; // while(tc--){ // vector <ll> vec; // ll n,s,r; // cin>>n>>s>>r; // ll sisa=s-r; // vec.pb(sisa); // cout<<sisa<<" "; // n--; // if(r%n==0){ // ll t=n; // while(t--){ // cout<<r/n<<" "; // } // } // else{ // // } // cout<<endl; // } //} ll a[200069]; ll le[1569][1509]; ll dp[300069]; int main(){ ll n; cin>>n; for(ll i=1;i<=n;i++)cin>>a[i]; memset(le, 0, sizeof(le)); for(ll i=1;i<=n;i++){ le[i][a[i]]=i; } for(ll i=1;i<=n;i++){ for(ll j=1;j<=1500;j++){ if(le[i][j]==0){ le[i][j]=le[le[i][j-1]-1][j-1]; } } } memset(dp, mod, sizeof(dp)); dp[0]=0; for(ll i=1;i<=n;i++){ for(ll j=1;j<=1500;j++){ if(le[i][j]!=0){ dp[i] = min(dp[i], dp[le[i][j]-1]+1); } } } cout<<dp[n]; }
cpp
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
#include <bits/stdc++.h> // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> // using namespace __gnu_pbds; using namespace std; #define int long long int #define ll long long #define mod 1000000007 // #define mod 998244353 #define fastIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL) #define endl "\n" #define mp make_pair #define pb push_back #define pf push_front #define lb lower_bound #define ub upper_bound #define vi vector<int> #define min_heap_pii priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> #define min_haep_i priority_queue<int, vector<int>, greater<int>> #define umii unordered_map<int, int> #define vpi vector<pair<int, int>> #define preci(x) cout << fixed << setprecision(9) << x << endl #define msi map<string, int> #define mii map<int, int> #define spi set<pair<int, int>> #define vst vector<string> #define vbl vector<bool> #define vvi vector<vector<int>> #define pii pair<int, int> #define pbr(val) cout << val << endl; #define pn cout << "No" << endl #define py cout << "Yes" << endl #define pim cout << "Impossible" << endl #define PI acos(-1.0) // tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, // tree_order_statistics_node_update> // T; const int limit = 1e18; // const int sz = 1000005; // const int LOG = 20; // vector<vector<int>> dxy = { {1, 0}, {0, -1}, {-1, 0}, {0, 1} }; int dirx[] = {1, -1, 0, 0}; int diry[] = {0, 0, 1, -1}; int str_int(string s) { stringstream ob(s); int num = 0; ob >> num; return num; } vector<int> primef(int n) { vector<int> ans; if (n % 2 == 0) { ans.pb(2); while (n % 2 == 0) { n /= 2; } } for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { ans.pb(i); while (n % i == 0) { // ans.pb(i); n /= i; } } } if (n > 2) ans.pb(n); return ans; } vi fact(int n) { vi ans; for (int i = 1; i * i <= n; i++) { if (n % i == 0) { if (i == n / i) { ans.pb(i); } else { ans.pb(i); ans.pb(n / i); } } } return ans; } int binExp(int base, int exp) { base %= mod; int res = 1; while (exp > 0) { if (exp & 1) { res = (int)((long long)res * base % mod); } base = (int)((long long)base * base % mod); exp >>= 1; } return res; } void sort_i(vi &v) { return sort(v.begin(), v.end()); } void sort_d(vi &v) { return sort(v.begin(), v.end(), greater<int>()); } int log_a_to_base_b(int a, int b) { return log(a) / log(b); } int msb(int n) // most significant bit of a number { int ans = -1; while (n > 0) { n >>= 1; ans++; } return ans; } int modInv(int a, int m) { return binExp(a, m - 2); } int sum_v(vector<int> &a) { int val = accumulate(a.begin(), a.end(), 0ll); return val; } bool is_nondecreasing(vector<int> &a, int s, int e) { bool flag = 1; for (int i = s + 1; i <= e; i++) { if (a[i] < a[i - 1]) { flag = 0; break; } } return flag; } int lcm(int a, int b) { int ans = a * b / __gcd(a, b); return ans; } bool is_same_parity(int a, int b) { if (a % 2 == b % 2) { return true; } else { return false; } } bool ispalin(string s, int l, int r) { bool flag = 1; while (l < r) { if (s[l] != s[r]) { flag = 0; break; } l++; r--; } if (flag) { return true; } else { return false; } } int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } void printyn(bool val) { if (val) cout << "YES" << endl; else cout << "NO" << endl; } bool isSubSequence(string str1, string str2, int m, int n) { int j = 0; for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; return (j == m); } void nextGreater(vector<int> &nums, vector<int> &ng) { stack<int> st; int len = nums.size(); ng[len - 1] = -1; // ng[len - 1] = len; st.push(len - 1); for (int i = len - 2; i >= 0; i--) { while (!st.empty() && nums[st.top()] <= nums[i]) st.pop(); if (st.empty()) // ng[i] = len; ng[i] = -1; else ng[i] = st.top(); st.push(i); } } void preGreater(vi &nums, vi &pg) { stack<int> st; int n = nums.size(); pg[0] = -1; st.push(0); for (int i = 1; i < n; i++) { while (st.size() > 0 && nums[st.top()] <= nums[i]) { st.pop(); } if (st.empty()) { pg[i] = -1; } else pg[i] = st.top(); st.push(i); } } void nextSmaller(vector<int> &nums, vector<int> &ns) { stack<int> st; int len = nums.size(); // ns[len - 1] = -1; ns[len - 1] = len; st.push(len - 1); for (int i = len - 2; i >= 0; i--) { while (!st.empty() && nums[st.top()] >= nums[i]) st.pop(); if (st.size() > 0) ns[i] = st.top(); st.push(i); } } void preSmaller(vi &nums, vi &ps) { stack<int> st; int len = nums.size(); for (int i = 0; i < len; i++) { while (st.size() > 0 && nums[st.top()] >= nums[i]) { st.pop(); } if (st.size() > 0) { ps[i] = st.top(); } st.push(i); } } int dig_len(int n) { int cnt = 0; while (n > 0) { n /= 10; cnt++; } return cnt; } bool is_vowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'o' || ch == 'u' || ch == 'i') return 1; return 0; } bool is_digit(char ch) { int val = ch - '0'; if (val >= 0 && val <= 9) return 1; return 0; } int binomialCoeff(int n, int r) { if (r > n || n < 0 || r < 0) return 0; int m = 998244353; int inv[r + 1] = {0}; inv[0] = 1; if (r + 1 >= 2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[m % i] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = ((ans % m) * (inv[i] % m)) % m; } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = ((ans % m) * (i % m)) % m; } return ans; } vi fac, ifac; void precompute(int n) { fac.resize(n + 1); fac[0] = fac[1] = 1; for (int i = 2; i <= n; i++) { fac[i] = (int)((long long)i * fac[i - 1] % mod); } ifac.resize(n + 1); for (int i = 0; i < fac.size(); i++) { ifac[i] = binExp(fac[i], mod - 2); } return; } int nCr(int n, int r) { if ((n < 0) || (r < 0) || (r > n)) { return 0; } return (int)((long long)fac[n] * ifac[r] % mod * ifac[n - r] % mod); } bool isprime(int x) { for (int i = 2; i * 1ll * i <= x; i++) if (x % i == 0) return false; return true; } // mod stuff int add(int x, int y) { x += y; while (x >= mod) x -= mod; while (x < 0) x += mod; return x; } int sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll * y) % mod; } // prime factors of a numbers in log(n) time using sieve() #define MAXN 20000001 int spf[MAXN]; void sieve_log() { spf[1] = 1; for (int i = 2; i < MAXN; i++) spf[i] = i; for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i < MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it is not // previously marked if (spf[j] == j) spf[j] = i; } } } int getFactorization(int x) { // vector<int> ret; // unordered_set<int> ret; mii ret; while (x != 1) { ret[spf[x]]++; // to[(spf[x])]++; x = x / spf[x]; } return ret.size(); // cnt of to divisor // int ans = 1; // for (auto it : ret) // { // ans *= (it.second + 1); // } // return ans; } int mex(vi a) { int n = a.size(); unordered_set<int> s; for (int i = 0; i < n; i++) { s.insert(a[i]); } int ans = 0; for (int i = 0; i <= n; i++) { if (s.count(i) == 0) { ans = i; break; } } return ans; } /*******************************************************************/ // const int LOG = 20; // const int LIM = 100001; // vi adj[LIM]; // int up[LIM][LOG]; // int depth[LIM]; // bool vis[LIM]; // int col[LIM]; /*******************************************************************/ const int MAX_N = 100000; const int LIM = 17; const int INF = (int)1e9 + 7; vector<int> adj[MAX_N + 5]; int depth[MAX_N + 5]; int par[MAX_N + 5][LIM + 1]; void build(int cur, int p) { int i; depth[cur] = depth[p] + 1; par[cur][0] = p; for (i = 1; i <= LIM; i++) par[cur][i] = par[par[cur][i - 1]][i - 1]; for (int x : adj[cur]) if (x != p) build(x, cur); } int lca_len(int a, int b) { int i, len = 0; if (depth[a] > depth[b]) swap(a, b); for (i = LIM; i >= 0; i--) { if (depth[par[b][i]] >= depth[a]) { b = par[b][i]; len += (1 << i); } } if (a == b) return len; for (i = LIM; i >= 0; i--) { if (par[a][i] != par[b][i]) { a = par[a][i]; b = par[b][i]; len += (1 << (i + 1)); } } return len + 2; } // void dfs(int a, int p) // { // vis[a] = 1; // depth[a] = depth[p] + 1; // for (int b : adj[a]) // { // if (vis[b]) // continue; // // depth[b] = depth[a] + 1; // up[b][0] = a; // for (int j = 1; j < LOG; j++) // { // up[b][j] = up[up[b][j - 1]][j - 1]; // } // dfs(b, a); // } // } // int lca(int a, int b) // { // if (depth[a] < depth[b]) // swap(a, b); // int k = depth[a] - depth[b]; // for (int j = LOG - 1; j >= 0; j--) // { // if (k & (1 << j)) // a = up[a][j]; // } // if (a == b) // return a; // for (int j = LOG - 1; j >= 0; j--) // { // if (up[a][j] != up[b][j]) // { // a = up[a][j]; // b = up[a][j]; // } // } // return up[a][0]; // } // int calc(int a, int b) // { // int lc = lca(a, b); // int val = depth[a] + depth[b] - 2 * depth[lc]; // return val; // } void solve() { int n, q, i; cin >> n; for (i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } build(1, 0); cin >> q; while (q--) { int x, y, a, b, k; cin >> x >> y >> a >> b >> k; int without = lca_len(a, b); int with = min(lca_len(a, x) + lca_len(y, b), lca_len(a, y) + lca_len(x, b)) + 1; int ans = INF; if (without % 2 == k % 2) ans = without; if (with % 2 == k % 2) ans = min(ans, with); cout << (ans <= k ? "YES" : "NO") << '\n'; } // int n; // cin >> n; // for (int i = 0; i < n - 1; i++) // { // int u, v; // cin >> u >> v; // adj[u].pb(v); // adj[v].pb(u); // } // build(1, 0); // int q; // cin >> q; // while (q--) // { // int x, y, u, v, k; // cin >> x >> y >> u >> v >> k; // int d_uv = calc(u, v); // int d_edge = min(calc(u, x) + calc(y, v), calc(u, y) + calc(x, v)) + 1; // int ans = INT_MAX; // if (d_uv % 2 == k % 2) // { // ans = d_uv; // } // if (d_edge % 2 == k % 2) // { // ans = (ans, d_edge); // } // if (ans <= k) // { // cout << "YES" << endl; // } // else // { // cout << "NO" << endl; // } // } } signed main() { fastIO; int t = 1; // sieve_log(); // cin >> t; while (t--) { solve(); } }
cpp
1290
D
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "constructive algorithms", "graphs", "interactive" ]
#include<bits/stdc++.h> using namespace std; int n,K,kc,ks,vis[1030]; char s[3]; void ins(int x){ int l=kc*x+1,r=l+kc-1; for(int i=l;i<=r;i++)if(!vis[i]){cout<<"? "<<i<<endl;cin>>s;if(s[0]=='Y')vis[i]=1;} } void work(int x){ ins(x); for(int i=1;i<(ks>>1);i++){ ins((x-i+ks)%ks); ins((x+i)%ks); }if(ks>1)ins((x+(ks>>1))%ks); } int main(){ cin>>n>>K;kc=min(n,K);ks=n/kc; for(int i=0;i<ks;i++){ work(i);cout<<"R"<<endl; }int ans=0; for(int i=1;i<=n;i++)ans+=vis[i]^1; cout<<"! "<<ans<<endl; return 0; }
cpp
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
#include <bits/stdc++.h> #define Source ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL); #define ll long long #define int long long #define ld long double #define Endl '\n' //#define t int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define sz(a) (int)(a).size() using namespace std; const int N = 2e5 + 5; const ll mod = 1e9 + 7; int dx[] = {+0, +0, +1, -1, -1, +1, -1, +1}; int dy[] = {+1, -1, +0, +0, +1, -1, -1, +1}; void testCase(int cs) { string s,t; cin >> s >> t; vector<vector<int>>freq(26); for (int i = 0; i < sz(s); ++i) { freq[s[i] - 'a'].push_back(i + 1); } int ans = 0, lst = 0; for (int i = 0; i < sz(t); ++i) { int c = t[i] - 'a'; if(freq[c].empty()) { cout << -1 << endl; return; } auto it = upper_bound(all(freq[c]), lst); if(it != freq[c].end()) { lst = *it; } else { lst = freq[c][0]; ans++; } } cout << ans + 1 << endl; } signed main() { // files(); Source ll t = 1; int cs = 0; cin >> t; while (t--) { testCase(++cs); } 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 <bits/stdc++.h> using namespace std; #define FAST_IO ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); #define ll long long #define loop(n) for (int i{0}; i<n; ++i) #define lop(n) for (int i{1}; i<n; ++i) const int N = 2e5+7, mod= 1e9 + 7; int left_most(int n){ int pos = 0; while (n > 0) { n = n >> 1; pos++; } return pos; } bool sortbyfirst(const pair<int, int>& a, const pair<int, int>& b) { if (a.first != b.first) return (a.first < b.first); return a.second < b.second; } void solve(){ int n; cin>>n; vector <pair<int, int>> v; string s=""; loop(n){ int x,y; cin>>x>>y; v.push_back({x,y}); } sort(v.begin(), v.end(), sortbyfirst); //sort(v.begin(), v.end(), sortbysec); //cout<<v[0].first-0<<" "<<v[0].second-0<<endl; loop(v[0].first) s+='R'; loop(v[0].second) s+='U'; for (int i{1}; i<v.size(); ++i){ //cout<<v[i].first<<" "<<v[i].second<<endl; int x_d, y_d; x_d= v[i].first- v[i-1].first; y_d= v[i].second-v[i-1].second; //cout<<x_d<<" "<<y_d<<endl; if (x_d <0 || y_d<0){ cout<<"NO"<<endl; return; } loop(x_d) s+='R'; loop(y_d) s+='U'; } cout<<"YES"<<endl; cout<<s<<endl; } int main() { FAST_IO; int t; cin>>t; while(t--) solve(); return 0; }
cpp
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define c(ans) cout << ans << endl #define cs(ans) cout << ans << " " #define fori(i,j,k) for(ll i = j; i < k; i++) #define ifor(i,j,k) for(ll i = j; i >= k; i--) #define inarr(j,n,a) for(ll i = j; i < n; i++) cin >> a[i]; #define sortall(v) sort(v.begin(), v.end()) #define sortarr(a,n) sort(a,a+n) #define reverseall(v) reverse(v.begin(), v.end()) #define cy cout << "YES" << endl #define cn cout << "NO" << endl #define all(v) v.begin(), v.end() #define sz(v) v.size() #define pb push_back #define ff first #define ss second typedef vector<ll> vll; typedef pair<ll, ll> pll; typedef map<ll, ll> mll; typedef queue<ll> qll; typedef set<ll> sll; typedef stack<ll> stll; typedef priority_queue<ll> maxpqll; typedef priority_queue<ll, vector<ll>, greater<ll>> minpqll; const ll inf = 1e18; const ll mod = 1e9 + 7; void cv(vector<ll> v){ fori(i,0,v.size()){ cs(v[i]); } cout << endl; } ll firstsetbit(ll x){ return x & -x; } ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } ll sum(ll l, ll r) { ll ans = r * (r + 1) >> 1; ans -= (l * (l - 1) >> 1); return ans; } struct my { vector<ll> a; ll mx, mn; bool flag; }; //------------------------------------code------------------------------------// int main(){ ios::sync_with_stdio(false); cin.tie(0); // ll T; // cin >> T; // while(T--){ ll n; cin >> n; vector<my> v(n); vector<ll> maxi; ll have = 0; fori(i, 0, n){ ll x; cin >> x; v[i].a.resize(x); v[i].flag = false; v[i].mx = INT_MIN; v[i].mn = INT_MAX; fori(j, 0, x){ cin >> v[i].a[j]; v[i].mx = max(v[i].mx, v[i].a[j]); v[i].mn = min(v[i].mn, v[i].a[j]); if(j == 0){ continue; } if(v[i].a[j] > v[i].a[j - 1]){ v[i].flag = true; } } if(v[i].flag){ have++; continue; } maxi.pb(v[i].mx); } sortall(maxi); ll final = 0; ll size = sz(maxi); fori(i, 0, n){ if(v[i].flag){ final += n; continue; } ll just = upper_bound(all(maxi), v[i].mn) - maxi.begin(); final += (have + size - just); } c(final); // } return 0; }
cpp
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
// Depressed boy Bhaskor Roy #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() using namespace std; #define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define endl '\n' void s1(){ int n; cin>>n; int a[n]; int ev=0,od=0; vector<int>oda,eva; for(int i=0;i<n;i++){ cin>>a[i]; if(a[i]%2){ od++; oda.push_back(i+1); } else{ ev++; eva.push_back(i+1); } } if(n==1 && od==1){ cout<<-1<<endl; } else if(ev>=1){ cout<<1<<endl; cout<<eva[0]<<endl; } else{ cout<<2<<endl; cout<<oda[0]<<" "<<oda[1]<<endl; } } int main(){ optimize(); int t; cin>>t; while(t--){ s1(); } return 0; }
cpp
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
#include <bits/stdc++.h> using namespace std; #define ll long long // ll int N = 1e9+7; #define f(n) for (auto i = 0; i < n; i++) #define fo(i, k, n) for (auto i = k; i < n; i++) #define ff first #define ss second #define vi vector<int> #define rep(i, a, b) for (int i = a; i < b; i++) #define pb push_back #define mp make_pair #define sorr \ { \ ios_base::sync_with_stdio(false); \ cin.tie(nullptr); \ } double pi = 2 * acos(0.0); const int N = 1e9 + 7; ll int comp=1e18+1; // Sort the array in descending order // sort(arr, arr + n, greater<int>()); // global varible = 0. // cout<<fixed<<setprecision(9); // memset(array name,value to be filled,sizeof(array name)); // void rest(int a){ // f(a){par[i]=0;sze[i]=0;}return; // } int par[150008]; int sz[150008]; void make(int q) { par[q] = q; sz[q] = 1; } int find(int q) { if (par[q] == q) return q; return par[q] = find(par[q]); } void Union(int x, int y) { x = find(x); y = find(y); if (x != y) { if (sz[x] < sz[y]) swap(x, y); par[y] = x; sz[x] += sz[y]; } } // bool vis[10005]; // bool is_valid(int x,int y,int n,int qx,int qy){ // return(x>0&&y>0&&x<=n&&y<=n&&((qx-x)!=(qy-y))&&((qy-y)!=-(qx-x))&&x!=qx&&y!=qy); // } // vector<pair<int,int>>mov{ // {1,0},{0,1},{-1,0},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1} // }; // void rest(int n){ // f(n+2)v[i].clear(); // } // ll int t[2000006]; // ll int val[2000006]; // val[3]=1; // vector<int>v[100005]; // bool vis[1005]; // // ll int val[200005][20]; // ll int dis[1005]; // ll int par[1005]; // f(1005) {par[i]=-1;dis[i]=INT_MAX;} // vector<pair<ll int,ll int>>v[1005]; // void dfs(int strt){ // set<pair<ll int,ll int>>s;s.insert({0,strt}); // dis[strt]=0; // while(s.size()){ // pair<ll int ,ll int >p=*s.begin();s.erase(s.begin()); // ll int ind=p.second,wt=p.first; vis[ind]=true; // for(auto x:v[ind]){ // ll int nex=x.first,wigh=x.second; // if(wigh+wt<dis[nex]&&!vis[nex]){ // dis[nex]=wigh+wt;par[nex]=ind; // s.insert({dis[nex],nex}); // } // } // } // return; // } // void path(ll int source,vector<pair<ll int,ll int>>&vec,ll int& ans=0){ // while(source!=-1){ // if(par[source]!=-1) {vec.pb({par[source],source});if(m[par[source]][source]==0)ans++;} // return path(par[source],vec,ans); // } // return; // } // map<int,int>m; // void to_find(){ // for(int i=0;i<5000050;i++){ // ll int d=(2*i)+1; // m[d]++; // } // return 0; // } bool is_val[200004]; bool vis[200004]; bool dfs(int ind,vector<vector<int>>&v){ if(ind==1)return true; vis[ind]=true; for(auto child:v[ind]){ if(vis[child]||(!is_val[child]))continue; if( dfs(child,v))return true; } return false; } int main(){ int n,res=0;cin>>n;string s;cin>>s;int opn=0,clo=0,cto=-1,ctc=-1; f(n){ if(s[i]=='(')opn++;else clo++;} if(opn==clo){ f(n){ if(s[i]=='(')opn++;else clo++; if(clo>opn&&cto==-1){cto=0;ctc=1;clo=1;opn=0;} if(cto!=-1&&(clo==opn)){res+=(2*clo); // cout<<clo<<" "; cto=-1;ctc=-1;clo=0;opn=0;} } cout<<res<<endl; } else cout<<-1<<endl; return 0;}
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 "iostream" using namespace std; int n,m; int cnt=0; int main(){ cin>>n>>m; int temp=m/n; if(m%n!=0){ cout<<"-1"; return 0; } while(temp%2==0) { cnt++; temp/=2; } while(temp%3==0) { cnt++; temp/=3; } if(temp!=1){ cout<<"-1"; return 0; } cout<<cnt; return 0; }
cpp
1285
D
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3 1 2 3 OutputCopy2 InputCopy2 1 5 OutputCopy4 NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
[ "bitmasks", "brute force", "dfs and similar", "divide and conquer", "dp", "greedy", "strings", "trees" ]
/* ফেরা হলো না ঘরে, নাহি ফিরলো ঘর দিকে আমার, এসে পথেরই মাঝে, পেছনে তাকিয়ে ফিরে আবার হেঁটে যাই আমি খুঁজতে কিছু, আমি আজও জানিনা কিসেরি পিছু! */ #include <bits/stdc++.h> using namespace std; #ifdef ONLINE_JUDGE #define fast ios_base::sync_with_stdio(0); cin.tie(0); // fast IO! but only when online_judge #define debug 0 #else #define fast ; #define debug 1 #endif // some typedefs for my convenience #define int long long int #define pii pair<int, int> #define vi vector<int> #define si set<int> #define mi map<int, int> // some speedup macros #define gap ' ' #define endl '\n' #define print(str) cout << str << endl #define YES print("YES") #define NO print("NO") #define loop(i, begin, end) for(__typeof(end)i=begin-(begin>end); i!=end-(begin>end); i+=1-2*(begin>end)) #define all(v) v.begin(), v.end() void solve(int cases); int32_t main() { fast int total_cases = 1; // cin >> total_cases; loop(cases, 1, total_cases+1) solve(cases); return 0; } // SOLVE STARTS HERE int dc(vi &v, int bit, int cases) { if (bit == -1) return 0; vi ones, zeros; int ocount = 0, zcount = 0, out = 0; for (auto x: v){ if ((x>>bit) & 1) ocount++, ones.push_back(x); else zcount++, zeros.push_back(x); } if (ocount && zcount){ out = 1 << bit; out |= min(dc(zeros, bit-1, cases), dc(ones, bit-1, cases)); } else if (ocount) out = dc(ones, bit-1, cases); else if (zcount) out = dc(zeros, bit-1, cases); // if (cases == 67447) cout<<"ocount="<<ocount<<"zcount="<<zcount<<"bit="<<bit<<"+"; return out; } void solve(int cases) { int n, q, out=0, sum=0, flag=0, maxi=LLONG_MIN, mini=LLONG_MAX; int in; cin >> n; vi v(n); #define printp(p) cout << '(' << p.F << ',' << gap << p.S << ')' << endl; #define printx(array) { for (auto x : array) cout << x << gap; cout << endl; } #define scanx(array) { for (auto &x: array) cin >> x; } #define printxp(array) { for (auto x : array) cout << '(' << x.first << ',' << gap << x.second << ')' << gap; cout << endl; } scanx(v); print(dc(v, 31 - __builtin_clz(*max_element(all(v))), n)); END:; } /* Fihad arRahman [email protected] 18-02-2023 20:32 */
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
// OMAR AL-MIDANI // /* ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣀⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣷⣶⣤⣀⡀⠄⠄⠄⠄⠄⣰⣷⡀⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⣀⣀⣀⠄⠄⠄⠄⠄⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣄⠄⠄⢠⣿⣿⣷⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠤⠒⠛⠛⠛⠛⠻⠷⣦⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⣿⣿⣿⠟⠁⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⢀⣤⣤⣶⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⡤⠐⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⢀⣶⣿⣿⠿⢛⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠁⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⢠⣿⠟⠉⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠘⠁⠄⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠻⣿⣿⣿⣿⣿⣿⣿⡛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⣾⣿⡿⣽⡿⢹⣿⣿⣟⣿⢻⠇⢀⢹⣿⢿⣿⣿⣿⣿⣿⣦⣙⢿⣿⢷⣈⠻⢿⣟⢿⣿⣿⣿⣿⡇⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⢿⡿⠁⡿⠁⢸⣿⣿⢹⡇⢸⠄⠈⠄⠻⣏⠻⣿⡿⣿⣿⣿⣌⠛⢿⡌⠙⢧⣀⠙⢳⡹⢻⣿⣿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠘⡇⠄⡇⢠⣼⣿⣿⠈⡇⠘⠤⠤⠤⠤⢜⣢⣘⡻⢮⡛⢿⣿⣷⣬⡤⠤⠤⠤⠥⠤⠥⢬⣿⣧⡄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠁⠄⠄⠘⢿⡏⠛⠄⠄⠄⠄⠄⠄⠄⠄⠄⠙⣿⣿⣿⡿⠋⠉⠛⠉⠄⠄⠄⠄⠄⠄⠄⢹⡿⠃⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠘⡇⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⡟⠁⠈⢳⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢸⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠱⡀⠄⠄⠄⠄⠄⠄⠄⠄⠄⡜⠁⠄⠄⠈⢇⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⡇⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠑⠦⢄⣀⣀⣀⣀⣀⠴⠊⠄⠄⠄⠄⠄⠄⠑⠤⢀⣀⣀⣀⡀⠠⠔⠋⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣶⣦⣄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣤⣶⣆⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢸⣿⣿⣿⣿⣶⣄⣀⣀⣀⣀⣤⣾⣿⣿⣿⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢸⣿⣿⣿⣿⣿⣿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠘⣿⣿⣿⣿⠟⠁⠄⠄⠄⠄⠙⢿⣿⣿⣿⡟⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠘⠟⠋⠁⠄⠄⠄⠄⠄⠄⠄⠄⠉⠛⠿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ */ #include <bits/stdc++.h> using namespace std; typedef long long ll; #define TestCases() \ int t; \ cin >> t; \ while (t--) #define rep(x, n, i) for (int i = x; i < n; i++) #define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) #define F first #define S second #define all(v) v.begin(), v.end() #define e endl #define ln "\n" #define Yes cout << "YES" << ln #define No cout << "NO" << ln #define Invalid cout << -1 << ln #define pb push_back #define pf push_front #define mp map<char, ll> #define debug(a) cout << #a << " : " << a << ln #define debugLine() cout << "==============" << ln #define gcd(a, b) __gcd(a, b) #define left p<<1 , l , (l+r)>>1 #define right p<<1|1 , ((l+r)>>1)+1 , r const int N = 2e4 + 7; const int M = 1000000007; #define log(x)\(31 ^ __builtin_clz(x)) // Easily calculate log2 on GNU G++ compilers ll mul(ll x, ll y) { return (ll) x * y %M; } ll seg[60][4*N],lazy[60][4*N] , a[60][N] ,dp[60][N],pre[60][N]; void push(int g,int p){ if(!lazy[g][p]) return; seg[g][p<<1] += lazy[g][p]; seg[g][p<<1|1] += lazy[g][p]; lazy[g][p<<1] += lazy[g][p]; lazy[g][p<<1|1] +=lazy[g][p]; lazy[g][p] = 0; } ll upd(int g,int i , int j , int inc , int p , int l , int r){ if(j<l || r<i) return seg[g][p]; if(i<=l && r<=j) return lazy[g][p] += inc, seg[g][p] += inc; push(g,p); return seg[g][p] = max(upd(g,i , j , inc , left) , upd(g,i , j , inc , right)); } int main() { fast; int n,m,k; cin>>n>>m>>k; for(int i = 1;i <= n;i++){ for(int j = 1;j <= m;j++){ cin>>a[i][j]; } } for(int i = 1;i <= n;i++){ for(int j = 1;j <= m;j++){ pre[i][j] = pre[i][j-1] + a[i][j]; } } for(int i = 1;i <=m;i++){ dp[2][i]= pre[1][i]- pre[1][max(i-k,0)] + pre[2][i]-pre[2][max(i-k,0)]; upd(2,i,i,dp[2][i],1,1,m); } for(int i = 3;i <= n+1;i++){ for(int j = 1;j <= m;j++){ ll sum = pre[i][j]-pre[i][max(j-k,0)] + pre[i-1][j]-pre[i-1][max(j-k,0)]; upd(i-1,j,min(j+k-1,m),-a[i-1][j],1,1,m); dp[i][j] = sum + seg[i-1][1]; if(j>=k){ upd(i-1,j-k+1,j,a[i-1][j-k+1],1,1,m); } upd(i,j,j,dp[i][j],1,1,m); } } cout<<seg[n+1][1]<<ln; return 0; } // dp[i][j]=
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 N = 200005; int dis1[N], disn[N]; bitset<N> special; vector<int> g[N]; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, k; cin >> n >> m >> k; for (int i = 0; i < k; ++i) { int x; cin >> x; special[x] = 1; } for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } queue<int> q; memset(dis1, -1, sizeof dis1); q.push(1); dis1[1] = 0; vector<int> sorted; while (!q.empty()) { int src = q.front(); if (special[src]) { sorted.push_back(src); } q.pop(); for (int u : g[src]) { if (dis1[u] == -1) { dis1[u] = dis1[src] + 1; q.push(u); } } } memset(disn, -1, sizeof disn); disn[n] = 0; q.push(n); while (!q.empty()) { int src = q.front(); q.pop(); for (int u : g[src]) { if (disn[u] == -1) { disn[u] = disn[src] + 1; q.push(u); } } } int ans = 0; int mx = disn[sorted.back()]; // for (int i : sorted) { // cout << i << ' '; // } // cout << '\n'; // for (int i : sorted) { // cout << disn[i] << ' '; // } // cout << '\n'; for (int i = k - 2; i >= 0; --i) { ans = max(ans, dis1[sorted[i]] + mx); // cout << sorted[i] << ' ' << mx << ' ' << ans << '\n'; mx = max(mx, disn[sorted[i]]); } cout << min(disn[1], ans + 1) << '\n'; return 0; }
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; int main() { ios::sync_with_stdio(false); cin.tie(0); ll a, b[200001] = {}, c, res = 0, now = 0; cin >> a; for (ll i = 0; i < a; i++) cin >> b[i]; for (ll i = 0; i < a; i++) { cin >> c; b[i] -= c; } sort(b, b + a); for (ll i = a - 1; i >= 0; i--) { if (b[i] <= 0) break; while (b[i] + b[now] <= 0) now++; res += (i - now); } cout << res << endl; return 0; }
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
#include <bits/stdc++.h> #define fi first #define se second #define faster ios_base::sync_with_stdio(0); cin.tie(0); #define pb push_back using namespace std; using ll = long long; using pii = pair <int, int>; mt19937_64 Rand(chrono::steady_clock::now().time_since_epoch().count()); const int maxN = 2e5 + 1; const int inf = 0x3f3f3f3f; const int Mod = 1e9 + 7; ll a[maxN]; int n; bool in[maxN * 5]; vector <int> P; inline int rd(int l, int r){ return l + Rand() % (r - l + 1); } void Sieve(){ for (int i = 2; i <= 1e6; ++i){ if (!in[i]){ P.pb(i); for (int j = i * 2; j <= 1e6; j += i) in[j] = 1; } } } int check(ll x){ if (x == 0) return n; vector <ll> S; for (int i: P){ if (x % i == 0){ S.pb(i); while (x % i == 0) x /= i; } } if (x != 1) S.pb(x); ll res = n; for (ll i: S){ ll cnt = 0; for (int j = 1; j <= n; ++j){ cnt += min(a[j] < i ? n : a[j] % i, i - (a[j] % i)); } res = min(res, cnt); } return res; } void Init(){ cin >> n; Sieve(); for (int i = 1; i <= n; ++i){ cin >> a[i]; } vector <int> b(n); iota(b.begin(), b.end(), 1); shuffle(b.begin(), b.end(), Rand); b.resize(min(n, 20)); int ans = n; for (int i: b){ ans = min(ans, check(a[i])); ans = min(ans, check(a[i] - 1)); ans = min(ans, check(a[i] + 1)); } cout << ans; } #define taskname "test" signed main(){ faster if (fopen(taskname ".inp", "r")){ freopen(taskname ".inp", "r", stdin); freopen(taskname ".out", "w", stdout); } int tt = 1; //cin >> tt; while (tt--){ Init(); } if (fopen("timeout.txt", "r")){ ofstream timeout("timeout.txt"); cerr << "Time elapsed: " << signed(double(clock()) / CLOCKS_PER_SEC * 1000) << "ms\n"; timeout << signed(double(clock()) / CLOCKS_PER_SEC * 1000); timeout.close(); } }
cpp
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
#include <iostream> #include<bits/stdc++.h> #include<deque> #include<algorithm> #include<math.h> #include<sstream> #include<stdio.h> #include<bitset> #include<string> #include<vector> #include<unordered_map> #include<queue> #include<set> #include<fstream> #include<map> #define int long long int #define ld long double #define pi 3.1415926535897932384626433832795028841971 #define MOD1 998244353 using namespace std; random_device seed_gen; mt19937_64 engine(seed_gen()); int inf = 1e18; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; template <typename T, typename U> void debug(std::vector<pair<T, U>> v) {for (int i = 0; i < v.size(); i++) cout << "[ " << v[i].first << " " << v[i].second << " ]\n"; cout << "\n";} template <typename T> void debug(std::vector<T> v) {cout << "[ "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "]\n";} template <typename T> void debug(std::set<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(std::multiset<T> v) {cout << "[ "; for (auto x : v) cout << x << " "; cout << "]\n";} template <typename T> void debug(vector<vector<T>> v) {int n = v.size(), m = v[0].size(); for (int i = 0; i < n; i++) {cout << "[ "; for (int j = 0; j < m; j++) cout << v[i][j] << " "; cout << "]\n";}} template <typename T> void debug(T i) {cout << "[ " << i << " ]\n";} template <typename T, typename U> void debug(T i, U j) {cout << "[ " << i << " " << j << " ]\n";} template <typename T, typename U, typename V> void debug(T i, U j, V k) {cout << "[ " << i << " " << j << " " << k << " ]\n";} template <typename T, typename U, typename V, typename X> void debug(T i, U j, V k, X l) {cout << "[ " << i << " " << j << " " << k << " " << l << " ]\n";} template <typename T, typename U> void debug(pair<T, U> x) {cout << "[ " << x.first << " " << x.second << " ]\n";} int expo(int a, int b, int mod) { int res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b = b >> 1; } return res; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int mminvprime(int a, int b) { return expo(a, b, b + 2); } const int N = 1e5 + 12; int a[N], ind[N]; bool cmp(int x, int y) { return a[x] > a[y]; } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int n, p, k; cin >> n >> p >> k; vector<vector<int>> s(n + 1, vector<int>(p, 0)); for (int i = 1; i <= n; ++i) { cin >> a[i]; ind[i] = i; } sort(ind + 1, ind + n + 1, cmp); for (int i = 1; i <= n; ++i) { for (int j = 0; j < p; j++) { int x; cin >> x; s[i][j] = x; } } int all = 1 << p; vector<vector<int>> dp(n + 1, vector<int>(all + 1, -1)); dp[0][0] = 0; for (int i = 1; i <= n; ++i) { for (int mask = 0; mask < all; mask++) { int curind = ind[i]; int cur = i - __builtin_popcount(mask); if (cur <= k) { if (dp[i - 1][mask] != -1) dp[i][mask] = dp[i - 1][mask] + a[curind]; } else { if (dp[i - 1][mask] != -1) dp[i][mask] = dp[i - 1][mask]; } for (int j = 0; j < p; j++) { if (!(mask & (1 << j))) continue; if (dp[i - 1][mask ^ (1 << j)] != -1) dp[i][mask] = max(dp[i][mask], dp[i - 1][mask ^ (1 << j)] + s[curind][j]); } } } cout << dp[n][all - 1]; return 0; }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include <iostream> #include <cmath> using namespace std; int sum(long long int a, long long int b, long long int c){ return a+b+c; } int main() { int t; long long int a, b, c, n; long long int diff; cin >> t; while(t--){ cin >> a >> b >> c >> n; int arr[3]={a, b, c}; sort(arr, arr+3); diff=arr[2]-arr[0]; diff+=arr[2]-arr[1]; if(n >= diff){ n-=diff; if(n%3==0){ cout << "YES" << endl; }else{ cout << "NO" << endl; } }else{ cout << "NO" << endl; } } return 0; }
cpp
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".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 next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
#include <bits/stdc++.h> #define ll long long int #define take(n) ll n; cin>>n; #define fo(i,n) for(ll i = 0; i<(ll)n; ++i) #define rep(i,a,b,d) for(ll i=a; (d<0)?(i>b):(d>0)?i<b:0; i += d) #define takevect(a,n) vector<ll> a(n); fo(q,n) cin>>a[q]; #define el "\n" #define pii pair<ll,ll> #define F first #define S second #define elif else if #define PI atan(1)*4.0 #define dtb(nino,xixo) bitset<nino>(xixo).to_string() #define lb lower_bound #define ub upper_bound #define pb push_back #define maxval INT64_MAX #define printvect(a) for(auto gar: a) cout<<gar<<' '; cout<<el; #define print(x) cout<<x<<el; #define all(bbb) bbb.begin(), bbb.end() #define mod 1000000007 #define remove(x) erase(x) #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define tree_set tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> #define ordered_multiset tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; bool is_prime(ll n); vector<ll> sieve(ll n); vector<ll> Sieve(ll n); bool is_palindrome(string s); vector<ll> P; vector<ll> spf; void solve(ll tt) { take(n) string s; cin >> s; map<pii, ll> m; ll x = 0, y = 0; ll M = 1e9; ll X = -1, Y = -1; m[{0,0}] = 0; for(ll i = 1; i<=n; i++) { if(s[i-1]=='U') y++; if(s[i-1]=='D') y--; if(s[i-1]=='L') x--; if(s[i-1]=='R') x++; if(m.find({x,y})!=m.end()) { ll d = i - m[{x,y}]; if(M > d) { M = d; X = m[{x,y}]+1; Y = i; } } m[{x,y}] = i; } if(M < 1e9) cout << X <<" " << Y << el; else cout << -1 << el; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); ll t{1}; cin>>t; fo(tt,t) { solve(tt); } return 0; } bool is_prime(ll n) { if(n<=3) return true; if(n%2==0 || n%3==0) return false; ll i{5}; while(i*i <= n) { if(n%i==0 || n%(i+2)==0) return false; i += 6; } return true; } vector<ll> sieve(ll n) { vector<ll> prime(n+1,-1); for (ll p = 2; p * p <= n; p++) { if (prime[p] == -1) { for (ll i = p * p; i <= n; i += p) prime[i] = p; } } for(ll i = 2; i<=n; i++) { if(prime[i]==-1) prime[i] = i; } return prime; } vector<ll> Sieve(ll n) { vector<bool> prime(n+1, true); for(ll p = 2; p*p<=n; p++) { if(prime[p]) { for(ll i = p*p; i <= n; i += p) prime[i] = false; } } vector<ll> z; for(ll i = 2; i<=n; i++) if(prime[i]) z.pb(i); return z; } bool is_palindrome(string s) { int l = s.length(); for(int i=0;i<=l/2;i++) { if(s[i]!=s[l-i-1]) return false; } return true; }
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 <bits/stdc++.h> using namespace std; #define pb push_back //typedef __int128 lll; #define ll long long #define all(x) x.begin(),x.end() #define repp(n) for(int i=0;i<n;i++) const ll MOD=998244353; const ll mod = 1e9 +7; void solve(){ ll n,a,b,k; cin>>n>>a>>b>>k; vector<ll> h(n); repp(n)cin>>h[i]; ll ans = 0; ll ok = a+b; vector<pair<ll,ll>> v; for(int i=0;i<n;i++){ ll temp = h[i]%ok; if(temp==0 || temp>a){ if(temp == 0){ temp = b; } else{ temp-=a; } ll t1 = 0; if(temp%a==0) t1 = temp/a; else t1 = temp/a +1; v.pb({t1,h[i]}); } else ans++; } sort(all(v)); repp(v.size()){ if(v[i].first<=k){ ans++; k-=v[i].first; } else break; } cout<<ans<<endl; } int main() { // int t; // cin>>t; // while(t--) { solve(); } 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 #define FOR(i, j, k) for (int i = j; i <= k; i++) #define FORR(i, j, k) for (int i = j; i >= k; i--) ll inf = 0x3f3f3f3f, linf = LLONG_MAX/2; ll MOD = 1e9+7; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll n, m; cin >> n >> m; vector<ll> v(n+1); v[0] = 1; FOR (i, 1, n) { v[i] = v[i-1]*i%m; } ll ans = 0; FOR (l, 1, n) { ans = (ans + (n-l+1) * v[l]%m * v[n-l+1]%m) % m; } cout << ans << '\n'; return 0; } // (n-l+1) * l! * (n-l+1)! // https://www.cnblogs.com/scnucjh/p/12153516.html
cpp
1313
E
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5];
[ "data structures", "hashing", "strings", "two pointers" ]
#include <bits/stdc++.h> #define int long long using namespace std; const int maxn = 1e6 + 10; int n,m; int f[4*maxn],lazy[4*maxn]; void down(int x, int lx, int rx) { f[x]+=(rx-lx+1)*lazy[x]; if (lx!=rx) { lazy[2*x]+=lazy[x]; lazy[2*x+1]+=lazy[x]; } lazy[x]=0; } void add(int x, int lx, int rx, int l, int r, int val) { if (lazy[x]!=0) down(x,lx,rx); if (lx>r||rx<l) return; if (lx>=l&&rx<=r) { lazy[x]+=val; down(x,lx,rx); return; } int mid=(lx+rx)/2; add(2*x,lx,mid,l,r,val); add(2*x+1,mid+1,rx,l,r,val); f[x]=f[2*x]+f[2*x+1]; } int get(int x, int lx, int rx, int l, int r) { if (lazy[x]!=0) down(x,lx,rx); if (lx>r||rx<l) return 0; if (lx>=l&&rx<=r) return f[x]; int mid=(lx+rx)/2; return get(2*x,lx,mid,l,r)+get(2*x+1,mid+1,rx,l,r); } vector <int> zfunction(string s) { int n=s.length(); vector <int> z(n,0); int l,r; l=r=0; z[0]=0; for (int i=1; i<n; i++) { z[i]=0; if (i<=r) z[i]=min(z[i-l],r-i+1); while (i+z[i]<n&&s[z[i]]==s[i+z[i]]) z[i]++; if (i+z[i]-1>r) { r=i+z[i]-1; l=i; } } return z; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin>>n>>m; string a,b,s; cin>>a>>b>>s; vector <int> z=zfunction(s+'$'+a); vector <int> za(n+1), zb(n+1); for (int i=1; i<=n; i++) za[i]=z[i+m]; reverse(s.begin(),s.end()); reverse(b.begin(),b.end()); z=zfunction(s+'$'+b); for (int i=n; i>=1; i--) zb[n-i+1]=z[i+m]; int ans=0; for (int i=n; i>=1; i--) { add(1,1,m,1,zb[i],1); if (i+m-1<=n) add(1,1,m,1,zb[i+m-1],-1); ans+=get(1,1,m,m-za[i],m-1); } cout<<ans<<'\n'; }
cpp
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
#include <bits/stdc++.h> // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> // using namespace __gnu_pbds; // #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> using namespace std; typedef long long ll; typedef long double ldb; typedef vector<int> vi; typedef vector<long long> vl; typedef vector<double> vdb; typedef vector<vector<int>> vvi; typedef vector<vector<ll>> vvl; typedef vector<string> vs; typedef set<int> si; typedef set<long long> sl; typedef set<double> sdb; typedef set<string> ss; typedef set<char> sc; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define ftb(i, a, b) for (int i = a, _b = b; i <= _b; i++) #define ft(i, a, b) for (int i = a, _b = b; i < _b; i++) #define fgb(i, a, b) for (int i = a, _b = b; i >= _b; i--) #define fg(i, a, b) for (int i = a, _b = b; i > _b; i--) #define endl "\n" ll mx(ll z, vl &a) { ll mn = 0; for (int i = 0;i < a.size() - 1;i++) { ll q = a[i]; ll k = a[i + 1]; if (a[i] == -1) { q = z; } if (a[i + 1] == -1) { k = z; } mn = max(mn, abs(q - k)); } return mn; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; vl a(n); ft(i, 0, n) { cin >> a[i]; } int l = 0, r = 1e9; while (l <= r) { if (r - l < 3) break; int z = (2 * l + r) / 3; int k = (l + 2 * r) / 3; ll temp1 = mx(z, a), temp2 = mx(k, a); if (temp1 < temp2) { r = k; } else l = z; } int ans = 1e9, num = 0; ftb(i, l, r) { int temp = mx(i, a); if (ans > temp) { ans = temp; num = i; } } cout << ans << " " << num << endl; } return 0; }
cpp
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4 OutputCopy2 3 1InputCopy1 3 OutputCopy3 1 1 1InputCopy8 5 OutputCopy-1InputCopy0 0 OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
#include <bits/stdc++.h> using namespace std; int main() { long long u,v; scanf("%I64d%I64d",&u,&v); if (u%2!=v%2 || u>v) { printf("-1"); return 0; } if (u==v) { if (!u) printf("0"); else printf("1\n%I64d",u); return 0; } long long x=(v-u)/2; if (u&x) printf("3\n%I64d %I64d %I64d",u,x,x); else printf("2\n%I64d %I64d",(u^x),x); }
cpp
1291
F
F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "graphs", "interactive" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; #define all(x) (x).begin(),(x).end() #define X first #define Y second #define sep ' ' #define debug(x) cerr << #x << ": " << x << endl; const ll MAXN = 1e6 + 10; int n, k; vector<int> B[MAXN]; set<pll> st; inline bool ask(int x) { cout << "? " << x << endl; string ans; cin >> ans; return ans == "Y"; } inline void R() { cout << "R" << endl; } inline vector<int> hamiltonian_path(int n, int i) { vector<int> path; for (int j = 0; j < n; j++) path.push_back((i + (j & 1 ? -1 : 1) * ((j + 1) / 2) + n) % n); return path; } int main() { cin >> n >> k; if (n == 1 && k == 1) return cout << "! 1" << endl, 0; if (k > 1) k /= 2; for (int i = 0; i < n / k; i++) { for (int j = 1; j <= k; j++) { int x = i * k + j; if (!ask(x)) B[i].push_back(x); } } R(); for (int i = 0; i < n / k / 2; i++) { vector<int> path = hamiltonian_path(n / k, i); for (int e : path) for (int j = B[e].size() - 1; j >= 0; j--) if (ask(B[e][j])) B[e].erase(B[e].begin() + j); for (int i = 1; i < path.size(); i++) st.insert({min(path[i], path[i - 1]), max(path[i], path[i - 1])}); R(); } int ans = 0; for (int i = 0; i < n / k; i++) ans += B[i].size(); cout << "! " << ans << endl; return 0; }
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
// LUOGU_RID: 101284988 #include <bits/stdc++.h> #define int long long #define mem(a,b) memset(a,b,sizeof(a)) #define fre(z) freopen(z".in","r",stdin),freopen(z".out","w",stdout) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> Pair; const double eps=1e-8; const int inf=2139062143; #ifdef ONLINE_JUDGE static char buf[1000000],*p1=buf,*p2=buf,obuf[1000000],*p3=obuf; #define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++ #endif inline void qread(){}template<class T1,class ...T2> inline void qread(T1 &a,T2&...b){ register T1 x=0;register bool f=false;char ch=getchar(); while(ch<'0') f|=(ch=='-'),ch=getchar(); while(ch>='0') x=(x<<3)+(x<<1)+(ch^48),ch=getchar(); x=(f?-x:x);a=x;qread(b...); } inline void dread(){}template<class T1,class ...T2> inline void dread(T1 &a,T2&...b){ register double w=0;register ll x=0,base=1; register bool f=false;char ch=getchar(); while(!isdigit(ch)) f|=(ch=='-'),ch=getchar(); while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar(); w=(f?-x:x);if(ch!='.') return a=w,dread(b...);x=0,ch=getchar(); while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),base*=10,ch=getchar(); register double tmp=(double)(x/(double)base);w=w+(double)(f?-tmp:tmp);a=w;dread(b...); } template<class T> T qmax(T x,T y){return x>y?x:y;} template<class T,class ...Arg> T qmax(T x,T y,Arg ...arg){return qmax(x>y?x:y,arg...);} template<class T> T qmin(T x,T y){return x<y?x:y;} template<class T,class ...Arg> T qmin(T x,T y,Arg ...arg){return qmin(x<y?x:y,arg...);} template<class T> T randint(T l,T r){static mt19937 eng(time(0));uniform_int_distribution<T>dis(l,r);return dis(eng);} const int MAXN=57; const int MAXM=2e4+7; int n,m,k,b[MAXM],a[MAXN][MAXM],f[MAXN][MAXM]; struct Seg_tree{ #define ls p<<1 #define rs p<<1|1 #define mid ((l+r)>>1) int tr[MAXM<<2],tag[MAXM<<2]; inline void pup(int p){tr[p]=qmax(tr[ls],tr[rs]);} inline void f(int p,int l,int r,int k){tr[p]+=k;tag[p]+=k;} void pwn(int p,int l,int r){ f(ls,l,mid,tag[p]);f(rs,mid+1,r,tag[p]);tag[p]=0; }void build(int a[],int p,int l,int r){ tag[p]=0;if(l==r) tr[p]=a[l]; else build(a,ls,l,mid),build(a,rs,mid+1,r),pup(p); }void upd(int p,int l,int r,int L,int R,int k){ if(L<=l&&r<=R) f(p,l,r,k); else{ pwn(p,l,r);if(L<=mid) upd(ls,l,mid,L,R,k); if(R>mid) upd(rs,mid+1,r,L,R,k);pup(p); } }int que(int p,int l,int r,int L,int R){ if(L<=l&&r<=R) return tr[p]; else{ int res=0;pwn(p,l,r); if(L<=mid) res=que(ls,l,mid,L,R); if(R>mid) res=qmax(res,que(rs,mid+1,r,L,R));return res; } } #undef mid }st[MAXN];int s[MAXN][MAXM],ans; signed main(){ qread(n,m,k);int i,j;for(i=1;i<=n;i++) for(j=1;j<=m;j++) qread(a[i][j]),s[i][j]=s[i][j-1]+a[i][j]; for(j=1;j<=m-k+1;j++) f[1][j]=s[1][j+k-1]-s[1][j-1]; for(i=2;i<=n;i++){ for(j=1;j<=k;j++) b[j]=f[i-1][j]+s[i][j+k-1]-s[i][k]; for(j=k+1;j<=m-k+1;j++) b[j]=f[i-1][j]+s[i][j+k-1]-s[i][j-1]; st[i-1].build(b,1,1,m);f[i][1]=st[i-1].que(1,1,m,1,m-k+1)+s[i][k]; // if(i==2){ // for(j=1;j<=m;j++) cout<<b[j]<<" ";cout<<endl; // // cout<<b[j]<<" ";cout<<endl; // cout<<st[i-1].que(1,1,m,1,m-k+1)<<" "<<s[i][k]<<endl; // } for(j=2;j<=m-k+1;j++){ st[i-1].upd(1,1,m,qmax(1ll,j-k),j-1,a[i][j-1]); st[i-1].upd(1,1,m,j,j+k-1,-a[i][j+k-1]); f[i][j]=st[i-1].que(1,1,m,1,m-k+1)+s[i][j+k-1]-s[i][j-1]; } }for(i=1;i<=m-k+1;i++) ans=qmax(ans,f[n][i]);printf("%lld\n",ans); // for(i=1;i<=n;i++){for(j=1;j<=m-k+1;j++) cout<<f[i][j]<<" ";cout<<endl;} #ifndef ONLINE_JUDGE cerr<<"Time: "<<clock()<<endl; system("pause > null"); #endif return 0; }
cpp
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
#include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define int ll #define fr first #define se second #define INF 0x3f3f3f3f #define LINF 0x3f3f3f3f3f3f3f3f #define For(i,a,b) for(int i = a; i <= b; ++i) #define Rep(i,a,b) for(int i = a; i >= b; --i) using namespace std; typedef pair<int,int> pii; #ifdef OVAL const ll N = 2e3+10; #else const ll N = 2e5+10; #endif string s; int n, q; int sum[N][30]; vector<int> query[N]; void solve() { cin >> s; n = s.size(); s = " " + s; For(i,1,n){ For(j,0,26)sum[i][j] = sum[i-1][j]; sum[i][s[i]-'a']++; } cin >> q; while(q--){ int l, r; cin >> l >> r; // cout << s.substr(l, r-l+1) << ' '; if(s[l] != s[r] || r==l){ cout << "Yes\n"; continue; } if(r-l+1 <= 3){ cout << "No\n"; continue; } int cnt[30], num = 0; For(i,0,26){ cnt[i] = sum[r][i]-sum[l-1][i]; if(cnt[i])num++; } if(num <= 2)cout << "No\n"; else cout << "Yes\n"; } } signed main() { ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int tt = 1; // cin >> tt; For(tc,1,tt){ solve(); } return 0; } /* acacaabcaacbca 7 1 5 6 9 10 14 1 8 2 6 3 7 1 14 acbca baacc */
cpp
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
#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> 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 }, m{ o }, k{}; r s{ o() }; v p{ o(m) }, c(26); ra::sort(p); i(0, n) { W(k < m && p[k] < i + 1) ++k; c[s[i] - 'a'] += m - k + 1; } o[c]; } int main() { z t{ o }; while (t--) solve_test_case(); }
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 Source ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL); #define ll long long #define int long long #define ld long double #define Endl '\n' //#define t int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define sz(a) (int)(a).size() using namespace std; const int N = 2e5 + 5; const ll mod = 1e9 + 7; int dx[] = {+0, +0, +1, -1, -1, +1, -1, +1}; int dy[] = {+1, -1, +0, +0, +1, -1, -1, +1}; void testCase(int cs) { string s; cin >> s; s.push_back('R'); int ans = 0, lst = 0; for (int i = 0; i < sz(s); ++i) { if(s[i] == 'R') { ans = max( (i+1) - lst, ans); lst = i + 1; } } cout << ans << endl; } signed main() { // files(); Source ll t = 1; int cs = 0; cin >> t; while (t--) { testCase(++cs); } 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; ll dp[mm*10]; int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); ll x; cin>>x; ll bjx=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); int n=v.size(); int k=sqrt(bjx)+1; for(int i=0;i<=k;i++)dp[i]=1; for(int i=0;i<n;i++){ for(int j=k;j>=v[i];j--){ if(j%v[i]==0){ dp[j]=max(dp[j],dp[j/v[i]]*v[i]); } } } ll ma=1; for(int i=k;i>=1;i--){ ma=max(ma,dp[i]); } cout<<bjx/ma<<' '<<ma; }
cpp
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
/* * created by Mohamed hossam #### #### ## ## ## ## ## ## ##### ## ## ###### ## ## ## ## ## ## ## ####### ############## ## ## ######## ## ###### ## ## ## ####### ############## ######### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ### ##### ## ## ## ## ## ####### ######## */ #include <bits/stdc++.h> #define ll long long #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; int main() { fast; ll t; cin>>t; while(t--) { ll n; cin>>n; ll a[n],x=0; vector<pair<ll,ll>>v; for(ll i=0; i<n; i++) { cin>>a[i]; if(a[i]%2==0)x=i+1; else v.push_back({a[i],i+1}); } if(x!=0)cout<<1<<"\n"<<x<<"\n"; else if(x==0&&v.size()>=2)cout<<2<<"\n"<<v[0].second<<" "<<v[1].second<<"\n"; else cout<<"-1\n"; } }
cpp
1301
F
F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105)  — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m)  — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5 1 2 1 3 4 4 5 5 1 2 1 3 2 1 1 3 4 2 2 2 2 OutputCopy2 0 InputCopy4 4 8 1 2 2 8 1 3 4 7 5 1 7 6 2 3 8 8 4 1 1 2 2 1 1 3 4 1 1 2 4 1 1 4 4 OutputCopy2 3 3 4 NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4).
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
/// Nu am loc de lista de adicenta? Calculez singur vecinii. /// Nota: Nu e nev de nodurile auxiliare pentru a compresa graful - daca ma joc odata prin culoare, nu ma mai uit #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #define debug(x) cerr << #x << " " << x << "\n" #define debugs(x) cerr << #x << " " << x << " " using namespace std; typedef long long ll; typedef pair <short, short> pii; const ll NMAX = 1002; const ll VMAX = 41; const ll INF = (1LL << 59); const ll MOD = 1000000009; const ll BLOCK = 318; const ll base = 31; const ll nrbits = 21; int dist[NMAX][NMAX][41]; int mat[NMAX][NMAX]; vector <pii> v[41]; short dx[] = {0, 1, -1, 0}; short dy[] = {1, 0, 0, -1}; short n, m; bool OK(short i, short j) { if(i > 0 && i <= n && j > 0 && j <= m) return 1; return 0; } int main() { #ifdef HOME ifstream cin(".in"); ofstream cout(".out"); #endif // HOME ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); short k, i, j; cin >> n >> m >> k; for(i = 1; i <= n; i++) { for(j = 1; j <= m; j++) { cin >> mat[i][j]; v[mat[i][j]].push_back({i, j}); } } deque <pii> dq; for(int col = 1; col <= k; col++) { for(i = 1; i <= n + 1; i++) { for(j = 1; j <= max(m, k); j++) { dist[i][j][col] = 32767; } } for(auto x : v[col]) { dist[x.first][x.second][col] = 0; dq.push_back({x.first, x.second}); } while(dq.size()) { pii x = dq.front(); dq.pop_front(); if(x.first != n + 1) { for(int d = 0; d < 4; d++) { pii care = {x.first + dx[d], x.second + dy[d]}; if(!OK(care.first, care.second)) continue; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1; dq.push_back({care.first, care.second}); } } pii care = {n + 1, mat[x.first][x.second]}; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col]; dq.push_front({care.first, care.second}); } } else { for(auto y : v[x.second]) { pii care = y; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1; dq.push_back({care.first, care.second}); } } } } } int q; cin >> q; while(q--) { int a, b, c, d; cin >> a >> b >> c >> d; int minim = abs(c - a) + abs(d - b); for(int col = 1; col <= k; col++) { minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1); } cout << minim << "\n"; } return 0; }
cpp
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10 codeforces dodivthree OutputCopy5 7 8 4 9 2 2 9 10 3 1 InputCopy7 abaca?b zabbbcc OutputCopy5 6 5 2 3 4 6 7 4 1 2 InputCopy9 bambarbia hellocode OutputCopy0 InputCopy10 code?????? ??????test OutputCopy10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
[ "greedy", "implementation" ]
#include <bits/stdc++.h> #define ll long long #define yes cout << "YES\n" #define no cout << "NO\n" #define pb insert #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; cin>>n; string a,b; cin>>a>>b; map<int,set<int>>m; map<int,int>m1; set<pair<int,int>>ans; for(int i=0;i<n;i++)m[b[i]].pb({i+1}); set<int>v,vektor,vektor1; map<int,int>mapa; for(int i=0;i<n;i++){ if(a[i]=='?'){ continue; } if(m[a[i]].size()){ int r=*m[a[i]].begin(); m[a[i]].erase(m[a[i]].begin()); ans.pb({i+1,r}); mapa[i+1]=1; m1[r]=1; } } for(int i=1;i<=n;i++){ if(!m1[i]){ if(b[i-1]!='?'){ vektor.pb(i); } } } // spajam ? iz string a sa nekim slovom iz stringa b slobodnim // m1 je za string b for(int i=1;i<=n;i++){ if(a[i-1]=='?'){ // spajam sa vektorom if(!vektor.size())break; int r=*vektor.begin(); ans.pb({i,r}); vektor.erase(vektor.begin()); m1[r]=1; mapa[i]=1; } } for(int i=1;i<=n;i++){ if(!mapa[i]){ if(a[i-1]!='?'){ vektor1.pb(i); } } } // sad iz stringa B ? spajam sa nekim slovom iz a for(int i=1;i<=n;i++){ if(b[i-1]=='?'){ // spajam sa vektorom if(!vektor1.size())break; int r=*vektor1.begin(); ans.pb({r,i}); vektor1.erase(vektor1.begin()); m1[i]=1; mapa[r]=1; } } set<int>s; for(int i=1;i<=n;i++){ if(!m1[i]){ if(b[i-1]=='?')s.pb(i); } } for(int i=1;i<=n;i++){ if(!mapa[i]){ if(a[i-1]!='?')continue; if(!s.size())break; int r=*s.begin(); ans.pb({i,r}); s.erase(s.begin()); } } cout<<ans.size()<<endl; for(auto it:ans){ cout<<it.first<<" "<<it.second<<endl; } }
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" ]
#define _CRT_SECURE_NO_WARNINGS #include<bits/stdc++.h> #include <unordered_map> using namespace std; typedef long long ll; #define l "\n" #define mod 100000009; #define L_M LLONG_MAX typedef unsigned long long ull; #define all(v) v.begin(),v.end() ll gcd(ll a, ll b) { return(!b) ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } void Naked_Compiler() { ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif } #define lpr pair<ll,ll> bool comparefn(lpr a, lpr b) { if (a.second != b.second) return a.first < b.first; return a.second < b.second; } const int N =10000; int main() { Naked_Compiler(); int tst; cin >> tst; while (tst--) { int n, cnt = 0; string s; cin >> n >> s; while (true) { bool ch = false; for (int i = 0; i < n; i++) { if (i == n - 1)break; if (s[i] == 'A' && s[i + 1] == 'P') { s[i + 1] = 'A'; i++; ch = true; } } cnt++; if (!ch)break; } cout << cnt - 1 << l; } }
cpp