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
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<stdio.h> char c[1000002];int n,cnt=0,v=0; int main(){ scanf("%d%s",&n,c+1); for(int i=1;i<=n;i++){ if(c[i]=='(')v++; else v--; if(v<0||(v==0&&c[i]=='('))cnt++; }printf("%d",v?-1:cnt); }
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<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=2e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[N]; char str[N]; ll f[N]; ll ans[26]; void solve() { n=read(),m=read(); memset(ans,0,sizeof ans); memset(f,0,sizeof(ll)*(n+4)); scanf("%s",str+1); for(int i=1;i<=m;i++) w[i]=read(); f[1]++,f[n+1]--; for(int i=1;i<=m;i++) f[1]++,f[w[i]+1]--; for(int i=1;i<=n;i++) f[i]=f[i]+f[i-1]; for(int i=1;i<=n;i++) { int c=str[i]-'a'; ans[c]+=f[i]; } for(int i=0;i<26;i++) printf("%lld ",ans[i]); printf("\n"); } int main() { // init(); // stin(); scanf("%d",&T); // T=1; while(T--) solve(); return 0; }
cpp
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 OutputCopy56 6 442 1 45 80 NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
[ "implementation" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back int main() { int t; ll a,b,x,y; cin>>t; while(t--){ cin>>a>>b>>x>>y; ll ans,ans1,ans2,ans3,ans4; ans = ans1 = ans2 = ans3 = ans4 = 0; ans1 = a * y; ans2 = b * x; ans3 = (a - 1 - x) * b; ans4 = a * (b - 1 - y); ans = max(ans1,ans2); ans = max(ans,max(ans3,ans4)); cout<<ans<<endl; } return 0; }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include <bits/stdc++.h> #define all(v) v.begin(), v.end() #define S second #define F first #define pb push_back using namespace std; typedef long long ll; const int N = 2e5 + 123; ll n, a, b, k; vector <ll> dp(N, 1); vector <ll> dpn(N); string s; int main() { cin >> n >> s; for(int i = 0; i < n; i++) { for(int j = 25; j > s[i] - 97; j--) { dp[i] = max(dp[i], dpn[j] + 1); } dpn[s[i] - 97] = max(dpn[s[i] - 97], dp[i]); } ll mx = *max_element(all(dpn)); cout << mx << '\n'; for(int i = 0; i < n; i++) { cout << dp[i] << ' '; } }
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" ]
#include <bits/stdc++.h> using namespace std; using ll=long long; bool isPrime(ll n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (ll i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } int computeXOR(int n) { // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; // If n%4 gives remainder 3 return 0; } int main() { // your code goes here ll test; cin>>test; while(test--) { ll a,b,c=0,d=0; cin>>a>>b; if(a<9&&b<9) cout<<'0'<<endl; else { d=9; while(d<=b) { c+=a; d*=10; d+=9; } cout<<c<<endl; } } return 0; }
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
///KoJa #include<bits/stdc++.h> using namespace std; #define task "test" #define vec vector #define fi first #define se second #define SZ(a) (a).begin(), (a).end() #define SZZ(a, Begin, End) (a) + (Begin), (a) + (Begin) + (End) #define BIT(n) (1LL << (n)) #define MASK(x, i) (((x) >> (i))&1) #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int, int> ii; template <class T> inline bool maximize(T &a, const T &b) { return (a < b ? (a = b, 1) : 0); } template <class T> inline bool minimize(T &a, const T &b) { return (a > b ? (a = b, 1) : 0); } struct Points { ll x, y; Points(){} Points(ll _x, ll _y) { x = _x; y = _y; } Points operator - (const Points &other) const { return Points(x - other.x, y - other.y);} ll operator * (const Points &other) const { return x * other.y - y * other.x;} ll triangle(const Points &b, const Points &c) { return (*this - b) * (*this - c); } }; void fastio() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); if(fopen(task ".inp", "r")) { freopen(task ".inp", "r", stdin); freopen(task ".out", "w", stdout); } else if(fopen(task ".in", "r")) { freopen(task ".in", "r", stdin); freopen(task ".out", "w", stdout); } } const int N = 50 + 10; const int M = int(2e4) + 10; const int INF = int(1e9); int n, m, k; int a[N][M], dp[N][M], pref[N][M]; void init() { cin >> n >> m >> k; for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) cin >> a[i][j]; } class SegmentTree { private: int n; vec<int> st; void update(int pos, int val, int l, int r, int id) { if((l > r)||(l > pos)||(pos > r)) return; if(l == r) { st[id] = val; return; } int mid = (l + r) >> 1; update(pos, val, l, mid, 2 * id); update(pos, val, mid + 1, r, 2 * id + 1); st[id] = max(st[2 * id], st[2 * id + 1]); } int getMax(int u, int v, int l, int r, int id) { if((u > v)||(l > r)||(u > r)||(l > v)) return -INF; if((u <= l)&&(r <= v)) return st[id]; int mid = (l + r) >> 1; return max(getMax(u, v, l, mid, 2 * id), getMax(u, v, mid + 1, r, 2 * id + 1)); } public: SegmentTree(int _n = 0) { this->n = _n; st.assign(4 * n + 10, -INF); } void update(int pos, int val) { return update(pos, val, 1, n, 1);} int getMax(int l, int r) { return getMax(l, r, 1, n, 1);} } it1, it2, it3; void process(int tc = 0) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) pref[i][j] = pref[i][j - 1] + a[i][j]; } for(int i = 1; i + k - 1 <= m; i++) dp[1][i] = pref[1][i + k - 1] - pref[1][i - 1] + pref[2][i + k - 1] - pref[2][i - 1]; for(int i = 2; i <= n + 1; i++) { it1 = it2 = it3 = SegmentTree(m); /** cost = sum(i->i+1, j->j+k-1) dp(i, j) = dp(i - 1, x) + cost x = 1->j-k dp(i, j) = dp(i - 1, y) + cost y = j+k->m dp(i, j) = dp(i - 1, z1) + cost - sum(i, z1->j+k-1) z1=j->j+k-1 dp(i, j) = dp(i - 1, z2) + cost - sum(i, j->z2+k-1) z2=j-k+1->j */ for(int j = 1; j + k - 1 <= m; j++) { it1.update(j, dp[i - 1][j]); //cout << i - 1 << " " << j << " " << dp[i - 1][j] << '\n'; } for(int j = 1; j + k - 1 <= m; j++) it2.update(j, dp[i - 1][j] + pref[i][j - 1]); for(int j = 1; j + k - 1 <= m; j++) it3.update(j, dp[i - 1][j] - pref[i][j + k - 1]); for(int j = 1; j + k - 1 <= m; j++) { int cost = pref[i][j + k - 1] - pref[i][j - 1] + pref[i + 1][j + k - 1] - pref[i + 1][j - 1]; if(j - k >= 1) dp[i][j] = max(dp[i][j], it1.getMax(1, j - k)); if(j + k <= m - k + 1) dp[i][j] = max(dp[i][j], it1.getMax(j + k, m)); dp[i][j] = max(dp[i][j], it3.getMax(max(j - k + 1, 1), j) + pref[i][j - 1]); dp[i][j] = max(dp[i][j], it2.getMax(j, min(j + k - 1, m)) - pref[i][min(j + k - 1, m)]); dp[i][j] += cost; //cout << i << " " << j << " " << dp[i][j] << '\n'; } } int res = 0; for(int i = 1; i + k - 1 <= m; i++) res = max(res, dp[n + 1][i]); cout << res; } int main() { fastio(); int t = 1; //cin >> t; for(int i = 1; i <= t; i++) { init(); process(i); } 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; #define ll long long int ll f(ll bit,vector<ll> &a){ if(bit==-1){ return 0; } vector<ll> pre,ab; ll n=a.size(); for(ll i=0;i<n;i++){ if(((1<<bit)&a[i])>0){ pre.push_back(a[i]); } else{ ab.push_back(a[i]); } } if(pre.size()==0){ return f(bit-1,ab); } if(ab.size()==0){ return f(bit-1,pre); } return min(f(bit-1,pre),f(bit-1,ab)) + (1<<bit); } void solve(){ ll n; cin >> n; vector<ll> a (n); for (ll i = 0; i < n; i++) { cin >> a[i]; } cout<<f(30,a)<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll T = 1; while (T--) { solve(); } return 0; }
cpp
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <vector> #include <cstring> #include <unordered_set> #include <set> #include <stack> #include <map> #include <cmath> #include <sstream> #include <queue> #define int long long #define yes cout<<"YES"<<'\n' #define no cout<<"NO"<<'\n' using namespace std; const int N=110; int a[N]; bool cmp(int a,int b) { return a>b; } signed main () { ios::sync_with_stdio(false); int t; cin>>t; while(t--){ int n; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } sort(a,a+n,cmp); for(int i=0;i<n;i++){ cout<<a[i]<<' '; } cout<<'\n'; } return 0; }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
#include <bits/stdc++.h> using namespace std; using vi = vector<int>; int main () { cin.tie(0), ios::sync_with_stdio(0); int t, n; cin >> t; while (t--) { cin >> n; vi a(n); string s; cin >> s; int mod = 0; for (int i = 0; i < n; i++) { a[i] = s[i] - '0'; mod = (mod + a[i]) % 2; } while (a.size() && a.back() % 2 == 0) a.pop_back(); if (a.size() && mod) a.pop_back(); while (a.size() && a.back() % 2 == 0) a.pop_back(); if (a.size()) for (int x : a) cout << x; else cout << -1; cout << '\n'; } }
cpp
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
#include<bits/stdc++.h> using namespace std; #define int long long const int N=2e6,P=998244353; int n,m,b[N],s[N],f[N][2],x,y,z; string a; int H(int l,int r,int x) { return (f[r][x]-f[l-1][x]*b[s[r]-s[l-1]]%P+P)%P; } signed main() { cin>>n>>a>>m,a=' '+a,b[0]=1; for(int i=1;i<=n;i++) b[i]=3*b[i-1]%P,s[i]=s[i-1]+(a[i]=='0'); for(int i=1;i<=n;i++) if(a[i]=='0') f[i][0]=(3*f[i-1][0]+1+(i&1))%P,f[i][1]=(3*f[i-1][1]+1+(i&1^1))%P; else f[i][0]=f[i-1][0],f[i][1]=f[i-1][1]; while(m--&&cin>>x>>y>>z) puts(H(x,x+z-1,x&1)==H(y,y+z-1,y&1)?"YES":"NO"); }
cpp
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
/* * In the name of GOD */ #include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair <int, int> pii; #define F first #define S second #define mk make_pair const int N = 301234; vector <int> a[N], b[N]; int w[N], force[N], ans[N][2], all; bool f[N], s[N]; int get (int v) { if (force[v] == 2) { return min(ans[v][0], ans[v][1]); } else { return ans[v][force[v]]; } } void merge (int u, int v, bool we) { u = w[u], v = w[v]; if (u == v) return; all -= get(u); all -= get(v); if (a[u].size() > a[v].size()) swap (u, v); if (force[u] != 2) { force[v] = force[u] ^ we; } for (int x : a[u]) { a[v].push_back(x); f[x] ^= we; ans[v][f[x]]++; w[x] = v; } all += get(v); } int32_t main () { for (int i = 0; i < N; i++) { w[i] = i; a[i] = {i}; f[i] = 0; force[i] = 2; ans[i][0] = 1; } int n, k; cin >> n >> k; for (int i = 0; i < n; i++) { char c; cin >> c; s[i] = (c - '0'); } for (int i = 0; i < k; i++) { int c; cin >> c; while (c--) { int x; cin >> x; x--; b[x].push_back(i); } } for (int i = 0; i < n; i++) { if (b[i].size() == 0) { } else if (b[i].size() == 1) { int v = b[i][0]; all -= get(w[v]); force[w[v]] = s[i] ^ f[v]; all += get(w[v]); } else { int u = b[i][0], v = b[i][1]; int w = f[u] ^ f[v] ^ s[i] ^ 1; merge (u, v, w); } cout << all << '\n'; } }
cpp
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES
[ "geometry", "implementation" ]
#include <iostream> #include "vector" #include "string" #include "set" #include "cmath" #include "iomanip" #include "algorithm" #include "map" #include "unordered_set" using namespace std; typedef long long ll; typedef long double ld; typedef string str; const ld PI = acos(-1); void f() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } struct otr{ pair<ll, ll> fir; pair<ll, ll> sec; }; vector<otr> a(3); bool ygl(){ pair<ll, ll>q1 = {a[0].fir.first-a[0].sec.first, a[0].fir.second - a[0].sec.second}; pair<ll, ll>q2 = {a[1].fir.first-a[1].sec.first, a[1].fir.second - a[1].sec.second}; ld vec = q1.first*q2.second-q1.second*q2.first; ld skal = q1.first*q2.first+q1.second*q2.second; ld yg = atan2(vec, skal); return (skal >= 0 || abs(skal) < 1E-20); } bool prin(pair<ll, ll>q, otr t) { ld aa = t.fir.second - t.sec.second; ld bb = t.sec.first-t.fir.first; ld cc = -(aa*t.fir.first+bb*t.fir.second); ld qqq = aa*q.first+bb*q.second+cc; return (abs(qqq) < 1E-20 && q.first >= min(t.fir.first, t.sec.first) && q.first <= max(t.fir.first, t.sec.first)); } void proverka() { if (!ygl()) { cout << "NO" << "\n"; return; } if ((prin(a[2].fir, a[0]) && prin(a[2].sec, a[1])) || (prin(a[2].sec, a[0]) && prin(a[2].fir, a[1]))) { if ((prin(a[2].fir, a[0]) && prin(a[2].sec, a[1]))) { ld r1, r2, r3, r4; r1 = (a[0].fir.first-a[2].fir.first)*(a[0].fir.first-a[2].fir.first) + (a[0].fir.second-a[2].fir.second)*(a[0].fir.second-a[2].fir.second); r2 = (a[0].sec.first-a[2].fir.first)*(a[0].sec.first-a[2].fir.first) + (a[0].sec.second-a[2].fir.second)*(a[0].sec.second-a[2].fir.second); r3 = (a[1].fir.first-a[2].sec.first)*(a[1].fir.first-a[2].sec.first) + (a[1].fir.second-a[2].sec.second)*(a[1].fir.second-a[2].sec.second); r4 = (a[1].sec.first-a[2].sec.first)*(a[1].sec.first-a[2].sec.first) + (a[1].sec.second-a[2].sec.second)*(a[1].sec.second-a[2].sec.second); if (min(r1, r2)*16 >= max(r1, r2) && min(r3, r4)*16 >= max(r3, r4)) { cout << "YES" << "\n"; } else { cout << "NO" << "\n"; } } else { ld r1, r2, r3, r4; r1 = (a[0].fir.first-a[2].sec.first)*(a[0].fir.first-a[2].sec.first) + (a[0].fir.second-a[2].sec.second)*(a[0].fir.second-a[2].sec.second); r2 = (a[0].sec.first-a[2].sec.first)*(a[0].sec.first-a[2].sec.first) + (a[0].sec.second-a[2].sec.second)*(a[0].sec.second-a[2].sec.second); r3 = (a[1].fir.first-a[2].fir.first)*(a[1].fir.first-a[2].fir.first) + (a[1].fir.second-a[2].fir.second)*(a[1].fir.second-a[2].fir.second); r4 = (a[1].sec.first-a[2].fir.first)*(a[1].sec.first-a[2].fir.first) + (a[1].sec.second-a[2].fir.second)*(a[1].sec.second-a[2].fir.second); if (min(r1, r2)*16 >= max(r1, r2) && min(r3, r4)*16 >= max(r3, r4)) { cout << "YES" << "\n"; } else { cout << "NO" << "\n"; } } } else { cout << "NO" << "\n"; return; } } int main() { f(); ll t; cin >> t; while (t--) { for (ll i = 0; i < 3; ++i) { cin >> a[i].fir.first >> a[i].fir.second >> a[i].sec.first >> a[i].sec.second; } if (a[0].fir == a[1].fir) { proverka(); } else if (a[0].fir == a[1].sec) { swap(a[1].sec, a[1].fir); proverka(); } else if (a[0].fir == a[2].fir) { swap(a[1], a[2]); proverka(); } else if (a[0].fir == a[2].sec) { swap(a[2].sec, a[2].fir); swap(a[1], a[2]); proverka(); } else if (a[0].sec == a[1].fir) { swap(a[0].fir, a[0].sec); proverka(); } else if (a[0].sec == a[1].sec) { swap(a[0].fir, a[0].sec); swap(a[1].fir, a[1].sec); proverka(); } else if (a[0].sec == a[2].fir) { swap(a[0].fir, a[0].sec); swap(a[2], a[1]); proverka(); } else if (a[0].sec == a[2].sec) { swap(a[0].fir, a[0].sec); swap(a[2].fir, a[2].sec); swap(a[1], a[2]); proverka(); } else if (a[1].fir == a[2].fir) { swap(a[2], a[0]); proverka(); } else if (a[1].fir == a[2].sec) { swap(a[2].fir, a[2].sec); swap(a[2], a[0]); proverka(); } else if (a[1].sec == a[2].fir) { swap(a[1].sec, a[1].fir); swap(a[2], a[0]); proverka(); } else if (a[1].sec == a[2].sec) { swap(a[1].sec, a[1].fir); swap(a[2].sec, a[2].fir); swap(a[2], a[0]); proverka(); } else { cout << "NO" << "\n"; } } return 0; }
cpp
1313
D
D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.
[ "bitmasks", "dp", "implementation" ]
// LUOGU_RID: 101831831 // Problem: Happy New Year // Contest: Luogu // URL: https://www.luogu.com.cn/problem/CF1313D // Memory Limit: 500 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org) //不回家了,我们去鸟巢! #include<bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") using namespace std; inline int read(){ int s=0,w=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();} while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); return s*w; } pair<int,int> a[100003]; int f[100003][1<<8],g[100003][13],tr[13],arr[13]; signed main() { int n=read(),m=read(),w=read(),N=1<<w; for(int i=1; i<=n; ++i) a[i].first=read(),a[i].second=read(); sort(a+1,a+n+1), memset(f,0xc0,sizeof(f)), f[0][0]=0; a[n+1].first=m+1; for(int i=0; i<w; ++i) g[0][i]=0; for(int i=1; i<=n; ++i) { for(int j=0; j<w; ++j) tr[j]=1<<j; int o=0; while(o<w&&a[i].second>g[i-1][o]) ++o; assert(o!=0); for(int j=o; j<w; ++j) g[i][j]=g[i-1][j]; for(int j=0; j+1<o; ++j) g[i][j]=g[i-1][j+1]; g[i][o-1]=a[i].second; int O=(1<<o)-1; for(int j=0; j<N; ++j) f[i][j-(j&O)+((j&O)>>1)]= max(f[i][j-(j&O)+((j&O)>>1)],f[i-1][j]), f[i][j-(j&O)+((j&O)>>1)+(1<<(o-1))]= max(f[i][j-(j&O)+((j&O)>>1)+(1<<(o-1))],f[i-1][j]); for(int j=0; j<N; ++j) if(f[i][j]>=0) { int cnt=0; arr[0]=a[i].first-1; for(int k=0; k<w; ++k) if(((j>>k)&1)) arr[++cnt]=max(a[i].first-1, min(a[i+1].first-1,g[i][k])); for(int k=cnt; k>=1; k-=2) f[i][j]+=arr[k]-arr[k-1]; } } int ans=0; for(int i=0; i<N; ++i) ans=max(ans,f[n][i]); printf("%d\n",ans); return 0; }
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" ]
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #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::chrono; using namespace std; template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ; template<class key, class value, class cmp = std::less<key>> using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>; // find_by_order(k) returns iterator to kth element starting from 0; // order_of_key(k) returns count of elements strictly smaller than k; template<class T> using min_heap = priority_queue<T, vector<T>, greater<T> >; //--------------------------------IO(Debugging)-----------------------------// template<class T> istream& operator >> (istream &is, vector<T>& V) { for (auto &e : V) is >> e; return is; } template<class T, size_t N> istream& operator >> (istream &is, array<T, N>& V) { for (auto &e : V) is >> e; return is; } template<class T1, class T2> istream& operator >> (istream &is, pair<T1, T2>& V) { is >> V.first >> V.second; return is; } #ifdef __SIZEOF_INT128__ ostream& operator << (ostream &os, __int128 const& value) { static char buffer[64]; int index = 0; __uint128_t T = (value < 0) ? (-(value + 1)) + __uint128_t(1) : value; if (value < 0) os << '-'; else if (T == 0) return os << '0'; for (; T > 0; ++index) { buffer[index] = static_cast<char>('0' + (T % 10)); T /= 10; } while (index > 0) os << buffer[--index]; return os; } istream& operator >> (istream& is, __int128& T) { static char buffer[64]; is >> buffer; size_t len = strlen(buffer), index = 0; T = 0; int mul = 1; if (buffer[index] == '-') ++index, mul *= -1; for (; index < len; ++index) T = T * 10 + static_cast<int>(buffer[index] - '0'); T *= mul; return is; } #endif template<typename CharT, typename Traits, typename T> ostream& _containerprint(std::basic_ostream<CharT, Traits> &out, T const &val) { return (out << val << " "); } template<typename CharT, typename Traits, typename T1, typename T2> ostream& _containerprint(std::basic_ostream<CharT, Traits> &out, pair<T1, T2> const &val) { return (out << "(" << val.first << "," << val.second << ") "); } template<typename CharT, typename Traits, template<typename, typename...> class TT, typename... Args> ostream& operator << (std::basic_ostream<CharT, Traits> &out, TT<Args...> const &cont) { out << "[ "; for (auto && elem : cont) _containerprint(out, elem); return (out << "]"); } template<class L, class R> ostream& operator << (ostream& out, pair<L, R> const &val) { return (out << "(" << val.first << "," << val.second << ") "); } template<typename L, size_t N> ostream& operator << (ostream& out, array<L, N> const &cont) { out << "[ "; for (auto && elem : cont) _containerprint(out, elem); return (out << "]"); } template<class T> ostream& operator<<(ostream &out, ordered_set<T> const& S) { out << "{ "; for (const auto& s : S) out << s << " "; return (out << "}"); } template<class L, class R, class chash = std::hash<L> > ostream & operator << (ostream &out, gp_hash_table<L, R, chash> const& M) { out << "{ "; for (const auto& m : M) out << "(" << m.first << ":" << m.second << ") "; return (out << "}"); } template<class P, class Q = vector<P>, class R = less<P> > ostream & operator << (ostream& out, priority_queue<P, Q, R> const& M) { static priority_queue<P, Q, R> U; U = M; out << "{ "; while (!U.empty()) out << U.top() << " ", U.pop(); return (out << "}"); } template<class P> ostream& operator << (ostream& out, queue<P> const& M) { static queue<P> U; U = M; out << "{ "; while (!U.empty()) out << U.front() << " ", U.pop(); return (out << "}"); } #define TRACE #ifdef TRACE #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } #else #define trace(...) 1 #endif //------------------------------------RNG-----------------------------------// mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); inline int64_t random_long(long long l = LLONG_MIN, long long r = LLONG_MAX) { uniform_int_distribution<int64_t> generator(l, r); return generator(rng); } struct custom_hash { // Credits: https://codeforces.com/blog/entry/62393 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); } template<typename L, typename R> size_t operator()(pair<L, R> const& Y) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(Y.first * 31ull + Y.second + FIXED_RANDOM); } }; //------------------------------------Defines-------------------------------// //#define int long long #define ll long long //#define ull unsigned long long #define ld long double #define getline_clear cin.ignore() #define merge_arrays(a,b,c) merge(all(a),all(b),back_inserter(c)) #define uid(a, b) uniform_int_distribution<int>(a, b) #define pb push_back #define eb emplace_back #define F first #define S second typedef long long LL; typedef pair<ll, ll> pii; typedef pair<LL, LL> pll; typedef pair<string, string> pse; typedef vector<long long> vi; typedef vector<vi> vvi; typedef vector<pii> vii; typedef vector<LL> vl; typedef vector<vl> vvl; typedef map<ll,ll> mll; #define elif else if #define rep(i, n) for(int i=0;i<n;i++) #define repn(i, n) for(int i=1;i<=n;i++) #define reset(a, b) memset(a, b, sizeof(a)) #define cy cout<<"YES"<<"\n" #define cn cout<<"NO"<<'\n' #define cyo cout <<"YO"<<'\n'; #define fi first #define se second #define mp make_pair #define pb push_back #define pf push_front #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(), v.rend() #define sz size() #define mem1(a)memset(a,-1,sizeof(a)) //---------------------Global Constants and Functions-----------------------// ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} //ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N)) //-----------------------------Code begins----------------------------------// ll mod = 1e9 + 7; void solve(){ ll n,a,b,k; cin >> n >> a >> b >> k; vii p(n); rep(i,n){ cin >> p[i].fi; p[i].fi%= (a + b); if(p[i].fi == 0)p[i].fi += (a + b); p[i].se = (p[i].fi + a - 1)/a - 1; } sort(all(p),[&](pii x ,pii y){ return x.se < y.se; }); ll ans = 0; rep(i,n){ if(k - p[i].se >=0){ ans++; k-= p[i].se; } } cout << ans << '\n'; } int32_t main( void ) { ios_base::sync_with_stdio(false), cin.tie(NULL); // freopen("convention.in","r",stdin); // freopen("convention.out","w",stdout); int T = 1; //cin >> T; for (int t = 1; t <= T; t++) { //cout << "Case #" << t << ": "; solve(); } return 0; /*cout << "Time taken by function: " << duration.count() << " microseconds" << endl;*/ }
cpp
1316
F
F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2 1 2 2 1 2 2 1 OutputCopy500000004 1 500000004 InputCopy4 1 2 3 4 4 1 5 2 5 3 5 4 5 OutputCopy625000011 13 62500020 375000027 62500027 NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.
[ "data structures", "divide and conquer", "probabilities" ]
#include<bits/stdc++.h> using namespace std; const int maxn=600005; const int mod=(1e9+7); int n,m,i,j,t,k,s,ls[maxn],tls,a[maxn],b[maxn]; int pla[maxn],chg[maxn],two[maxn]; int sum[maxn<<2],cnt[maxn<<2],lef[maxn<<2],rig[maxn<<2]; inline int Pow(int x,int y) { int ret=1; while (y) { if (y&1) ret=1ll*ret*x%mod; x=1ll*x*x%mod;y>>=1; }return ret; } inline void re_new(int rt,int v,int c) { if (c==0) { sum[rt]=lef[rt]=rig[rt]=0;cnt[rt]=1; } else { sum[rt]=v*1ll*v%mod*(c*1ll*two[c-1]%mod-two[c]+mod+1)%mod; lef[rt]=rig[rt]=v*1ll*(two[c]-1)%mod; cnt[rt]=two[c]; } } inline void pushup(int rt) { sum[rt]=(sum[rt<<1]*1ll*cnt[rt<<1|1]+sum[rt<<1|1]*1ll*cnt[rt<<1]+lef[rt<<1]*1ll*rig[rt<<1|1])%mod; cnt[rt]=cnt[rt<<1]*1ll*cnt[rt<<1|1]%mod; lef[rt]=(lef[rt<<1]+lef[rt<<1|1]*1ll*cnt[rt<<1])%mod; rig[rt]=(rig[rt<<1|1]+rig[rt<<1]*1ll*cnt[rt<<1|1])%mod; } void build(int rt,int l,int r) { if (l==r) { re_new(rt,ls[r],b[r]); return; } int mid=(l+r)>>1; build(rt<<1,l,mid);build(rt<<1|1,mid+1,r); pushup(rt); } void upd(int rt,int l,int r,int pl) { if (l==r){re_new(rt,ls[r],b[r]);return;} int mid=(l+r)>>1; if (pl>mid) upd(rt<<1|1,mid+1,r,pl); else upd(rt<<1,l,mid,pl); pushup(rt); } int main() { two[0]=1; for (i=1;i<maxn;++i) two[i]=2*two[i-1]%mod; scanf("%d",&n); for (i=1;i<=n;++i) scanf("%d",&a[i]),ls[i]=a[i]; scanf("%d",&m); for (i=1;i<=m;++i) { scanf("%d%d",&pla[i],&chg[i]); ls[n+i]=chg[i]; } sort(ls+1,ls+n+m+1);tls=1; for (i=2;i<=n+m;++i) if (ls[i]^ls[tls]) ls[++tls]=ls[i]; for (i=1;i<=n;++i) { b[a[i]=lower_bound(ls+1,ls+tls+1,a[i])-ls]++; } build(1,1,tls); int mul=Pow(2,mod-1-n); printf("%lld\n",sum[1]*1ll*mul%mod); for (i=1;i<=m;++i) { chg[i]=lower_bound(ls+1,ls+tls+1,chg[i])-ls; --b[a[pla[i]]];upd(1,1,tls,a[pla[i]]); ++b[chg[i]];upd(1,1,tls,chg[i]); a[pla[i]]=chg[i]; printf("%lld\n",sum[1]*1ll*mul%mod); } return 0; }
cpp
1299
E
E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.In response, you will learn if the average of elements with indexes a1,a2,…,aka1,a2,…,ak is an integer. In other words, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,…,pk][p1,p2,…,pk] and [n+1−p1,n+1−p2,…,n+1−pk][n+1−p1,n+1−p2,…,n+1−pk] are indistinguishable. Therefore, you are guaranteed that p1≤n2p1≤n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2≤n≤8002≤n≤800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,…,aka1,a2,…,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1≤ai≤n1≤ai≤n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+⋯+pakkpa1+pa2+⋯+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2≤n≤8002≤n≤800, nn is even).In the next line output nn integers p1,p2,…,pnp1,p2,…,pn — the valid permutation of numbers from 11 to nn. p1≤n2p1≤n2 must hold.ExampleInputCopy2 1 2 OutputCopy? 1 2 ? 1 1 ! 1 2
[ "interactive", "math" ]
#include <cstdio> #include <vector> #include <iostream> using namespace std; const int M = 805; int read() { int x=0,f=1;char c; while((c=getchar())<'0' || c>'9') {if(c=='-') f=-1;} while(c>='0' && c<='9') {x=(x<<3)+(x<<1)+(c^48);c=getchar();} return x*f; } int n,p[M],id[M],rd[M]; int ask(vector<int> v) { printf("? %d",v.size()); for(int x:v) printf(" %d",x); puts("");fflush(stdout); return read(); } int qry(int x) { vector<int> v; for(int i=1;i<=n;i++) if(i!=x && !p[i]) v.push_back(i); return ask(v); } void get(int x,int a,int y,int b) { for(int i=1;i<=n;i++) { if(!p[i] && !id[x] && rd[i]==a) {if(qry(i)) id[x]=i;} else if(!p[i] && !id[y] && rd[i]==b) {if(qry(i)) id[y]=i;} } p[id[x]]=x;p[id[y]]=y; } signed main() { n=read();get(1,0,n,0); for(int t=2,l=2,r=n-1;l<=r;t<<=1) { //calc the remainder for(int i=1;i<=n;i++) if(!p[i]) { vector<int> v; for(int j=1;j<=t;j++) if(j%t!=rd[i]) v.push_back(id[j]); v.push_back(i); if(ask(v)) rd[i]+=t>>1; } while(l<=2*t && l<=r) get(l,l%t,r,r%t),l++,r--; } if(p[1]>n/2) for(int i=1;i<=n;i++) p[i]=n-p[i]+1; printf("!"); for(int i=1;i<=n;i++) printf(" %d",p[i]); puts("");fflush(stdout); }
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" ]
//Je Cruis En Moi #include <bits/stdc++.h> using namespace std; const int MAXN = 1e6+ 10; int a[MAXN], mn[MAXN],mx[MAXN]; int main () { int t; cin >> t; while (t --) { long long x, y, a, b; cin >> x >> y >> a >> b; if ((y - x) % (a + b) == 0) cout << (y - x) / (a + b) << endl; else cout << -1 << endl; } }
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<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=1e6+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[N]; int f[N]; void solve() { n=read(); scanf("%s",str+1); int a=0,b=0; int last=0; for(int i=1;i<=n;i++) { if(str[i]=='(') a++; else b++; if(str[i]=='(') last++; else last--; f[i]=last; } if(a!=b) printf("-1\n"); else { int ans=0; for(int i=1;i<=n;i++) { if(f[i]<0) { for(int j=i;j<=n;j++) { if(f[j]==0) { ans+=j-i+1; i=j; break; } } } } printf("%d\n",ans); } } int main() { // init(); // stin(); // scanf("%d",&T); T=1; while(T--) solve(); return 0; }
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" ]
# include <bits/stdc++.h> using namespace std; int n,ecnt,go[1000010],adj[500010],nxt[1000010],fa[500010],lg[250010],d[250010],bz[30][250010]; struct disjoint_set_union { struct node { int fa,sz;} f[250010]; void init_(int x) { for (int i=1;i<=x;i++) f[i].fa=i, f[i].sz=1; } int find_(int x) { return f[x].fa==x ? x : f[x].fa=find_(f[x].fa);} void merge_(int x,int y) { int l=find_(x),r=find_(y); if (l==r) return; if (f[l].sz<f[r].sz) swap(l,r); f[l].sz+=f[r].sz, f[r].fa=l; } } dsu; void add_(int u,int v) { go[++ecnt]=v, nxt[ecnt]=adj[u], adj[u]=ecnt;} void DFS_(int x) { d[x]=d[fa[x]]+1, bz[0][x]=fa[x]; for (int i=1;i<=lg[d[x]];i++) bz[i][x]=bz[i-1][bz[i-1][x]]; for (int i=adj[x];i;i=nxt[i]) if (go[i]!=fa[x]) fa[go[i]]=x, DFS_(go[i]); } int LCA_(int x,int y) { if (d[x]<d[y]) swap(x,y); int j=lg[d[x]]; while (d[x]>d[y]) { if (d[bz[j][x]]>=d[y]) x=bz[j][x]; j--; } if (x==y) return x; j=lg[d[x]]; while (j>=0) { if (bz[j][x]!=bz[j][y]) x=bz[j][x], y=bz[j][y]; j--; } return fa[x]; } void work_(int x,int y) { int k=LCA_(x,y); if (dsu.find_(k)!=dsu.find_(x)) { int op=x; for (int i=lg[n];i>=0;i--) if (dsu.find_(bz[i][op])==dsu.find_(op)) op=bz[i][op]; printf("%d %d %d %d\n",op,fa[op],x,y); dsu.merge_(op,fa[op]); } else { int op=y; for (int i=lg[n];i>=0;i--) if (d[bz[i][op]]>d[k]&&dsu.find_(bz[i][op])!=dsu.find_(k)) op=bz[i][op]; printf("%d %d %d %d\n",op,fa[op],x,y); dsu.merge_(op,fa[op]); } } void solve_(int x) { for (int i=adj[x];i;i=nxt[i]) if (go[i]!=fa[x]) fa[go[i]]=x, solve_(go[i]), work_(go[i]-n,x-n); } int main() { // freopen("in.in","r",stdin); // freopen("out.out","w",stdout); scanf("%d",&n); for (int u,v,i=1;i<n;i++) scanf("%d%d",&u,&v), add_(u,v), add_(v,u); for (int u,v,i=1;i<n;i++) scanf("%d%d",&u,&v), add_(u+n,v+n), add_(v+n,u+n); for (int i=2;i<=n;i++) lg[i]=lg[i/2]+1; DFS_(1); dsu.init_(n); printf("%d\n",n-1); solve_(n+1); 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" ]
#include <bits/stdc++.h> using namespace std; #define A first #define B second #define MP make_pair #define ms(a, x) memset(a, x, sizeof(a)) #define boost() ios_base::sync_with_stdio(false); cin.tie(); cout.tie() typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<long long, long long> pll; typedef pair<long double, long double> pld; const int INF = 0x3f3f3f3f; const ll LLINF = 0x3f3f3f3f3f3f3f3f; const double PI = acos(-1); const int mxN=1e4+5; int main(){ boost(); int t; cin >> t; while(t--){ int n; cin >> n; vector <int> v(n); for(int i=0; i<n; i++) cin >> v[i]; if(n >= 2){ int odd=-1; bool found=false; for(int i=0; i<n; i++){ if(v[i]%2 == 0){ cout << 1 << '\n' << i+1; found=true; break; } if(odd == -1){ odd=i+1; } else{ cout << 2 << '\n' << odd << " " << i+1; found=true; break; } } if(!found) cout << -1; } else{ if(v[0] % 2 == 0){ cout << 1 << '\n' << 1; } else cout << -1; } cout << '\n'; } }
cpp
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
#include "bits/stdc++.h" #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") // #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template<typename T> // pbds using pbds = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // using ll = long long; using ld = long double; typedef complex<ld> cd; // typedef pair<int, int> pi; typedef pair<ll,ll> pl; typedef pair<ld,ld> pd; // typedef vector<int> vi; typedef vector<ld> vd; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<cd> vcd; // template<class T> using pq = priority_queue<T>; template<class T> using pqg = priority_queue<T, vector<T>, greater<T>>; // #define FOR(i, a, b) for (ll i=a; i<(b); i++) #define F0R(i, a) for (ll i=0; i<(a); i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define trav(a,x) for (auto& a : x) #define uid(a, b) uniform_int_distribution<int>(a, b)(rng) #define sumv(x) accumulate(x.begin(), x.end(), 1LL*0) #define yes cout << "YES" << endl #define no cout<<"NO"<<endl // #define sz(x) (int)(x).size() #define mp make_pair #define pb push_back #define eb emplace_back #define fi first #define se second #define lb lower_bound #define ub upper_bound #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define ins insert #define Unique(X) (X).erase(unique(all(X)),(X).end()) // template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} // template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << "}\n";} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifdef DEBUG #define dbg(x...) cerr << "\e[91m"<<__func__<<":"<<__LINE__<<" [" << #x << "] = ["; _print(x); cerr << "\e[39m" << endl; #else #define dbg(x...) #endif // const ll MOD = 1e9 + 7; const ll mod = 998244353; const char nl = '\n'; const int MX = 1e5 + 1; const ll c = 5*(1e5 + 1); const ll INF = 1000000000000000000; const ll inf = 1000000000; const ll eps = 1e-9; void solve(int test){ ll n, m ; cin >> n >> m; vector <string> v(n); map <string , ll> mm; for(ll i = 0; i < n; ++i){ cin >> v[i]; mm[v[i]]++; } dbg(mm); vector<string> L , R; string middle; for(ll i = 0; i < n; ++i){ string curr = v[i]; reverse(all(curr)); if(curr == v[i]){ middle = curr; } else if(mm.find(curr) != mm.end()){ L.pb(v[i]); R.pb(curr); mm.erase(v[i]); mm.erase(curr); } } cout << sz(L) * 2 * m + sz(middle) << nl; for(auto i : L) cout << i; cout << middle; reverse(all(R)); for(auto i : R) cout << i; cout << nl; } bool test_case = 0; int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); clock_t start = clock(); cout << fixed << setprecision(15); ll t = 1; if(test_case){ cin >> t; } for(ll i = 1; i <= t; ++i){ solve(1); } clock_t end = clock(); double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cerr << "Time : " << fixed << time_taken << setprecision(5); cerr << " sec" << nl; }
cpp
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#include<bits/stdc++.h> using namespace std; #define OM_NAMAH_SHIVAY ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) #define F first #define S second #define int long long #define pb push_back void solve(){ int n;cin>>n; string s;cin>>s; string temp=""; string ansst=s; int ans=-1; for(int k=0;k<s.size();k++){ temp=""; for(int j=k;j<s.size();j++){ temp.pb(s[j]); } int x= s.size()-k; if (x%2==0) { for (int i = 0; i <k; ++i) { temp.pb(s[i]); } } else{ for (int i = k-1; i >=0; --i) { temp.pb(s[i]); } } if(temp<ansst){ ansst=temp; ans=k+1; } } if (ans==-1) { cout<<s<<endl; cout<<1<<endl;return; } cout<<ansst<<endl; cout<<ans<<endl;return; } int32_t main() { OM_NAMAH_SHIVAY; int t; t=1; cin>>t; // cout<<"t not found"<<endl; while(t--){ solve(); } // #ifdef LOCAL_DEFINE cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; // #endif return 0; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int m= 998244353; ll mod (ll x){ return ((x%m+m)%m); } ll add(ll a , ll b){ return mod(mod(a)+mod(b)); } ll mul(ll a, ll b){ return mod(mod(a)*mod(b)); } int main(){ int t; cin>>t; while(t--){ ll n,m; cin>>n>>m; ll zeroes= n-m; ll t= m+1; ll ingrp1= zeroes/t; ll ingrp2= zeroes % t; ll in2= ingrp1+1; ll countingrp1= (t-ingrp2)*(ingrp1*(ingrp1+1))/2; ll countingrp2= (ingrp2)*(in2*(in2+1))/2; cout<< (n*(n+1))/2 - (countingrp1+countingrp2)<<endl; } }
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
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 <bits/stdc++.h> #pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #pragma GCC optimize("Ofast")//Comment optimisations for interactive problems (use endl) #pragma GCC target("avx,avx2,fma") #pragma GCC optimization ("unroll-loops") using namespace std; struct PairHash {inline std::size_t operator()(const std::pair<int, int> &v) const { return v.first * 31 + v.second; }}; // speed #define Code ios_base::sync_with_stdio(false); #define By ios::sync_with_stdio(0); #define Sumfi cout.tie(NULL); // alias using ll = long long; using ld = long double; using ull = unsigned long long; // constants const ld PI = 3.14159265358979323846; /* pi */ const ll INF = 1e18; const ld EPS = 1e-9; const ll MAX_N = 202020; const ll mod = 998244353; // typedef typedef pair<ll, ll> pll; typedef vector<pll> vpll; typedef array<ll,3> all3; typedef array<ll,4> all4; typedef array<ll,5> all5; typedef vector<all3> vall3; typedef vector<all4> vall4; typedef vector<all5> vall5; typedef pair<ld, ld> pld; typedef vector<pld> vpld; typedef vector<ld> vld; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<vll> vvll; typedef vector<int> vi; typedef vector<bool> vb; typedef deque<ll> dqll; typedef deque<pll> dqpll; typedef pair<string, string> pss; typedef vector<pss> vpss; typedef vector<string> vs; typedef vector<vs> vvs; typedef unordered_set<ll> usll; typedef unordered_set<pll, PairHash> uspll; typedef unordered_map<ll, ll> umll; typedef unordered_map<pll, ll, PairHash> umpll; // macros #define rep(i,m,n) for(ll i=m;i<n;i++) #define rrep(i,m,n) for(ll i=n;i>=m;i--) #define all(a) begin(a), end(a) #define rall(a) rbegin(a), rend(a) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) #define INF(a) memset(a,0x3f3f3f3f3f3f3f3fLL,sizeof(a)) #define ASCEND(a) iota(all(a),0) #define sz(x) ll((x).size()) #define BIT(a,i) (a & (1ll<<i)) #define BITSHIFT(a,i,n) (((a<<i) & ((1ll<<n) - 1)) | (a>>(n-i))) #define pyes cout<<"YES\n"; #define pno cout<<"NO\n"; #define endl "\n" #define pneg1 cout<<"-1\n"; #define ppossible cout<<"Possible\n"; #define pimpossible cout<<"Impossible\n"; #define TC(x) cout<<"Case #"<<x<<": "; #define X first #define Y second // utility functions template <typename T> void print(T &&t) { cout << t << "\n"; } template<typename T> void printv(vector<T>v){ll n=v.size();rep(i,0,n){cout<<v[i];if(i+1!=n)cout<<' ';}cout<<endl;} template<typename T> void printvv(vector<vector<T>>v){ll n=v.size();rep(i,0,n)printv(v[i]);} template<typename T> void printvln(vector<T>v){ll n=v.size();rep(i,0,n)cout<<v[i]<<endl;} void fileIO(string in = "input.txt", string out = "output.txt") {freopen(in.c_str(),"r",stdin); freopen(out.c_str(),"w",stdout);} void readf() {freopen("", "rt", stdin);} template <typename... T> void in(T &...a) { ((cin >> a), ...); } template<typename T> void readv(vector<T>& v){rep(i,0,sz(v)) cin>>v[i];} template<typename T, typename U> void readp(pair<T,U>& A) {cin>>A.first>>A.second;} template<typename T, typename U> void readvp(vector<pair<T,U>>& A) {rep(i,0,sz(A)) readp(A[i]); } void readvall3(vall3& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2];} void readvall5(vall5& A) {rep(i,0,sz(A)) cin>>A[i][0]>>A[i][1]>>A[i][2]>>A[i][3]>>A[i][4];} void readvvll(vvll& A) {rep(i,0,sz(A)) readv(A[i]);} struct Combination { vll fac, inv; ll n, MOD; ll modpow(ll n, ll x, ll MOD = mod) { if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; } Combination(ll _n, ll MOD = mod): n(_n + 1), MOD(MOD) { inv = fac = vll(n,1); rep(i,1,n) fac[i] = fac[i-1] * i % MOD; inv[n - 1] = modpow(fac[n - 1], MOD - 2, MOD); rrep(i,1,n - 2) inv[i] = inv[i + 1] * (i + 1) % MOD; } ll fact(ll n) {return fac[n];} ll nCr(ll n, ll r) { if(n < r or n < 0 or r < 0) return 0; return fac[n] * inv[r] % MOD * inv[n-r] % MOD; } }; struct Matrix { ll r,c; vvll matrix; Matrix(ll r, ll c, ll v = 0): r(r), c(c), matrix(vvll(r,vll(c,v))) {} Matrix(vvll m) : r(sz(m)), c(sz(m[0])), matrix(m) {} Matrix operator*(const Matrix& B) const { Matrix res(r, B.c); rep(i,0,r) rep(j,0,B.c) rep(k,0,B.r) { res.matrix[i][j] = (res.matrix[i][j] + matrix[i][k] * B.matrix[k][j] % mod) % mod; } return res; } Matrix copy() { Matrix copy(r,c); copy.matrix = matrix; return copy; } ll get(ll y, ll x) { return matrix[y][x]; } Matrix pow(ll n) { assert(r == c); Matrix res(r,r); Matrix now = copy(); rep(i,0,r) res.matrix[i][i] = 1; while(n) { if(n & 1) res = res * now; now = now * now; n /= 2; } return res; } }; // geometry data structures template <typename T> struct Point { T y,x; Point(T y, T x) : y(y), x(x) {} Point(pair<T,T> p) : y(p.first), x(p.second) {} Point() {} void input() {cin>>y>>x;} friend ostream& operator<<(ostream& os, const Point<T>& p) { os<<p.y<<' '<<p.x<<'\n'; return os;} Point<T> operator+(Point<T>& p) {return Point<T>(y + p.y, x + p.x);} Point<T> operator-(Point<T>& p) {return Point<T>(y - p.y, x - p.x);} Point<T> operator*(ll n) {return Point<T>(y*n,x*n); } Point<T> operator/(ll n) {return Point<T>(y/n,x/n); } bool operator<(const Point &other) const {if (x == other.x) return y < other.y;return x < other.x;} Point<T> rotate(Point<T> center, ld angle) { ld si = sin(angle * PI / 180.), co = cos(angle * PI / 180.); ld y = this->y - center.y; ld x = this->x - center.x; return Point<T>(y * co - x * si + center.y, y * si + x * co + center.x); } ld distance(Point<T> other) { T dy = abs(this->y - other.y); T dx = abs(this->x - other.x); return sqrt(dy * dy + dx * dx); } T norm() { return x * x + y * y; } }; template<typename T> struct Line { Point<T> A, B; Line(Point<T> A, Point<T> B) : A(A), B(B) {} Line() {} void input() { A = Point<T>(); B = Point<T>(); A.input(); B.input(); } T ccw(Point<T> &a, Point<T> &b, Point<T> &c) { T res = a.x * b.y + b.x * c.y + c.x * a.y; res -= (a.x * c.y + b.x * a.y + c.x * b.y); return res; } bool isIntersect(Line<T> o) { T p1p2 = ccw(A,B,o.A) * ccw(A,B,o.B); T p3p4 = ccw(o.A,o.B,A) * ccw(o.A,o.B,B); if (p1p2 == 0 && p3p4 == 0) { pair<T,T> p1(A.y, A.x), p2(B.y,B.x), p3(o.A.y, o.A.x), p4(o.B.y, o.B.x); if (p1 > p2) swap(p2, p1); if (p3 > p4) swap(p3, p4); return p3 <= p2 && p1 <= p4; } return p1p2 <= 0 && p3p4 <= 0; } pair<bool,Point<ld>> intersection(Line<T> o) { if(!this->intersection(o)) return {false, {}}; ld det = 1. * (o.B.y-o.A.y)*(B.x-A.x) - 1.*(o.B.x-o.A.x)*(B.y-A.y); ld t = ((o.B.x-o.A.x)*(A.y-o.A.y) - (o.B.y-o.A.y)*(A.x-o.A.x)) / det; return {true, {A.y + 1. * t * (B.y - A.y), B.x + 1. * t * (B.x - A.x)}}; } //@formula for : y = ax + fl //@return {a,fl}; pair<ld, ld> formula() { T y1 = A.y, y2 = B.y; T x1 = A.x, x2 = B.x; if(y1 == y2) return {1e9, 0}; if(x1 == x2) return {0, 1e9}; ld a = 1. * (y2 - y1) / (x2 - x1); ld b = -x1 * a + y1; return {a, b}; } }; template<typename T> struct Circle { Point<T> center; T radius; Circle(T y, T x, T radius) : center(Point<T>(y,x)), radius(radius) {} Circle(Point<T> center, T radius) : center(center), radius(radius) {} Circle() {} void input() { center = Point<T>(); center.input(); cin>>radius; } bool circumference(Point<T> p) { return (center.x - p.x) * (center.x - p.x) + (center.y - p.y) * (center.y - p.y) == radius * radius; } bool intersect(Circle<T> c) { T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y); return (radius - c.radius) * (radius - c.radius) <= d and d <= (radius + c.radius) * (radius + c.radius); } bool include(Circle<T> c) { T d = (center.x - c.center.x) * (center.x - c.center.x) + (center.y - c.center.y) * (center.y - c.center.y); return d <= radius * radius; } }; ll __gcd(ll x, ll y) { return !y ? x : __gcd(y, x % y); } all3 __exgcd(ll x, ll y) { if(!y) return {x,1,0}; auto [g,x1,y1] = __exgcd(y, x % y); return {g, y1, x1 - (x/y) * y1}; } ll __lcm(ll x, ll y) { return x / __gcd(x,y) * y; } ll modpow(ll n, ll x, ll MOD = mod) { if(x < 0) return modpow(modpow(n,-x,MOD),MOD-2,MOD); n%=MOD; if(!x) return 1; ll res = modpow(n,x>>1,MOD); res = (res * res) % MOD; if(x&1) res = (res * n) % MOD; return res; } ll solve(ll k, vll A) { vll psum{0}; rep(i,0,sz(A)) psum.push_back(psum.back() + A[i]); ll mi = *min_element(all(psum)); if(mi >= 0) return -1; if(psum.back() >= 0 and -mi < k) return -1; if(-mi >= k) { rep(i,1,sz(psum)) { if(-psum[i] >= k) return i; } return -1; } ll cyc = max(0ll,(k + mi) / -psum.back() - 1); ll res = sz(A) * cyc; k += psum.back() * cyc; rep(_,0,10) { rep(i,0,sz(A)) { if(k <= 0) return res; res += 1; k += A[i]; } if(k <= 0) return res; } return -1; } int main() { Code By Sumfi cout.precision(12); ll tc = 1; //in(tc); rep(i,1,tc+1) { ll k,n; in(k,n); vll A(n); readv(A); print(solve(k,A)); } return 0; }
cpp
1286
F
F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3 1 10 100 OutputCopy3 InputCopy3 5 3 -2 OutputCopy2 InputCopy1 0 OutputCopy0 NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
#include <cstdio> #include <map> #include <iostream> #include <set> #include <algorithm> #include <unordered_map> #include <bitset> #include <queue> #include <stack> #include <random> #include <cstring> #include <ctime> #include <cmath> #include <assert.h> using namespace std; #define LL long long #define pp pair<int,int> #define mp make_pair #define ull unsigned long long namespace IO{ const int sz=1<<22; char a[sz+5],b[sz+5],*p1=a,*p2=a,*t=b,p[105]; inline char gc(){ // return p1==p2?(p2=(p1=a)+fread(a,1,sz,stdin),p1==p2?EOF:*p1++):*p1++; return getchar(); } template<class T> void gi(T& x){ x=0; int f=1;char c=gc(); if(c=='-')f=-1; for(;c<'0'||c>'9';c=gc())if(c=='-')f=-1; for(;c>='0'&&c<='9';c=gc()) x=x*10+(c-'0'); x=x*f; } inline void flush(){fwrite(b,1,t-b,stdout),t=b; } inline void pc(char x){*t++=x; if(t-b==sz) flush(); } template<class T> void pi(T x,char c='\n'){ if(x<0)pc('-'),x=-x; if(x==0) pc('0'); int t=0; for(;x;x/=10) p[++t]=x%10+'0'; for(;t;--t) pc(p[t]); pc(c); } struct F{~F(){flush();}}f; } using IO::gi; using IO::pi; using IO::pc; const int mod=998244353; inline int add(int x,int y){return x+y>=mod?x+y-mod:x+y;} inline int dec(int x,int y){return x-y<0?x-y+mod:x-y;} inline int mul(int x,int y){return 1ll*x*y%mod;} inline int qkpow(int a,int b){ int ans=1,base=a%mod; while(b){ if(b&1)ans=1ll*ans*base%mod; base=1ll*base*base%mod; b>>=1; } return ans; } int n,f[(1<<20)+5],sz[(1<<20)+5],f2[(1<<20)+5]; LL a[25],sum[(1<<20)+5]; signed main(){ gi(n); for(int i=0;i<n;i++){ gi(a[i]); if(!a[i])i--,n--; } for(int i=0;i<(1<<n);i++){ int cnt=0; for(int j=0;j<n;j++)if((1<<j)&i)sz[i]++,sum[i]+=a[j],cnt+=(a[j]!=0); } for(int i=1;i<(1<<n);i++){ for(int S=(i&(i-1));S;S=(S-1)&i){ LL s=abs(sum[S]-sum[i^S]); if(s<sz[i]&&(sz[i]&1)!=(s&1)){ f2[i]=1; break; } } } int all=(1<<n)-1; for(int s=1;s<(1<<n);s++){ if(!f[s]&&f2[s]){ f[s]=1; int sta=all^s; for(int t=sta;t;t=(t-1)&sta) f[s|t]=max(f[s|t],f[t]+1); } } printf("%d\n",n-f[(1<<n)-1]); 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<bits/stdc++.h> using namespace std; #define w(t) int t;cin >> t; while(t--) #define ll long long #define get_arr(x,o,n) for(int i=o;i<n;i++){cin >> x[i];} #define fr(i,x,y) for(int i=x;i<y;i++) #define fr_rev(i,x,y) for(int i=x;i>y;i--) #define sz(x) x.size() #define sp " " #define vsort(v) sort(v.begin(),v.end()) #define vsort_rev(v) sort(v.begin(),v.end(), greater<int>()) #define pb push_back #define vi vector<int> #define br cout << endl; #define prints(v) for(auto u:v)cout << u << sp; #define print(v) for(auto u:v)cout << u ; #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)); bool compare(int a ,int b) { return a > b ? true : false; } void solve(){ } int main(int argc, char const *argv[]) { fastread() w(t) { int a,b; cin >> a>> b; if(a%b==0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } }
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; int main() { int t; std::cin >> t ; int x; int y; int a; int b; while (t--){ cin >> x >> y>> a>> b; int i = y - x ; int j = a + b ; if ( i % j == 0){ cout << i / j << "\n" ; } else { cout << "-1" << '\n' ; } } return 0; }
cpp
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; #define ll long long vector<bool> primes; void seive(int n){ primes.resize(n+1, true); primes[0] = false; primes[1] = false; for(int i=2; i*i<=n; i++){ if(primes[i]){ for(int j=i*i; j<=n; j+=i) primes[j] = false; } } } ll kadane(vector<ll> &vec, ll start, ll end) { //largest sum of contiguous subarray ll currSum = 0, maxSum = INT_MIN; for(ll i = start; i < end; i++) { currSum += vec[i]; if(currSum < 0) currSum = 0; maxSum = max(maxSum, currSum); } return maxSum; } void solve(){ ll n; cin>>n; ll i = 0; vector<ll> a(n); while(i < n) cin>>a[i++]; if(n == 1) {cout<<"Yes\n"; return;} ll l = n-1, r = 0; for(i=0; i<n; i++) { if(a[i] <= i-1) {l = i-1; break;} } for(i=n-1; i>=0; i--) { if(a[i] <= n-i-2) {r = i+1; break;} } if(l >= r) cout<<"Yes\n"; else cout<<"No\n"; } int main(){ ll t; cin>>t; while(t--){ solve(); } }
cpp
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; template<class t> using vc=vector<t>; template<class t> using vvc=vc<vc<t>>; using vi = vc<int>; using vl = vc<ll>; using vvi = vc<vi>; using vvl = vc<vl>; using pii = pair<int, int>; using pll = pair<ll, ll>; #define inf 0x3f3f3f3f #define llinf 0x3f3f3f3f3f3f3f3f #define ALL(x) (x).begin(),(x).end() #define rALL(x) (x).rbegin(),(x).rend() #define rev(x) reverse(ALL(x)) #define srt(x) sort(ALL(x)) #define rsrt(x) sort(rALL(x)) #define rb(_, l, r) for(int _= l; _ <= r; ++_) #define rep(_, l, r) for(int _ = l; _ < r; ++_) #define br(_, r, l) for(int _ = r; _ >= l; _--) #define sz(x) (int)(x.size()) template<class t,class u> bool chmax(t&a,u b){if(a<b){a=b;return true;}else return false;} template<class t,class u> bool chmin(t&a,u b){if(b<a){a=b;return true;}else return false;} template<typename T> void in(vector<T>&a) {for(auto& e: a) cin>> e;} mt19937_64 rng((unsigned int) chrono::steady_clock::now().time_since_epoch().count()); void p(int x) { if (x) cout << "YES" << '\n'; else cout << "NO" << '\n'; } template<class t> void printv(t x, char delimiter = ',', bool needBrace = true) { needBrace && cout << "{"; for(auto it = x.begin(); it != x.end(); ) { cout << *it; it = next(it); if (it != x.end()) { cout << delimiter; } else { needBrace && cout << "}"; } } cout << "\n"; } #define TEST #ifdef TEST #define pr(...) printf(__VA_ARGS__); #define db(x, ...) debug##x(__VA_ARGS__) #define ldb(parm...) do {cout << "Line:" << __LINE__ << " "; db(parm);} while(0) #define debugv(v...) do {printv(v);} while(0) #define debug1(a) cout << #a << " = " << a << ' '; #define debug2(a,b) do {debug1(a); debug1(b); cout << '\n';} while(0) #define debug3(a,b,c) do {debug1(a); debug2(b, c);} while(0) #define debug4(a,b,c,d) do {debug1(a); debug3(b, c, d);} while(0) #else #define db(...) "Your attitude towards suffering is the melody of life."; #endif /* str -> str.c_str() db(v, a) -> printv() db(1, x) -> print x db(2, x, y) -> print x, y */ const char nl = '\n'; #define SINGLE void solve() { int n; cin >> n; vi a(n); map<int, vc<pii>> mp; rep (i, 0, n) { cin >> a[i]; int cur = 0; br (j, i, 0) { cur += a[j]; mp[cur].push_back({j + 1, i + 1}); } } int mxv = -1, mx = 0; for (auto&[k, v]: mp) { int m = sz(v), cur = 1, pre = v[0].second; rep (i, 1, m) { if (v[i].first > pre) { cur ++; pre = v[i].second; } } if (chmax(mx, cur)) mxv = k; } auto v = mp[mxv]; cout << mx << nl; auto [l, r] = v.front(); cout << l << ' ' << r << nl; int m = sz(v), cur = 1, pre = v[0].second; rep (i, 1, m) { if (v[i].first > pre) { cout << v[i].first << ' ' << v[i].second << nl; pre = v[i].second; } } } int main() { ios::sync_with_stdio(0);cin.tie(0); #ifdef SINGLE solve(); #else int T; cin >> T; while (T--) solve(); #endif return 0; }
cpp
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; #define N 200001 #define ll long long int main(){ ll n; cin>>n; double x=0.0; while(n>0){ x+=(double)1/n; n--; } cout<<setprecision(12)<<x<<endl; return 0; }
cpp
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n,m,p; cin>>n>>m>>p; vector<int> a(n); vector<int> b(m); for(int i = 0; i<n; i++){ cin>>a[i]; } for(int i = 0; i<m; i++){ cin>>b[i]; } int f1 = 0; for(int i = 0; i<min(n,m); i++){ if(a[i]%p !=0){ f1 = i; break; } if(b[i]%p != 0){ f1 = i; break; } } if(b[f1]%p != 0 && a[f1]%p != 0){ cout<<2*f1<<endl; } else{ if(a[f1]%p != 0){ for(int i = f1+1; i<m; i++){ if(b[i]%p != 0){ cout<<f1+i<<endl; break; } } } else{ for(int i = f1+1; i<n; i++){ if(a[i]%p != 0){ cout<<f1+i<<endl; break; } } } } }
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" ]
#include <bits/stdc++.h> #define SP putchar(' ') #define EL putchar('\n') #define File(a) freopen(a ".in", "r", stdin), freopen(a ".out", "w", stdout) template <typename T> void read(T &); template <typename T> void write(const T &); const int N = 250005; namespace DSU { int find(int x); void merge(int x, int y); int mnd[N]; int fa[N]; } // namespace DSU int LCA(int u, int v); int anck(int u, int k); void dfs(int u); int fa[N][20], dep[N]; int que[N], qh, qt, fa2[N]; bool inq[N]; std::vector<int> G1[N], G2[N]; int n; int main() { read(n); for (int i = 1; i < n; ++i) { int u, v; read(u), read(v); G1[u].push_back(v), G1[v].push_back(u); } for (int i = 1; i < n; ++i) { int u, v; read(u), read(v); G2[u].push_back(v), G2[v].push_back(u); } dfs(1); que[qh = qt = 0] = 1; while (qh <= qt) { int u = que[qh++]; inq[u] = true; for (int v : G2[u]) { if (inq[v]) continue; fa2[v] = u; que[++qt] = v; } } for (int i = 1; i <= n; ++i) DSU::fa[i] = i, DSU::mnd[i] = dep[i]; std::reverse(que + 1, que + n); write(n - 1), EL; for (int i = 1; i < n; ++i) { int u = que[i], v = fa2[u]; int L = LCA(u, v); int fu = DSU::find(u); int x; if (DSU::mnd[fu] > dep[L]) { x = anck(u, dep[u] - DSU::mnd[fu]); } else { x = v; for (int i = 18; i >= 0; --i) { if (dep[x] - (1 << i) >= dep[L] && DSU::find(fa[x][i]) != fu) x = fa[x][i]; } } DSU::merge(x, fa[x][0]); write(x), SP, write(fa[x][0]), SP, write(u), SP, write(v), EL; } return 0; } int LCA(int u, int v) { if (dep[u] < dep[v]) std::swap(u, v); u = anck(u, dep[u] - dep[v]); if (u == v) return u; for (int i = 18; i >= 0; --i) { if (fa[u][i] != fa[v][i]) { u = fa[u][i], v = fa[v][i]; } } return fa[u][0]; } int anck(int u, int k) { for (int i = 0; i < 19; ++i) { if (k >> i & 1) u = fa[u][i]; } return u; } void dfs(int u) { for (int i = 1; i <= 18; ++i) fa[u][i] = fa[fa[u][i - 1]][i - 1]; for (int v : G1[u]) { if (v == fa[u][0]) continue; fa[v][0] = u; dep[v] = dep[u] + 1; dfs(v); } } namespace DSU { int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } void merge(int x, int y) { int fx = find(x), fy = find(y); if (fx != fy) { fa[fx] = fy; mnd[fy] = std::min(mnd[fy], mnd[fx]); } } } // namespace DSU template <typename T> void read(T &Re) { T k = 0; char ch = getchar(); int flag = 1; while (!isdigit(ch)) { if (ch == '-') flag = -1; ch = getchar(); } while (isdigit(ch)) k = k * 10 + ch - '0', ch = getchar(); Re = flag * k; } template <typename T> void write(const T &Wr) { if (Wr < 0) putchar('-'), write(-Wr); else if (Wr < 10) putchar(Wr + '0'); else write(Wr / 10), putchar((Wr % 10) + '0'); }
cpp
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
#include <iostream> #include <ranges> #include <algorithm> #include <numeric> #include <vector> #include <array> #include <set> #include <map> #include <bit> #include <sstream> #include <list> #include <stack> #include <queue> #include <cmath> typedef long long integerType; typedef integerType z; typedef std::vector<integerType> v; typedef std::vector<v> V; typedef std::set<integerType> s; typedef std::multiset<integerType> S; typedef std::string r; typedef std::vector<r> R; typedef std::vector<bool> b; struct RHEXAOCrocks { RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); } template<class T> operator T() const { T n; std::cin >> n; return n; } std::string operator()() { std::string s; std::cin >> s; return s; } v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; } R operator()(integerType n, char del) { R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c; for (integerType i{}; i < n;++i) while ((c = std::cin.get()) != del) vec[i].push_back(c); return vec; } V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; } template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; } RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) { for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) { for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this; } }o; #define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__) #define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__) #define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__) #define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__) #define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A) #define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B) #define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C) #define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D) #define z(a) (integerType)((a).size()) #define ff(...) auto f = [&](__VA_ARGS__, const auto& f) #define f(...) f(__VA_ARGS__, f) #define gg(...) auto g = [&](__VA_ARGS__, const auto& g) #define g(...) g(__VA_ARGS__, g) #define hh(...) auto h = [&](__VA_ARGS__, const auto& h) #define h(...) h(__VA_ARGS__, h) using namespace std; namespace ra = ranges; inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); } inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); } z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; } #define w(...) if(__VA_ARGS__) #define _ else #define W(...) while(__VA_ARGS__) #define A(...) for(auto __VA_ARGS__) #define O while(true) void solve_test_case() { z q{ o }, x{ o }, need{}, mex{}; v c(x); i(0, q) { z e{ o }; ++c[e % x]; while (c[need]) { --c[need]; ++mex; need = mex % x; } o[mex]['\n']; } } int main() { z t{ 1 }; while (t--) solve_test_case(); }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vb = vector<bool>; using vll = vector<ll>; using vs = vector<string>; #define ALL(v) v.begin(), v.end() #define SORT(v) sort(ALL(v)) #define SZ(v) int(v.size()) #ifdef DLOCAL #include <local.h> #else #define deb(...); #endif void solve() { int n; cin >> n; string s; cin >> s; vi count(26); for (int i = 0; i < n; ++i) { count[s[i] - 'a']++; } int pos = 0; vector<pii> indexes(26); // start, end for (int i = 0; i < 26; ++i) { indexes[i].first = pos; pos += count[i]; indexes[i].second = pos; } deb(count); for (int i = 0; i < 26; ++i) { if (indexes[i].first == indexes[i].second) continue; char c = char('a' + i); deb(c, indexes[i]) } vi ans; vi positions(27, 0); map<char, int> temp; for (int i = 0; i < n; ++i) { if (temp.upper_bound(s[i]) != temp.end()) { positions[s[i] - 'a'] = *max_element(positions.begin() + (s[i] - 'a') + 1, positions.end()) + 1; ans.emplace_back(positions[s[i] - 'a']); } else { positions[s[i] - 'a'] = 1; ans.emplace_back(positions[s[i] - 'a']); } temp[s[i]]++; } deb(positions) deb(ans); cout << *max_element(ALL(ans)) << "\n"; for (int i = 0; i < n; ++i) { cout << ans[i] << " "; } } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin ("puzzle_name.in"); //ofstream cout ("puzzle_name.out"); solve(); return 0; }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
// clang-format off #include<bits/stdc++.h> using namespace std; #ifdef LOCAL #include "deb/debug.h" #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif #define int long long typedef unsigned long long ull; typedef long double ld; #define ff first #define ss second const int MOD = 1e9 + 7; int sum(int a, int b) { return (a + b) % MOD; } void solve() { int n, m; cin >> n >> m; vector< vector<int> > dpp(m, vector<int>(n + 1)); for (int j = 1; j <= n; j++) dpp[0][j] = 1; for (int i = 1; i < m; i++) { for (int j = 1; j <= n; j++) { dpp[i][j] = sum(dpp[i][j - 1], dpp[i - 1][j]); } } vector< vector< vector<int> > > dp(m + 1, vector< vector<int> >(n + 1, vector<int>(n + 1, 0))); for (int i = 1; i <= n; i++) dp[m][i][i] = dpp[m - 1][i]; for (int s = 1; s <= n; s++) { for (int i = m - 1; i >= 0; i--) { for (int j = s; j <= n; j++) { dp[i][j][s] = sum(dp[i][j - 1][s], dp[i + 1][j][s]); } } } int ans = 0; for (int k = 1; k <= n; k++) { for (int j = k; j <= n; j++) ans = sum(ans, dp[0][j][k]); } cout << ans << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int _ = 1; // cin >> _; for (;_; --_) { solve(); } return 0; }
cpp
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
#include<bits/stdc++.h> #pragma GCC optimize("Ofast", "inline", "-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") using namespace std; int const lim=(1<<18)-1;long long res; int i,j,n,x,u,v,f[lim+5],cnt[lim+5]; int read(){ int x=0;char ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar(); return x; } int find(int x){return f[x]==x?x:f[x]=find(f[x]);} signed main(){ n=read();cnt[0]=1; for (i=1;i<=n;i++) cnt[x=read()]++,res-=x; for (i=0;i<=lim;i++) f[i]=i; for (i=lim;~i;i--) for (j=i;j;j=(j-1)&i) if (cnt[j]&&cnt[i^j]){ u=find(j);v=find(i^j); if (u==v) continue; res+=1ll*i*(cnt[u]+cnt[v]-1); f[u]=v;cnt[v]=1; } printf("%lld\n",res); return 0; }
cpp
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES
[ "geometry", "implementation" ]
#include <bits/stdc++.h> #define int long long using namespace std; struct point{ int x,y; }; struct line{ point p1,p2; }a[4]; int len_line_pow(line a){//求线段长度的平方 return (a.p1.x-a.p2.x)*(a.p1.x-a.p2.x)+(a.p1.y-a.p2.y)*(a.p1.y-a.p2.y); } bool check_same_point(point p1,point p2){//判断两点是否相同 return p1.x==p2.x&&p1.y==p2.y; } bool check_one_line(line a,point p){//判断三点共线 return (a.p1.y-p.y)*(a.p2.x-p.x)==(a.p2.y-p.y)*(a.p1.x-p.x); } bool check_5_point(line a,point p){//判断p是不是在a的1/5点和4/5线之间 a.p1.x*=5,a.p2.x*=5,a.p1.y*=5,a.p2.y*=5; p.x*=5,p.y*=5; point p1={a.p1.x+(a.p2.x-a.p1.x)/5,a.p1.y+(a.p2.y-a.p1.y)/5}; point p4={a.p1.x+(a.p2.x-a.p1.x)/5*4,a.p1.y+(a.p2.y-a.p1.y)/5*4}; double d=sqrt((double)len_line_pow({p1,p4})); double d1=sqrt((double)len_line_pow({p,p1})); double d4=sqrt((double)len_line_pow({p,p4})); return fabs(d-d1-d4)<1e-3; } bool check(line l,line r,line m){ //条件1:两线有唯一共同端点 int x=check_same_point(l.p1,r.p1); if(check_same_point(l.p1,r.p2)){ x++; swap(r.p1,r.p2); } if(check_same_point(l.p2,r.p1)){ x++; swap(l.p1,l.p2); } if(check_same_point(l.p2,r.p2)){ x++; swap(l.p1,l.p2); swap(r.p1,r.p2); } if(x!=1){ return false; } //条件2:夹角不是钝角,可以是直角 if(len_line_pow(l)+len_line_pow(r)<len_line_pow({l.p2,r.p2})){ return false; } //条件3:第3线两端点与前两线共线 if(check_one_line(l,m.p1)&&check_one_line(r,m.p2)){ ; }else if(check_one_line(l,m.p2)&&check_one_line(r,m.p1)){ swap(m.p1,m.p2); }else{ return false; } //条件4:第3线两端点必须在两线分别的1/5点和4/5线之间 if(check_5_point(l,m.p1)&&check_5_point(r,m.p2)){ return true; }else{ return false; } } signed main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin>>T; while(T--){ for(int i=1;i<=3;i++){ cin>>a[i].p1.x>>a[i].p1.y>>a[i].p2.x>>a[i].p2.y; } bool flag=false; for(int i=1;i<=3&&!flag;i++){ for(int j=1;j<=3&&!flag;j++){ if(i==j){ continue; } for(int k=1;k<=3&&!flag;k++){ if(k==j||k==i){ continue; } flag|=check(a[i],a[j],a[k]); } } } cout<<(flag?"YES":"NO")<<"\n"; } 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; #define ll long long int //<min, x> pair<ll, ll> f(ll c, vector<ll> &a){ if(a.size() == 0 || c == 0){ return pair<ll, ll>(0, 0); } vector<ll> setBit; vector<ll> unsetBit; for(ll i = 0; i<a.size(); i++){ if((a[i] & c) == c){ setBit.push_back(a[i]); } else{ unsetBit.push_back(a[i]); } } pair<ll, ll> ansSet = f(c/2, setBit); pair<ll, ll> ansUnset = f(c/2, unsetBit); pair<ll, ll> ans = ansUnset; if(unsetBit.size() == 0){ ans = ansSet; ans.second += c; return ans; } else if(setBit.size() == 0){ ans = ansUnset; return ans; } if(ansSet.first < ansUnset.first){ ans = ansSet; ans.second += c; } if(setBit.size() != 0 && unsetBit.size() != 0){ ans.first += c; } return ans; } void solve(){ ll n; cin >> n; vector<ll> a (n); for (ll i = 0; i < n; i++) { cin >> a[i]; } ll c = powl(2, 30); pair<ll, ll> ans = f(c, a); cout << ans.first << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll T = 1; while (T--) { solve(); } return 0; }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int a, b, c, n; cin >> a >> b >> c >> n; int val = a; val = max(val, b); val = max(val, c); a = val - a; b = val - b; c = val - c; if ((a + b + c) > n) { cout << "NO" << endl; } else if (a == 0) { n -= b; n -= c; if ((n % 3) == 0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } else if (b == 0) { n -= a; n -= c; if ((n % 3) == 0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } else if (c == 0) { n -= a; n -= b; if ((n % 3) == 0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } } }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define nl endl #define pb push_back const int N=1e5+10; #define uniq(v) (v).erase(unique(v.begin(),v.end()),(v).end()) void solve(){ ll n,m; cin>>n>>m; // cout<<m<<" "<<n<<nl; vector<string>v1(n),v2(m); for(ll i=0;i<n;i++){ cin>>v1[i]; } for(ll i=0;i<m;i++){ cin>>v2[i]; } ll q; cin>>q; for(ll i=0;i<q;i++){ ll x; cin>>x; ll a=x,b=x; if(a%n==0){ a=(n-1); } else{ a=(a%n)-1; } if(b%m==0){ b=(m-1); } else{ b=(b%m)-1; } cout<<v1[a]+v2[b]<<nl; } } int main(){ // ll t;cin>>t;while(t--) solve(); }
cpp
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
//DEVENDRA KUMAR #include <bits/stdc++.h> using namespace std; #define int long long int #define vi vector<int> #define pb push_back #define pii pair<int,int> #define F first #define S second #define rep(i,n) for(int i=0; i<n; i++) #define nl cout<<endl #define all(x) x.begin(),x.end() #define yes {cout<<"YES";nl;} #define no {cout<<"NO";nl;} const int mod = 1000000007; const double PI = 3.14159265358979323846; int power(int x,int y,int p); void read(vector<int> &a); void read(vector<vector<int>> &a); void print(vector<int>&a); void print(vector<vector<int>>&a); int inv(int x){return power(x,mod-2,mod);}; const int MAXN = 100001; vector<int> adj[MAXN]; vector<int> label(MAXN, -1); void solve(){ int n, u, v; cin>>n; for(int i=1; i<n; i++){ cin>>u>>v; adj[u].pb(i); adj[v].pb(i); } int cnt = 0; for(int i=1; i<=n; i++){ if(adj[i].size() > 2){ label[adj[i][0]] = cnt++; label[adj[i][1]] = cnt++; label[adj[i][2]] = cnt++; break; } } for(int i=1; i<n; i++){ if(label[i]==-1){ label[i] = cnt++; } } for(int i=1; i<n; i++){ cout<<label[i]<<"\n"; } } signed main(){ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); int t = 1; // cin>>t; while(t--) solve(); return 0; } void read(vector<int> &a){ rep(i,a.size()) cin>>a[i]; } void read(vector<vector<int>> &a){ rep(i,a.size()) rep(j,a[i].size()) cin>>a[i][j]; } void print(vector<int> &a){ for(auto x: a) cout<<x<<' '; nl; } void print(vector<vector<int>> &a){ for(auto x: a){ for(auto z: x) cout<<z<<" "; nl; } } int power(int x,int y,int p){int res = 1; x%=p; if(!x) return 0; while(y){ if(y&1) res=(res*x)%p; y=y>>1; x=(x*x)%p; } return res;}
cpp
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
#include<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=2e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[N]; void solve() { n=read(); for(int i=1;i<=n;i++) w[i]=read(); vector<PII> vec; for(int i=1;i<=n;i++) vec.push_back({i-w[i],i}); sort(vec.begin(),vec.end()); ll ans=-1; for(int i=0;i<n;i++) { int j=i; ll res=0; while(vec[j].fi==vec[i].fi&&j<n) res+=w[vec[j].se],j++; ans=max(res,ans); i=j-1; } printf("%lld\n",ans); } int main() { // init(); // stin(); // scanf("%d",&T); T=1; while(T--) solve(); return 0; }
cpp
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; #define eb emplace_back inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 2e5 + 10; const int inf = 1e9 + 10; int n, m, a[N], par[N]; struct node {int v1, p1, v2, p2;} f[1 << 18], g[N]; struct edge {int u, v, w;}; int find(int x) {return x == par[x] ? x : par[x] = find(par[x]);} void push(node &f, int v, int p) { if(f.v1 == -inf) {f.v1 = v, f.p1 = p; return;} if(f.p1 == p) {if(v > f.v1) f.v1 = v, f.p1 = p; return;} if(v >= f.v1) {f.v2 = f.v1, f.p2 = f.p1, f.v1 = v, f.p1 = p; return;} if(v > f.v2) f.v2 = v, f.p2 = p; } int main() { n = read(); rep(i, 1, n) a[i] = read(); a[++ n] = 0; rep(i, 1, n) m = max(m, a[i]), par[i] = i; int t = 1; while((1 << t) <= m) t ++; ll ans = 0; while(true) { rep(i, 0, (1 << t) - 1) f[i] = (node) {-inf, 0, -inf, 0}; rep(i, 1, n) push(f[a[i]], a[i], find(i)), g[i] = (node) {-inf, 0, -inf, 0}; rep(i, 1, (1 << t) - 1) rep(o, 0, t - 1) if(i >> o & 1) { int j = i ^ (1 << o); push(f[i], f[j].v1, f[j].p1); push(f[i], f[j].v2, f[j].p2); } rep(i, 1, n) { int j = ((1 << t) - 1) ^ a[i]; int p = find(i); if(p == f[j].p1) push(g[p], a[i] + f[j].v2, f[j].p2); else push(g[p], a[i] + f[j].v1, f[j].p1); } vector<edge> arc; rep(i, 1, n) if(i == find(i)) { if(g[i].v1 > -inf) arc.eb((edge) {i, g[i].p1, g[i].v1}); } for(edge e : arc) { int u = find(e.u); int v = find(e.v); if(u == v) continue; par[u] = v, ans += e.w; } int cnt = 0; rep(i, 1, n) cnt += (i == find(i)); if(cnt == 1) break; } rep(i, 1, n) ans -= a[i]; printf("%lld\n", ans); return 0; }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
#include<iostream> using namespace std; using ll = long long int ; int main() { ll t; cin>>t; for(int i=0;i<t;i++) { int n; cin>>n; string s; string ss=""; cin>>s; for(int i=0; i<n; i++) { if(s[i]=='1' || s[i]=='3' || s[i]=='5' || s[i]=='7' || s[i]=='9') ss+=s[i]; if(ss.size()==2) break; } if(ss.size()==2) cout<<ss<<endl; else cout<<-1<<endl; } return 0; }
cpp
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
// LUOGU_RID: 99528311 #include<iostream> #include<stdio.h> #include<ctype.h> #include<string.h> #include<queue> #define ll long long #define ld long double #define fi first #define se second #define pii pair<int,int> #define lowbit(x) ((x)&-(x)) #define popcount(x) __builtin_popcount(x) #define inf 0x3f3f3f3f #define infll 0x3f3f3f3f3f3f3f3f #define umap unordered_map #define all(x) x.begin(),x.end() #define mk make_pair #define pb push_back #define ckmax(x,y) x=max(x,y) #define ckmin(x,y) x=min(x,y) #define rep(i,l,r) for(int i=l;i<=r;++i) #define per(i,r,l) for(int i=r;i>=l;--i) #define N 55 using namespace std; inline int read(){ int x=0,f=0; char ch=getchar(); while(!isdigit(ch)) f|=(ch==45),ch=getchar(); while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar(); return f?-x:x; } struct edge{ int b,c,f,n; }e[N*N*4]; int n,m,h[N],tot=1; inline void charu(int a,int b,int f,int c){ e[++tot].b=b,e[tot].f=f,e[tot].c=c,e[tot].n=h[a],h[a]=tot; e[++tot].b=a,e[tot].f=0,e[tot].c=-c,e[tot].n=h[b],h[b]=tot; } int S,T,dis[N],flow[N],vis[N],pre[N]; queue <int> q; inline bool spfa(){ memset(dis,0x3f,sizeof(dis)); memset(flow,0,sizeof(flow)); flow[S]=inf,dis[S]=0,vis[S]=1,q.push(S); while(!q.empty()){ int u=q.front();q.pop();vis[u]=0; for(int i=h[u];i;i=e[i].n){ int v=e[i].b; if(e[i].f && dis[v]>dis[u]+e[i].c){ dis[v]=dis[u]+e[i].c; flow[v]=min(flow[u],e[i].f),pre[v]=i; if(!vis[v]) vis[v]=1,q.push(v); } } } return flow[T]; } int cnt; double C[N*N]; inline pair<int,int> EK(){ int maxflow=0,mincost=0; while(spfa()){ C[++cnt]=dis[T],C[cnt]+=C[cnt-1]; maxflow+=flow[T],mincost+=flow[T]*dis[T]; for(int x=T;x!=S;x=e[pre[x]^1].b) e[pre[x]].f-=flow[T],e[pre[x]^1].f+=flow[T]; } return {maxflow,mincost}; } signed main(){ n=read(),m=read(); for(int i=1;i<=m;++i){ int x=read(),y=read(),z=read(); charu(x,y,1,z); } S=1,T=n; EK(); for(int q=read();q--;){ double x=read(); double ans=1e9; for(int i=1;i<=cnt;++i){ ckmin(ans,(C[i]+x)/(double)i); } printf("%.10lf\n",ans); } return 0; }
cpp
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
#include <bits/stdc++.h> #include <ext/rope> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> // ███████╗████████╗███████╗██╗ ██╗ #define endl "\n" // ██╔════╝╚══██╔══╝██╔════╝██║ ██║ #define F first // ███████╗ ██║ █████╗ ██║ ██║ #define S second // ╚════██║ ██║ ██╔══╝ ╚██╗ ██╔╝ #define For(i, x , n) for(ll i=x ;x==0?i<n :i<=n;i++) // ███████║ ██║ ███████╗ ╚████╔╝ #define Forn(i , x , n )for(int i = n-x ; x==1?i>=0:i>0;i--) //╚══════╝ ╚═╝ ╚══════╝ ╚═══╝ #define cin(v,x,n) For(i,x,n) cin>>v[i] #define Insert(v,x,n) For(i,x,n){int in;cin>>in;v.insert(in);} #define Cin long long n ; cin>>n ; long long arr[n] ; cin(arr,0,n) ; #define Cin2 LL arr2[n] ; cin(arr2,n) ; #define r0 return 0 #define B begin() #define E end() #define RB rbegin() #define RE rend() #define pow 1LL*pow #define Back(s) *s.rbegin() #define Front(s) *s.begin() #define PF(x) push_front(x) #define PB(x) push_back(x) #define POF pop_front() #define POB pop_back() #define Digits(n) (n==0?1:(int)log10(n)+1) #define Bits(n) (ll)log2(n)+1 #define pof(n) ((n&(n-1))==0) #define smaller(n) order_of_key(n) #define bigger(cont , n , x) ( (n) - cont.smaller( x + 1) ) // #define bigger(cont , x) distance(cont.upper_bound(x) , cont.E) #define At(n) find_by_order(n) #define Idx(cont , x) (int)( L(ms)-(distance(cont.lower_bound(x), cont.E))) // linear time for set... #define Sigma(n) (1LL)*( n%2==0?((ll)n/2)*((ll)n+1) :(((ll)n+1)/2)*(ll)n ) // use bracket Sigma(n -+\*) #define Modx(a,b,c) ((a%c)*(b%c))%c #define Modp(a,b,c) ((a%c)+(b%c))%c #define Edis(X1 , X2 , Y1 , Y2) (double) sqrt( pow( abs( X1 - X2 ) , 2) + pow( abs ( Y1 - Y2 ) , 2 )) #define intersect(l , r , l2 , r2) (l<=r2 and r >=l2) #define lcm(a , b) a*b / __gcd(a , b) #define uniq(x) sort(All(x)); x.erase(unique(All(x)),x.E) #define L(s) (int) s.size() // لا تحاول ان تتخطي قدراتك // #define IDX(fnd,s) fnd-s.B // بل اصنع اليوم بما تستطع // #define MAX INT_MAX // ستجد في الغد // #define MIN INT_MIN // ++قدراتك // #define uMAX 0xffffffff #define LA(a) (int)(sizeof(a)/sizeof(a[0])) #define full(x) !(x.empty()) #define All(v) v.B,v.E #define Allr(v) v.rbegin(),v.rend() #define getName(x) #x #define debug(x) cout<<getName(x)<<" = "<<x<<endl #define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n"; #define lambda auto x =[](const Pair &x, const Pair &y) {if (x.second != y.second) {return x.second < y.second;} return x.first < y.first;} #define lambdaSTEV [](const Pair &x, const Pair &y) {if (x.F != y.F) {return x.F < y.F;} return x.S < y.S;} #define Mo_Salah cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); // #pragma GCC optimize("Ofast") // #pragma GCC target("avx,avX2,fma") // #pragma GCC target ("sse4.2") #define oSet tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define oMap tree<int, int ,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define Acc accumulate // lower_bound and upper_bound work oppositely #define oMultiset tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> #define tests int tt ; cin >> tt ; while(tt--) void judge (){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int rnd(int a, int b){ return a + rand() % (b - a + 1);} int generator(){int w = rnd(0, 10);return w; } using namespace std ; using namespace __gnu_pbds; using namespace __gnu_cxx; typedef long long ll ; typedef unsigned long long ull ; typedef pair<ll,ll> Pair ; const int N = 200005 ; const ll MOD = 1e9+7 ; const double PI =3.141592653589793238462643383279502884; const int INF = MAX ; const ll INFl = LLONG_MAX ; int di[] = { 1, -1, 0, 0, 1, -1, 1, -1 }; int dj[] = { 0, 0, 1, -1, 1, -1,-1, 1 }; char dc [] = {'D','U','R','L'} ; int knightX[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int knightY[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; ll n , m , components , k ; // bool f ; bool Salka(int x, int y) { return x > 0 && y > 0 && x <= n && y <= m; } // 1 based /*equal_less auto it = ms.upper_bound(k-i+1) ; if((it!=ms.E and it!=ms.B)or (it==ms.E and full(ms))) it-- ; */ template <typename T1 , typename T2>void dabt_el_masna3(T1 &v , T2 &v2){ v =T1(n+1) ; v2 =T2(n+1) ; } struct point{public : double x , y ;} ; struct triple{public : ll a , b , c ;} ; template <typename T>void debugcont(T&v){for(auto i : v)debug(i);} template <typename T>void debugcont2(T&v){for(auto [l ,r] : v)debug(l) ,debug(r) ; } template<typename T> auto equal_less(T&v , int value){ //return iterator needed or end when fail auto it = upper_bound(All(v) , value) ; //or idx upperbound(value) - container begin if((it!=v.E and it!=v.B) or (it==v.E and full(v))) it-- ; else it=v.E; return it; } /* “You just keep pushing. You just keep pushing. I made every mistake that could be made. But I just kept pushing.” — René Descartes */ /* Steven's Golden Rules ❤ ❏ if you feel so dumb you didnt work enough ❏ give it more time more effort you will be better ❏ if it gives WA that means you will learn something ❏ every problem either teach you something or make you better in something other than that you didnt realy solve it . */ //* main(){ judge() ; Mo_Salah ; tests{ int n , p ; cin>>n>>p; int arr[n] ; vector<int> v; cin(arr,0,n); while(p--){ int in; cin>>in; v.push_back(in-1); } sort(All(v)); For(i,0,L(v))sort(arr+v[i],arr+v[i]+2) ; int l =-1 ,r=-1 ; For(i,1,L(v)-1){ if( v[i] == v[i-1]+1){ if(l==-1) l = v[i-1]; r=v[i]; } else { if(l!=-1) sort(arr+l,arr + r + 1); l=-1 , r = l ; } } if(l!=-1) sort(arr+l,arr+r+1); puts(is_sorted(arr,arr+n)?"YES":"NO"); } }
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; const int N = 510; int dp[N][N], one[N][N], a[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; for(int i=1; i<=n; i++) dp[i][i] = 1, one[i][i] = a[i]; for(int len=2; len<=n; len++) { for(int i=1; i + len - 1<=n; i++) { int j = i + len - 1; dp[i][j] = 10000; for(int k=i+1; k<=j; k++) { if(one[i][k-1] != 0 && one[i][k-1] == one[k][j]) one[i][j] = one[i][k-1] + 1, dp[i][j] = 1; dp[i][j] = min(dp[i][j], dp[i][k-1] + dp[k][j]); } } } cout<<dp[1][n]<<flush; return 0; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long int void solve(){ ll n, m; cin >> n >> m; // if(m == 0){ // cout << 0 << endl; // return; // } ll ans = (n*(n+1))/2; ll z = n - m; // floor(z/(m+1)) * (m-x) + ceil(z/(m+1)) * (x) = z // x = z % m+1; ll x = z % (m+1); ll c = ceil((double)z/(m+1)); ans -= x * (c*(c+1))/2; ll f = z/(m+1); ans -= (m+1-x) * (f*(f+1))/2; cout << ans << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll T = 1; cin >> T; while (T--) { solve(); } return 0; }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define M 1000000007 int main() { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ll n; cin>>n; vector<pair<ll,ll>>a(n); for(ll j=0;j<n;j++){ cin>>a[j].first>>a[j].second; } if(n%2==1){ cout<<"NO\n"; } else{ ll p,q; p=a[0].first+a[n/2].first; ll f=1; q=a[0].second+a[n/2].second; for(ll j=0;j<n/2;j++){ if(p==a[j].first+a[j+n/2].first&&q==a[j].second+a[j+n/2].second){ continue; } else{ f=-1; break; } } if(f==-1){ cout<<"NO\n"; } else{ cout<<"YES\n"; } } }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include <iostream> #include <vector> #include <queue> #include <unordered_map> #include <unordered_set> #include <map> #include <set> #include <cmath> #include <algorithm> #include <functional> using namespace std; #define int long long int gauss(int x) { return x*(x+1)/2; } void solve() { int n,k; cin>>n>>k; int aux=n; n-=k; k++; //cout<<n<<' '<<k; cout<<gauss(aux)-gauss(n/k+1)*(n%k)-gauss(n/k)*(k-(n%k)); } main() { auto sol=[](bool x)->string { if(x)return "YES"; return "NO"; }; int tt=1; cin>>tt; while(tt--) { solve(); cout<<'\n'; } }
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; #ifdef DEBUG #include "debug.h" #else #define debug(...) 1 #endif using ll = long long; using db = long double; using VS = vector<string>; using VLL = vector<ll>; using VVLL = vector<VLL>; using VVVLL = vector<VVLL>; using PLL = pair<ll, ll>; using MLL = map<ll, ll>; using SLL = set<ll>; using QLL = queue<ll>; using SS = stringstream; #define rep(x, l, u) for (ll x = l; x < u; x++) #define rrep(x, l, u) for (ll x = l; x >= u; x--) #define fe(x, a) for (auto x : a) #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define mst(x, v) memset(x, v, sizeof(x)) #define sz(x) (ll) x.size() #define umap unordered_map #define uset unordered_set #define mset multiset // clang-format off ll ob(ll i, ll n) { return i < 0 || i >= n; } ll tp(ll x) { return ( 1LL << x ); } ll rup(ll a, ll b) { return a % b ? a/b + 1 : a/b; } ll sign(ll x) { return x == 0 ? 0 : x / abs(x); } void makemod(ll& x, ll m) { x %= m; if (x < 0) { x += m; } } ll getmod(ll x, ll m) { makemod(x, m); return x; } ll powmod(ll a, ll b, ll m) { if (b == 0) return 1; ll h = powmod(a, b/2, m); ll ans = h*h%m; return b%2 ? ans*a%m : ans; } ll invmod(ll a, ll m) { return powmod(a, m - 2, m); } void inll(ll& x) { scanf("%lld", &x); } template <typename A, typename B> bool upmin(A& x, B v) { if (v >= x) return false; return x = v, true; } template <typename A, typename B> bool upmax(A& x, B v) { if (v <= x) return false; return x = v, true; } // clang-format on const VLL di = {0, 0, 1, -1, 1, -1, 1, -1}, dj = {1, -1, 0, 0, -1, -1, 1, 1}; const ll mod = 1'000'000'007, mod2 = 998'244'353, inf = (ll)1e18 + 5; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const double PI = atan(1) * 4; struct Angle { ll x, y, revs; // x, y of the coordinate // revs is the 0-indexed circle its on // by default 0 Angle(ll x, ll y, ll r = 0) { ll g = gcd(x, y); assert(g > 0); this->x = x / g; this->y = y / g; this->revs = r; } ll quadrant() const { // * NOTE this is 0-indexed if (y >= 0 && x > 0) return 0 + revs * 4; if (x <= 0 && y > 0) return 1 + revs * 4; if (y <= 0 && x < 0) return 2 + revs * 4; if (x >= 0 && y < 0) return 3 + revs * 4; assert(false); } PLL bound(ll quad) const { return {quad * 90, (quad + 1) * 90}; } double angle() const { // Return an angle from [0, 360) PLL b = bound(quadrant()); double res = x == 0 ? 90 : atan(y / (double)x) / PI * 180; res += revs * 360; // roughly get to the right angle while (res < b.first) res += 180; while (res >= b.second) res -= 180; assert(res >= b.first && res < b.second); return res; } ll compare(const Angle& rhs) const { // return -1 if self is smaller, 0 if same, 1 if self is bigger if (x == rhs.x && y == rhs.y) return 0; ll q = quadrant(), rhsq = rhs.quadrant(); if (q < rhsq) return -1; if (q > rhsq) return 1; // same quadrant if (y * rhs.x < x * rhs.y) return -1; return 1; } }; ostream& operator<<(ostream& os, const Angle& angle) { os << "{" << angle.x << ", " << angle.y << "}"; return os; } namespace NCR { ll ncr(ll n, ll r) { if (r > n) return 0; // n! / r! / (n-r)! // small r: ll ans = 1; rep(i, n - r + 1, n + 1) { ans *= i; } rep(i, 1, r + 1) { ans /= i; } return ans; } } // namespace NCR void solve() { ll n; cin >> n; vector<PLL> A(n); rep(i, 0, n) cin >> A[i].first >> A[i].second; // choose some point and fix as the center ll ans = 0; rep(i, 0, n) { // sort around this point vector<Angle> B; rep(j, 0, n) { if (i == j) continue; B.push_back({A[j].first - A[i].first, A[j].second - A[i].second}); } sort(all(B), [](auto a, auto b) { // return 1 if a is smaller if (a.compare(b) <= 0) return 1; return 0; }); rep(j, 0, n - 1) { B.push_back({B[j].x, B[j].y, B[j].revs + 1}); } ll total = NCR::ncr(n - 1, 4); ll sub = 0; // count how many points are within the other half ll r = 0; // right pointer rep(j, 0, n - 1) { Angle plusHalf = {-B[j].x, -B[j].y, (B[j].quadrant() + 2) / 4}; while (B[r].compare(plusHalf) == -1) { r++; } ll amount = r - j; sub += NCR::ncr(amount - 1, 3); } ans += total - sub; } cout << ans << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0); ll t = 1; // cin >> t; rep(i, 0, t) 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" ]
#include <bits/stdc++.h> #define name "" #define test "test" #define ll long long #define ld long double #define fi first #define se second #define pll pair < ll, ll > #define pii pair < int, int > #define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define sz(x) ((int)(x).size()) #define pb push_back #define mp make_pair using namespace std; const ld EPS = 1e-9; const int INF = 1e9 + 7; const ll LINF = 1E18; const int NMAX = 2e5; const ll MOD = 1e9 + 7; const ll BASE = 2309; int n, f[200003], g[200003], minl[200003]; pii a[200003]; void sol() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i].fi >> a[i].se; sort(a + 1, a + n + 1, [&](pii &x, pii &y) { return x.se < y.se; }); g[n] = 1, minl[n] = a[n].fi; for (int i = n - 1; i >= 1; i--) { g[i] = g[i + 1] + (minl[i + 1] > a[i].se); minl[i] = min(minl[i + 1], a[i].fi); } int res = 0; vector < int > vec; vec.push_back(-INF); for (int i = 1; i < n; i++) { int it = lower_bound(vec.begin(), vec.end(), minl[i + 1]) - vec.begin(); it --; res = max(res, g[i + 1] + it); while (sz(vec) && vec.back() >= a[i].fi) vec.pop_back(); vec.push_back(a[i].se); } cout << max(res, sz(vec) - 1) << '\n'; } int main() { fast; if(fopen(name".inp", "r")) { freopen(name".inp", "r", stdin); freopen(name".out", "w", stdout); } int t; cin >> t; while (t --) sol(); }
cpp
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
#include<bits/stdc++.h> #define ls i<<1 #define rs i<<1|1 #define fi first #define se second #define min amin #define max amax #define pb push_back using namespace std; using ll=long long; using pii=array<int,2>; constexpr int N=60; constexpr int inf=1E9; constexpr int p=998244353; int qpow(int x,int n=p-2){int y=1;for(;n;n>>=1,x=1LL*x*x%p)if(n&1)y=1LL*y*x%p;return y;} template<typename T=int>T read(){T x;cin>>x;return x;} template<typename U,typename V>U min(U x,V y){return x<y?x:y;} template<typename U,typename V>U max(U x,V y){return x>y?x:y;} template<typename U,typename...V>U min(U x,V...y){return min(x,min(y...));} template<typename U,typename...V>U max(U x,V...y){return max(x,max(y...));} template<typename U,typename V>bool cmin(U &x,V y){return x>y?x=y,true:false;} template<typename U,typename V>bool cmax(U &x,V y){return x<y?x=y,true:false;} int f[N],g[N]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout<<fixed<<setprecision(6); int n=read(),m=n>>1; for(int i=1;i<=m;++i)f[i]=g[i]=inf; while(n--) { int x=read(); if(!x) { for(int i=m;i>=1;--i) { cmin(g[i],f[i]+1); f[i]=min(f[i-1],g[i-1]+1); } cmin(g[0],f[0]+1); f[0]=inf; } else if(x&1) { for(int i=0;i<=m;++i) { cmin(g[i],f[i]+1); f[i]=inf; } } else { for(int i=m;i>=1;--i) { f[i]=min(f[i-1],g[i-1]+1); g[i]=inf; } f[0]=g[0]=inf; } } cout<<min(f[m],g[m])<<'\n'; }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define F first #define S second void yes(){cout<<"YES\n";} void no(){cout<<"NO\n";} long long mod = 1e9+7; struct Point{ int x,y; }; void solve() { int n; cin >> n; vector<Point> P(n+1); for(int i=0; i<n; i++){ cin >> P[i].x >> P[i].y; } P[n] = P[0]; bool ok = true; if(n&1){ cout <<"NO\n"; }else{ for(int i=0; i<n/2; i++){ if(P[i+1].x - P[i].x + P[i+n/2+1].x - P[i+n/2].x == 0 and P[i+1].y - P[i].y + P[i+n/2+1].y - P[i+n/2].y == 0){ continue; }else{ ok = false; break; } } if(ok == true){ cout <<"YES\n"; }else{ cout <<"NO\n"; } } } int main() { ios::sync_with_stdio(0); cin.tie(0); // int t; cin >> t; while(t--)// solve(); }
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" ]
#import<iostream> int m,n,s;main(){std::cin>>n>>m;if(m%n)return std::cout<<-1,0;for(m/=n;~m%2||m%3<1;s++)m%2?m%3?:m/=3:m/=2;std::cout<<(m>1?-1:s);}
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include <bits/stdc++.h> #include <cstdio> using namespace std; /*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<pair<long long,long long>, null_type,less<pair<long long,long long> >, rb_tree_tag,tree_order_statistics_node_update>*/ template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;}; template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for(auto &x : a) out << x << ' '; return out;}; #define mod1 (long long)998244353 #define mod2 (long long)1000000007 #define first_bit(x) (x&(-x)) #define last_bit(x) (x&~(x)) #define ll long long #define ld long double #define int long long #define ff first #define ss second #define pb push_back #define w(x) long long x;cin>>x;while(x--) #define vi vector<long long> #define mii map<long long,long long> #define pii pair<long long,long long> #define set_bits(x) __builtin_popcountll(x) #define fast() ios_base::sync_with_stdio(false);cin.tie(NULL); #define sz(x) ((long long)x.size()) #define all(x) begin(x), end(x) #define memo(x,y) memset((x),(y),sizeof(x)); map<int,vector<pii> > adj; vector<int> path; bool dfs(int root,int par,int tg){ if(root==tg){ return true; } for(auto i:adj[root])if(i.ff!=par){ if(dfs(i.ff,root,tg)){ path.push_back(i.ss); return true; } } return false;; } struct point{ int st; int en; int mini; }; signed main(){ fast(); int n; cin>>n; vector<int> res(n,1000000); for(int i=1;i<=n-1;i++){ int a,b; cin>>a>>b; adj[a].pb({b,i}); adj[b].pb({a,i}); } int m; cin>>m; vector<point> v(m); vector<vi> rut; for(int i=0;i<m;i++){cin>>v[i].st>>v[i].en>>v[i].mini;} sort(all(v),[&](point p1,point p2){ return p1.mini<p2.mini; }); for(auto i:v){ vector<int> curr; dfs(i.st,0,i.en); curr=path; path.clear(); rut.pb(curr); for(auto j:curr){res[j]=i.mini;} } bool can=true; for(int i=0;i<m;i++){ bool pass=false; for(auto j:rut[i])if(res[j]==v[i].mini)pass=true; can&=pass; } if(can)for(int i=1;i<=n-1;i++)cout<<res[i]<<" "; else cout<<-1<<endl; }
cpp
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
// Problem: D. Reachable Strings // Contest: Codeforces - Codeforces Round #625 (Div. 1, based on Technocup 2020 Final Round) // URL: https://codeforces.com/contest/1320/problem/D // Memory Limit: 256 MB // Time Limit: 3000 ms // // Powered by CP Editor (https://cpeditor.org) #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx,avx2,sse,sse2") #include<bits/stdc++.h> #define all(x) begin(x), end(x) using namespace std; using ll = long long; template<typename F> void multitest(F func) { int t; cin >> t; while(t--) func(); } void report(int ok) { cout << (ok?"Yes":"No") << '\n'; } const int N = 1<<18; int main() { cin.tie(0)->sync_with_stdio(0); int n; string s; cin >> n; cin >> s; vector<int> zeros; bitset<N> zero_bitset[2]; for(int i = 0; i < n; i++) { if(s[i] == '0') { zero_bitset[0][zeros.size()] = i & 1; zeros.push_back(i); } } zero_bitset[1] = ~zero_bitset[0]; auto count = [&](int l, int r) {//zeros in [l; r) return lower_bound(all(zeros), r) - lower_bound(all(zeros), l); }; int q, a, b, len; cin >> q; while(q--) { cin >> a >> b >> len; a--, b--; int z1 = count(a, a + len); int z2 = count(b, b + len); int s1 = count(0, a); int s2 = count(0, b); if(z1 != z2) report(0); else { int mismatch = ((zero_bitset[0] >> s1) ^ (zero_bitset[(a^b)&1] >> s2))._Find_first(); report(mismatch >= z1); } } }
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include<bits/stdc++.h> #define int long long int #define rep(i,a,b) for(int i=a;i<b;i++) #define vi vector<int> #define vll vector<long long int> using namespace std; bool isPossible(int num,string &str,int a,int b,int have){ int total_cost = 0; char prev = 'Z'; for(int i=num;i<str.length();i++){ if(str[i] != prev){ prev = str[i]; if(str[i] == 'A') total_cost += a; else total_cost += b; } } return total_cost<=have; } void solve() { int a,b,p;cin>>a>>b>>p; string str;cin>>str; int n = str.length(); str = str.substr(0,n-1); int lo = 0, hi = 1e9; while(lo < hi){ int mid = (lo + hi)/2; if(isPossible(mid,str,a,b,p)){ hi = mid; } else{ lo = mid + 1; } } cout<<lo+1<<endl; } signed main() { int t; cin>>t; while(t--) solve(); return 0; }
cpp
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long string modify(string &s,int n,int k){ string result_prefix = s.substr(k - 1, n - k + 1); string result_suffix = s.substr(0, k - 1); if (n % 2 == k % 2) reverse(result_suffix.begin(), result_suffix.end()); return result_prefix + result_suffix; } void solve(); int main(){ int testNumber; cin>>testNumber; while(testNumber--){ solve(); } return 0; } void solve(){ string s, best_s, temp; int n, best_k; cin >> n >> s; best_s = modify(s, n, 1); best_k = 1; for (int k = 2; k <= n; ++k) { temp = modify(s, n, k); if (temp < best_s) { best_s = temp; best_k = k; } } cout << best_s << '\n' << best_k << '\n'; }
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> using namespace std; const int N=2e5+10; int pre[N][30]; string s; int main() { ios::sync_with_stdio(false);cin.tie(0); string s; cin>>s; int n=s.size(); s=' '+s; for(int i=1;i<=n;i++) { for(int j=0;j<26;j++) { pre[i][j]=pre[i-1][j]+(s[i]==j+'a'); } } int q; cin>>q; while(q--) { int l,r,cnt=0; cin>>l>>r; if(l==r||s[l]!=s[r]) { cout<<"YES\n"; continue; } else { for(int i=0;i<26;i++) { if(pre[r][i]-pre[l][i]) cnt++;//这个区间有字符i+'a' if(cnt>=3) break; } } if(cnt>=3) cout<<"YES\n"; else cout<<"NO\n"; } 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 <iomanip> #include <iostream> #include <map> #include <string> #pragma GCC optimize("Ofast") #pragma GCC target("avx,sse2,sse3,sse4,mmx,arch=cannonlake,tune=cannonlake") #define query(pos) (a[*lower_bound(stk + 1, stk + 1 + r, (pos))]) #define endl '\n' using std::cin; using std::cout; using std::lower_bound; using std::map; using std::string; using std::upper_bound; constexpr long long N = 6e5 + 514; constexpr long long mask = (1 << 30) - 1; long long nxt[N], anc[N]; string s; long long a[N]; // 串和 w 数组 long long stk[N]; // 单调栈 long long r; // 栈顶 __int128 ans, sum; long long tmp1, tmp2; // tmp for output long long n; char c; map<long long, long long> cnt; void output(__int128 out) { constexpr long long P = 1e18; if (out < P) { cout << (long long)out << endl; } else { tmp1 = out / P, tmp2 = out % P; cout << tmp1 << std::setw(18) << std::setfill('0') << tmp2 << endl; } } int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); s.reserve(N); cin >> n; cin >> c >> a[0]; s += c; // 第一次加字符不需要加密 ans = a[0]; // 第一次加数字同理 stk[++r] = 0; cout << a[0] << endl; // 因此直接输出就行了 for (long long i = 1, j = 0; i < n; ++i) { cin >> c >> a[i]; c = (c - 'a' + ans % 26) % 26 + 'a'; s += c; // 字符加密 a[i] = a[i] ^ (ans & mask); // 数字加密 /* KMP */ while (j && c != s[j]) { j = nxt[j]; } if (s[j] == c) { ++j; } nxt[i + 1] = j; if (c == s[nxt[i]]) { anc[i] = anc[nxt[i]]; } else { anc[i] = nxt[i]; } for (long long k = i; k > 0;) { if (s[k] == c) { k = anc[k]; } else { long long v = query(i - k); --cnt[v]; sum -= v; if (cnt[v] == 0) { cnt.erase(v); } k = nxt[k]; } } if (s[0] == c) { ++cnt[a[i]]; sum += a[i]; } /* 单调栈 */ while (r && a[i] <= a[stk[r]]) { --r; } stk[++r] = i; long long ncnt = 0; // 当前长度 border 的数量(大概 for (auto it = cnt.upper_bound(a[i]);;) { if (it == cnt.end()) break; sum -= (it->first - a[i]) * it->second; ncnt += it->second; auto j = std::next(it); cnt.erase(it); it = j; } cnt[a[i]] += ncnt; ans += a[stk[1]] + sum; output(ans); } 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" ]
/* Your Mind Is Your Biggest Enemy */ #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; #pragma GCC optimize ("-O3") #define ll long long int #define ld long double #define ff first #define ss second /*-----------------------------------------------DEBUG FUNCTIONS----------------------------------------------------------------------------------------------------------------------------------------------------*/ #ifdef YuvrajSharma #define deb(...) cerr << "(" << #__VA_ARGS__ << "): ", debug(__VA_ARGS__),cerr<<endl; #else #define deb(...); #endif void debug(ll t) {cerr << t;} void debug(int t) {cerr << t;} void debug(string t) {cerr << t;} void debug(char t) {cerr << t;} void debug(ld t) {cerr << t;} void debug(double t) {cerr << t;} void debug(unsigned ll t) {cerr << t;} template <class Y, class V> void debug(pair <Y, V> p); template <class Y> void debug(vector <Y> v); template <class Y> void debug(set <Y> v); template <class Y, class V> void debug(map <Y, V> v); template <class Y> void debug(multiset <Y> v); template <class Y, class V> void debug(pair <Y, V> p) {cerr << "{"; debug(p.ff); cerr << ","; debug(p.ss); cerr << "}";} template <class Y> void debug(vector <Y> v) {cerr << "[ "; for (Y i : v) {debug(i); cerr << " ";} cerr << "]";} template <class Y> void debug(set <Y> v) {cerr << "[ "; for (Y i : v) {debug(i); cerr << " ";} cerr << "]";} template <class Y> void debug(multiset <Y> v) {cerr << "[ "; for (Y i : v) {debug(i); cerr << " ";} cerr << "]";} template <class Y, class V> void debug(map <Y, V> v) {cerr << "[ "; for (auto i : v) {debug(i); cerr << " ";} cerr << "]";} template <typename Head, typename... Tail> void debug(Head H, Tail... T){cerr << H << ' ';debug(T...);} /*------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ #define endl '\n' #define pb push_back #define mp make_pair #define lb lower_bound #define ub upper_bound #define sz(x) (ll)x.size() #define pqh priority_queue #define ook order_of_key // returns position (unsigned integer) to given key #define fbo find_by_order // returns iterator to the element at given position #define fo(i,n) for(i=0;i<n;i++) #define Fo(i,n) for(i=1;i<=n;i++) #define rep(i,a,b) for(i=a;i<=b;i++) #define per(i,b,a) for(i=b;i>=a;i--) #define all(x) x.begin(), x.end() #define zerobits(x) __builtin_ctzll(x) #define setbits(x) __builtin_popcountll(x) #define tr(it, a) for(auto it = a.begin(); it != a.end(); it++) #define tol(s) transform(s.begin(),s.end(),s.begin(),::tolower); #define tou(s) transform(s.begin(),s.end(),s.begin(),::toupper); #define read(v) for(auto &itt:v) cin>>itt; #define print(v) for(auto &itt:v) cout<<itt<<' ' ; cout<<endl; #define T ll tt=0;cin>>tt;for(ll test=1;test<=tt;test++) typedef pair<ll, ll> pl; typedef vector<pl> vpl; typedef pair<int,int> pi; typedef vector<pi> vpi; typedef pair<ll,pl> plp; typedef vector<plp> vplp; typedef pair<pi,int> ppi; typedef vector<ppi> vppi; typedef pair<pl,pl> ppp; typedef vector<ppp> vppp; typedef pair<pi,pi> pppi; typedef vector<pppi> vpppi; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<int> vi; typedef vector<vi> vvi; template <typename Y> using oset = tree<Y, null_type, less<Y>, rb_tree_tag, tree_order_statistics_node_update>; template <class Y> void debug(oset<Y> v) {cerr << "[ "; for (auto i : v) {debug(i); cerr << " ";} cerr << "]";} template <typename Y> using pql = priority_queue<Y, vector<Y>, greater<Y>>; template <typename Y> void make_unique(Y &vec) { vec.erase(unique(vec.begin(),vec.end()), vec.end()); } mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); ll randint(ll a, ll b){ return uniform_int_distribution<ll>(a, b)(rnd); } struct custom_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; const ll mod = 1e9+7; // 998244353 ; /*------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ ll isprime(ll n){ if(n<=1) return 0; if(n<=3) return 1; if(n%2==0||n%3==0) return 0; for(ll i=5;i*i<=n;i=i+6) if(n%i==0||n%(i+2)==0) return 0; return 1; } ll gcd(ll a,ll b){return __gcd(a,b); } void testnum(ll t){cout<<"Case #"<<t<<": ";} ll lsb(ll n){ n=n^(n&(n-1)); ll pos=0; while(n){n=n>>1; pos++; } return pos-1; }/* acc. to zero indexing*/ ll bpow(ll a,ll n){ll res=1; while(n>0){ if(n&1LL) res=res*a; a=a*a; n>>=1; } return res; } ll msb(ll n){ ll pos=0; while(n){n=n>>1; pos++; } return pos-1; }/* acc. to zero indexing*/ ll mpow(ll a, ll n,ll p){ a%=p; ll res=1; while(n>0){ if(n&1LL)res=res*a%p; a=a*a%p; n>>=1; } return res; } ll add(ll a, ll b){ return (a+b)%mod; } ll sub(ll a,ll b){ return (a-b+mod)%mod; } ll mul(ll a, ll b){ return ((a%mod)* (b%mod)) % mod; } ll modI(ll n,ll p){ return mpow(n, p - 2, p); } ll lcm(ll a,ll b){return (a*b)/__gcd(a,b);} ll LCM(vl &v,ll n){ ll ans=v[0]; for(ll i=1;i<n;i++) ans=(((v[i]*ans))/(__gcd(v[i],ans))); return ans; }ll ncr(ll n,ll r){if(n<0||r<0||n<r){return 0;}ll res=1;if(r>n-r)r=n-r; for(ll i=0;i<r;++i){res*=(n-i);res/=(i+1);}return res; } map<ll, ll> pnt_compression(vl &pnt){ map<ll, ll> u; ll i=0,ct=0; fo(i,sz(pnt)){ u[pnt[i]]=0;} for(auto &it:u){ it.ss=ct; ct++;} return u; } bool comp(pl a,pl b){ return false; } /*------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ const ld PI = 3.141592653589793 ; const ld eps = 1e-9 ; const ll inf = 2e18 ; // 1e9; const ll cons = 505; ll N,M; vl v; ll dp[cons],dp2[cons][cons]; ll solve(ll l,ll r){ if(l==r){ return dp2[l][r]=v[l-1]; } ll &ans=dp2[l][r]; if(ans!=-1){ return ans; } ans=0; for(ll i=l;i<r;i++){ ll pre=solve(l,i),suf=solve(i+1,r); if(pre==suf&&pre>0){ return ans=pre+1; } } return ans; } signed main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); #ifdef YuvrajSharma freopen("input.txt","r",stdin),freopen("output.txt","w",stdout),freopen("error.txt", "w", stderr); #endif // cout<<fixed<<setprecision(9); ll n=0,m=0,i=0,j=0,k=0,cnt=0,ans=0,sum=0,flag=0,pos=-1,ind=-1,mn=inf,mx=-inf,res=0; cin>>n; v=vl(n); fo(i,n){ cin>>v[i]; } memset(dp2,-1,sizeof dp2); dp[0]=0; Fo(i,n){ dp[i]=inf; for(j=1;j<=i;j++){ if(solve(j,i)>0){ dp[i]=min(dp[i],dp[j-1]+1); } } } cout<<dp[n]<<endl; return 0; } /* always remember these things => check edge cases like when n==1, l==r, overflow, array bounds => don't initialize dp with such values which dp state can attain => don't use memset when multiple testcases are present => there is a pattern when everything is uniformly distributed => try different approaches and try to find a general solution => BF, FC, LM, BS, MTH, GY, DP, DC, PSA, CT */
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" ]
// LUOGU_RID: 96383303 #include<bits/stdc++.h> using namespace std; string s; long long ans1; long long sum[205][205],ans[205]; int main(){ cin >> s; for(int i = 0;i < s.size();i++){ for(int j = 97;j <= 122;j++){ if(ans[j]){ sum[j][s[i]] += ans[j]; ans1 = max(ans1,sum[j][s[i]]); } } ans[s[i]]++; ans1 = max(ans1,ans[s[i]]); } cout << ans1; 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" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 5010; const int inf = 1e9 + 10; int n, m, a[N], s[N], c[N], f[N][N], g[N]; void cmax(int &x, int y) {x = x > y ? x : y;} int main() { n = read(), m = read() + (g[0] = n); rep(i, 1, n) a[i] = read(), g[i] = g[i - 1] >> 1; rep(i, 1, n) s[i] = read(); rep(i, 1, m) {c[i] = read(); rep(j, 1, n) f[i][j] = -inf;} per(i, n, 1) { int v = a[i]; per(j, n, 1) cmax(f[v][j], f[v][j - 1] + c[v] - s[i]); rep(j, v, m) rep(k, 0, g[j - v]) cmax(f[j + 1][k >> 1], f[j][k] + c[j + 1] * (k >> 1)); } printf("%d\n", f[m + 1][0]); return 0; }
cpp
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
#include<bits/stdc++.h> using namespace std; int main() {int t; cin >> t; while(t--){ int n; cin >> n; int a[2 * n]; for(int i=0;i<2*n;i++){ cin >> a[i]; } sort(a,a + (2*n)); cout << a[n] - a[n-1] << endl; } return 0; }
cpp
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define debug(x) cout<<":["<<x<<"XE]"<<endl; #define debug2(x,y) cout<<":["<<x<<" "<<y<<"XE]"<<endl; #define _ ios_base::sync_with_stdio(false); #define mod 1000000007 #define mod2 998244353 #define inf LLONG_MAX #define yes cout << "YES\n" #define yes2 cout << "Yes\n" #define no cout << "NO\n" #define no2 cout << "No\n" #define forn2(a,n) for(int i=1;i<=n;i++){cin>>a[i];} #define forn(x,n) for(int i=x;i<=n;i++) int main() {_ // freopen("feast.in", "r", stdin); // freopen("feast.out", "w", stdout); ll t=1,ca=1; //cin>>t; ///CHECK FROM HERE*** while(t--){ ll n; cin>>n; string s; cin>>s; vector<ll>v(n+1,-1); for(int i=0;i<n;i++){ if(v[i]!=-1){ for(int j=i+1;j<n;j++){ if(s[j]<s[i]){ v[j]=1-v[i]; } } continue; } set<ll>st; for(int j=i+1;j<n;j++){ if(s[j]<s[i]){ if(v[j]!=-1)st.insert(v[j]); } } //debug(st.size()) if(st.size()==0){v[i]=0; for(int j=i+1;j<n;j++){ if(s[j]<s[i]){ v[j]=1; } } } else{ ll z=*st.begin(); z=1-z; v[i]=z; for(int j=i+1;j<n;j++){ if(s[j]<s[i]){ if(v[j]==-1)v[j]=1-z; } } } } //forn(0,n-1)debug(v[i]) ll ok=1; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(v[i]==v[j]&&s[j]<s[i])ok=0; } } if(ok){ yes; forn(0,n-1)cout<<v[i]; } else no; } }
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 <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define fastread() (ios_base:: sync_with_stdio(false), cin.tie(NULL)); //LL, other ways to simplify it?, tricks & math, backwards, constraints, //ll mod(1e9+7); void runCase() { vector<int> v(26, 0); int n; cin >> n; int m; cin >> m; int a[m]; map<int, int> ma[n]; string s; cin >> s; for (int i = 0; i < m; ++i) { cin >> a[i]; } for (int i = 0; i < n; ++i) { if (i > 0) { ma[i] = ma[i-1]; } ma[i][s[i] - 'a']++; } for (int i = 0; i < m; ++i) { for (auto y : ma[a[i] - 1]) { v[y.first] += y.second; } } for (auto y : ma[n - 1]) { v[y.first] += y.second; } for (int i = 0; i < 26; ++i) { cout << v[i] << " "; } cout << endl; } int main() { fastread() int t = 1; cin >> t; while (t--) { runCase(); } return 0; }
cpp
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2 3 3 2 1 6 3 1 4 1 5 9 OutputCopy3 5 NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
[ "greedy", "implementation" ]
//ABANOUB FAWAZ #include <iostream> #include <iomanip> #include<cmath> #include<string> #include<vector> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #define ll long long using namespace std; void fast() { ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); } bool com(pair<int, int>& a, pair<int, int>& b) { if (a.first == b.first) return b.second < b.first; } ll bs(ll arr[], ll l, ll r, ll key) { while (l <= r) { ll m = (l + r) / 2; if (arr[m] == key)return m; if (arr[m] > key)r = m - 1; else l = m + 1; } return -1; } bool prime(ll n) { if (n <= 1)return 0; for (ll i = 2; i * i <= (n); i++) { if (n % i == 0)return 0; } return 1; } int primes[1005]; void seive() { primes[0] = primes[1] = 0; for (int i = 2; i <= sqrt(1000); i++) { if (primes[i]) { for (int j = 2; j * i <= 1000; j++) { primes[j * i] = 0; } } } } ll fib(ll n) { if (n == 1)return 1; if (n == 2)return 2; else return fib(n - 1) + fib(n - 2); } ll GCD(ll a, ll b) { return a == 0 ? b : GCD(b % a, a); } ll LCM(ll x, ll y) { return x * y / GCD(x, y); } bool make_palindrome(string s) { map<char, ll>mp; ll c = 0; for (int i = 0; i < s.size(); i++)mp[s[i]]++; for (auto it : mp) { if (it.second & 1)c++; } if (c > 1)return 0; return 1; } void binary(ll n) { if (n == 0)return; binary(n / 2); cout << n % 2; } int main() { fast(); const double PI = 3.14159265359; ll t; cin >> t; while (t--) { ll n; cin >> n; vector<ll>x(n); set<ll>st; for (int i = 0; i < n; i++) { cin >> x[i]; st.insert(x[i]); } cout << st.size() << "\n"; } return 0; }
cpp
1303
F
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10 2 1 1 1 2 1 2 2 1 1 1 2 3 1 2 1 2 2 2 2 2 2 1 2 3 2 4 2 1 5 OutputCopy2 4 3 3 4 4 4 2 2 4
[ "dsu", "implementation" ]
/* * @name Dinic algorithm * @description Algorithm for flow searching in O(n^2m) * */ /* Includes */ #include <bits/stdc++.h> /* Using libraries */ using namespace std; /* Defines */ #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define ld long double #define pb push_back #define vc vector #define sz(a) (int)a.size() #define forn(i, n) for (int i = 0; i < n; ++i) #define pii pair <int, int> #define vec pt #define all(a) a.begin(),a.end() /* Constants */ #define ll long long const ld eps = 1e-10; const int inf = 2e18; const ll mod = 1e9 + 7; const int bit = 12; const int C = 1e6, N = 2e6 + 1; struct dsu { vc <int> p; int comp; dsu (int n): comp(n) { p.resize(n); iota(all(p), 0); } int find (int u) { return u == p[u] ? u : p[u] = find(p[u]); } int unite (int u, int v) { u = find(u); v = find(v); if (u == v) return 0; p[v] = u; return 1; } }; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, -1, 1}; int n, m; int a[400][400]; int ans[N]; void go (vc <pii> &add, int d) { dsu t(n * m); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) a[i][j] = 0; for (auto &[crd, j] : add) { int x = crd / m, y = crd % m; a[x][y] = 1; int was = 1; for (int i = 0; i < 4; ++i) { int kx = x + dx[i], ky = y + dy[i]; if (kx >= 0 && ky >= 0 && ky < m && kx < n && a[kx][ky] == 1) { was -= t.unite(crd, kx * m + ky); } } ans[j] += d * was; } } vc <pii> add[N], del[N]; void solve () { int q; cin >> n >> m >> q; int ret = 1; for (int i = 0; i < q; ++i) { int x, y, c; cin >> x >> y >> c; --x; --y; if (a[x][y] != c) { ret = c + 1; add[c].pb({x * m + y, i}); del[a[x][y]].pb({x * m + y, i}); a[x][y] = c; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { del[a[i][j]].pb({i * m + j, q}); } } for (int i = 0; i < ret; ++i) { go(add[i], 1); } for (int i = 0; i < ret; ++i) { reverse(all(del[i])); go(del[i], -1); } int comp = 1; for (int i = 0; i < q; ++i) { comp += ans[i]; cout << comp << '\n'; } } //dsadas /* Starting and precalcing */ signed main() { fast; int t = 1; //cin >> t; while (t--) solve(); return 0; }
cpp
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
#include<iostream> #include<math.h> #include<algorithm> #include<string> #include<cstring> #include<string.h> #include<vector> #include<map> #include<cmath> #include<cstdio> #include<set> #include<deque> #include<queue> #include<stack> using namespace std; const int inf=0x3f3f3f3f,hamod=1e9+7,HAmod=1e9+9,mod=200907,N=1e6+10,maxn=1e5+10; const double pi=acos(-1.0); typedef long long ll; #define mp make_pair #define eps 1e-8 #define lighting ios::sync_with_stdio(false);cin.tie(0),cout.tie(0); //#define lighting ios::sync_with_stdio(false);cin.tie(nullptr),cout.tie(nullptr); stack<ll>l,r; ll n,maxx=-1,pos,m[N],suml[N],sumr[N]; signed main() { lighting; cin>>n; for(ll i=1;i<=n;i++) { cin>>m[i]; while(!l.empty()&&m[l.top()]>m[i]) l.pop(); if(l.empty()) suml[i]=suml[0]+i*m[i]; else suml[i]=suml[l.top()]+(i-l.top())*m[i]; l.push(i); } for(ll i=n;i>=1;i--) { while(!r.empty()&&m[r.top()]>m[i]) r.pop(); if(r.empty()) sumr[i]=sumr[n+1]+(n-i+1)*m[i]; else sumr[i]=sumr[r.top()]+(r.top()-i)*m[i]; r.push(i); if(suml[i]+sumr[i]-m[i]>maxx) { maxx=suml[i]+sumr[i]-m[i]; pos=i; } } //cout<<maxx<<endl; for(ll i=pos-1;i>=1;i--) { m[i]=min(m[i],m[i+1]); } for(ll i=pos+1;i<=n;i++) { m[i]=min(m[i],m[i-1]); } for(ll i=1;i<=n;i++) cout<<m[i]<<" "; }
cpp
1292
C
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3 1 2 2 3 OutputCopy3 InputCopy5 1 2 1 3 1 4 3 5 OutputCopy10 NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<vector<int>> g(n); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; u--, v--; g[u].push_back(v); g[v].push_back(u); } vector par(n, vector<int>(n, -1)), sz(n, vector<int>(n, 1)); for (int i = 0; i < n; i++) { auto DFS = [&](int u, auto&& DFS) -> void { for (int v : g[u]) if (v != par[i][u]) { par[i][v] = u; DFS(v, DFS); sz[i][u] += sz[i][v]; } }; DFS(i, DFS); } vector dp(n, vector<long long>(n, -1)); auto Calc = [&](int u, int v, auto&& Calc) -> long long { if (u == v) return 0; else if (dp[u][v] != -1) return dp[u][v]; else return dp[u][v] = 1ll * sz[u][v] * sz[v][u] + max(Calc(u, par[u][v], Calc), Calc(v, par[v][u], Calc)); }; long long ans = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans = max(ans, Calc(i, j, Calc)); cout << ans << "\n"; }
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 fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int main() { long long n; cin>>n; string s; cin>>s; long long i=0,ct=0,ans=0; while (n--) { if(s[i]=='('){ct++;} else if(s[i]==')'){ct--;} if(ct<0 || (ct==0 && s[i]=='(')) { ans++; } i++; } if(ct!=0) { cout<<"-1\n"; } else { cout<<ans<<"\n"; } }
cpp
1310
C
C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1 abac OutputCopyaba InputCopy19 5 1821 aupontrougevkoffice OutputCopyau NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".
[ "binary search", "dp", "strings" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 1005, M = 1000005; int n, m, cnt, lcp[N][N]; ll k, f[N][N], g[N][N]; char s[N]; struct str {int l, r;} a[M]; bool operator< (const str &x, const str &y) { int l1 = x.l, r1 = x.r, l2 = y.l, r2 = y.r; int lp = lcp[l1][l2], len = min(r1 - l1, r2 - l2) + 1; if (lp >= len) return r1 - l1 < r2 - l2; return s[l1 + lp] < s[l2 + lp]; } bool check(int mid) { memset(f, 0, sizeof f); memset(g, 0, sizeof g); for (int i = 0; i <= n + 1; i++) g[i][0] = 1; int len = a[mid].r - a[mid].l + 1; for (int j = 1; j <= m; j++) { for (int i = n; i >= 1; i--) { int lp = lcp[i][a[mid].l]; // 要比 mid 大 if (str{a[mid].l, a[mid].r} < str{i, n}) f[i][j] = g[i + min(len, lp) + 1][j - 1]; // i + min() + 1 是为了大于 } for (int i = n; i >= 1; i--) g[i][j] = min(k, g[i + 1][j] + f[i][j]); // 防止爆 long long } return f[1][m] >= k; } int main() { scanf("%d%d%lld%s", &n, &m, &k, s + 1); for (int i = n; i >= 1; i--) { for (int j = n; j >= 1; j--) { if (s[i] == s[j]) lcp[i][j] = lcp[i + 1][j + 1] + 1; if (j >= i) a[++cnt] = {i, j}; } } sort(a + 1, a + 1 + cnt); int l = 1, r = cnt, ans; while (l <= r) { int mid = l + r >> 1; if (check(mid)) ans = mid, l = mid + 1; else r = mid - 1; } // 因为算的是大于, 所以要加 1 for (int i = a[ans + 1].l; i <= a[ans + 1].r; i++) printf("%c", s[i]); 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; using ll = long long; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll tc = 1; // cin >> tc; while (tc--) { ll n, m, k; cin >> n >> m >> k; vector<ll> v(k); for (auto &x : v) { cin >> x; } vector<vector<ll>> g(n + 1); for (ll a, b, x = 0; x < m; x++) { cin >> a >> b; g[a].push_back(b); g[b].push_back(a); } vector<ll> dist_source(n + 1, 0), dist_terminal(n + 1, 0); auto bfs = [&](vector<ll> &dist, ll node) -> void { vector<bool> visit(n + 1, 0); queue<ll> q; q.push(node); visit[node] = 1; while (!q.empty()) { auto frnt = q.front(); q.pop(); for (auto nbr : g[frnt]) { if (!visit[nbr]) { visit[nbr] = 1; dist[nbr] = dist[frnt] + 1; q.push(nbr); } } } }; bfs(dist_source, 1); bfs(dist_terminal, n); vector<pair<ll, ll>> elem; for (auto x : v) { elem.push_back({dist_source[x], dist_terminal[x]}); } sort(all(elem)); ll res = -1e18; for (ll x = 0; x < elem.size() - 1; x++) { ll dsx = elem[x].first, dtx = elem[x].second; ll dsx1 = elem[x + 1].first, dtx1 = elem[x + 1].second; if (dsx < dsx1) { res = max(res, min(dist_source[n], dtx1 + dsx + 1)); } else { res = max(res, min(dist_source[n], dtx + dsx1 + 1)); } } cout << res << '\n'; } return 0; }
cpp
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
#include <bits/stdc++.h> using namespace std; #define sz(s) (int)(s.size()) #define all(v) v.begin(),v.end() #define clr(d, v) memset(d,v,sizeof(d)) #define ll long long void file() { std::ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); } int main() { file(); int n; cin >> n; vector<int> v(n); for (auto &it: v)cin >> it; for (int i = 0; i < n; i++) { v.push_back(v[i]); } int ans = 0; int cnt = 0; for (auto it: v) { if (it == 1)cnt++; else cnt = 0; ans = max(ans, cnt); } cout << ans; }
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" ]
// Time Limit: 2023-02-13 11:44:50 // Just_Chill #include<bits/stdc++.h> #define int long long #define mod (int)1000000007l #define nl cout<<"\n"; #define pb push_back #define all(a) a.begin(),a.end() #define pii pair<int,int> #define vi vector<int> #define vpi vector<pair<int,int>> #define vvi vector<vector<int>> #define mii map<int,int> #define S second #define F first #define f(i,a,n) for(int i=a;i<n;i++) #define fi(i,n,a) for(int i=n-1;i>=a;i--) #define tcsolve(tcs) while(tcs--) solve(); using namespace std; template<class T,class S> void print(map<T,S> mp) {for(auto it:mp) cout<<it.first<<" "<<it.second<<"\n";} template<class T,class S> void print(map<T,vector<S>> mp) {for(auto it:mp){ cout<<it.first<<"\n"; int l=it.second.size();for(int i=0;i<l;i++) cout<<it.second[i]<<" ";nl;}} template<class T> void print(vector<vector<T>> &v) {int n=v.size(); for(int i=0;i<n;i++){ cout<<"key : "<<i+1<<"\n";cout<<"val : ";for(auto y:v[i]){ cout<<y<<" ";}cout<<"\n\n";}} template <class T> void print(const T & c) {cout<<c<<"\n";} template <class T,class K> void print(const T & c,const K & d) {cout<<c<<" "<<d<<"\n";} template <class T,class A,class N> void print(const T & c,const A & d,const N & e) {cout<<c<<" "<<d<<" "<<e<<"\n";} template <class T> void print(vector<T> & v){int l=v.size();for(int i=0;i<l;i++) cout<<v[i]<<" ";nl;} template <class T,class S> void print(vector<pair<T,S>> & v){int l=v.size();for(int i=0;i<l;i++) cout<<v[i].first<<" "<<v[i].second<<"\n";} #define arrayinput int n;cin>>n;vector<int> a(n);for(int i=0;i<n;i++)cin>>a[i]; void solve() { string s,t;cin>>s>>t; map<char,set<int>> mp; int n=s.length(); f(i,0,n) mp[s[i]].insert(i); int l=t.length(); int prev=-1; int cnt=1; f(i,0,l){ auto it=mp[t[i]].upper_bound(prev); if(mp[t[i]].size()==0){ print(-1);return; } if(it!=mp[t[i]].end()){ prev=*it; } else{ prev=-1;cnt++;i--; } } print(cnt); } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int tcs=1; cin>>tcs; tcsolve(tcs); }
cpp
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
#include <bits/stdc++.h> #define all(x) x.begin(), x.end() #define r_all(x) x.rbegin(), x.rend() #define sz(x)(ll) x.size() #define g_max(x, y) x = max(x, y) #define g_min(x, y) x = min(x, y) #define rsz(a, n) a.resize(n) #define ass(a, n) a.assign(n, 0) #define YES() cout << "YES\n" #define Yes cout << "Yes\n" #define NO() cout << "NO\n" #define No() cout << "No\n" #define endl "\n" #define print(a) for (auto &x: a) cout << x << " "; cout << endl #define print_pair(a) #define FOR(i, fr, to) for (long long i = fr; i <= to; i++) #define RFOR(i, fr, to) for (long long i = fr; i >= to; i--) #define pb push_back #define eb emplace_back #define is insert #define F first #define S second using namespace std; using ll = long long; using ld = long double; using vll = vector<ll>; using vvll = vector<vll>; using vc = vector<char>; using vvc = vector<vc>; using pll = pair<ll, ll>; using vpll = vector<pll>; using vvpll = vector<vpll>; using stkll = stack<ll>; using qll = queue<ll>; using dqll = deque<ll>; using sll = set<ll>; using msll = multiset<ll>; using mll = map<ll, ll>; using vsll = vector<sll>; using sc = set<char>; using pcll = pair<char, ll>; ll dr[] = {0, 1, 0, -1}, dc[] = {-1, 0, 1, 0}; const ll INF = 1e18; ll MOD = 998244353; ll mod_add(ll u, ll v, ll mod = MOD) { u %= mod, v %= mod; return (u + v) % mod; } ll mod_sub(ll u, ll v, ll mod = MOD) { u %= mod, v %= mod; return (u - v + mod) % mod; } ll mod_mul(ll u, ll v, ll mod = MOD) { u %= mod, v %= mod; return (u * v) % mod; } ll mod_pow(ll u, ll p, ll mod = MOD) { u %= mod; if (p == 0) { return 1; } ll v = mod_pow(u, p / 2, mod) % mod; v = (v * v) % mod; return (p % 2 == 0) ? v : (u * v) % mod; } ll mod_inv(ll u, ll mod = MOD) { u %= mod; ll g = __gcd(u, mod); if (g != 1) { return -1; } return mod_pow(u, mod - 2, mod); } ll mod_div(ll u, ll v, ll mod = MOD) { u %= mod, v %= mod; return mod_mul(u, mod_inv(v), mod); } template<class T> vector<T> operator+(vector<T> a, vector<T> b) { a.insert(a.end(), b.begin(), b.end()); return a; } pll operator+(pll a, pll b) { pll ans = {a.first + b.first, a.second + b.second}; return ans; } template<class A, class B> ostream &operator<<(ostream &os, const pair<A, B> &p) { os << p.first << " " << p.second; return os; } template<class A, class B> istream &operator>>(istream &is, pair<A, B> &p) { is >> p.first >> p.second; return is; } template<class T> ostream &operator<<(ostream &os, const vector<T> &vec) { for (auto &x: vec) { os << x << " "; } return os; } template<class T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &x: vec) { is >> x; } return is; } template<class T> ostream &operator<<(ostream &os, const set<T> &vec) { for (auto &x: vec) { os << x << " "; } return os; } template<class A, class B> ostream &operator<<(ostream &os, const map<A, B> d) { for (auto &x: d) { os << "(" << x.first << " " << x.second << ") "; } return os; } template<class A> void read_arr(A a[], ll from, ll to) { for (ll i = from; i <= to; i++) { cin >> a[i]; } } template<class A> void print_arr(A a[], ll from, ll to) { for (ll i = from; i <= to; i++) { cout << a[i] << " "; } cout << "\n"; } template<class A> void print_arr(A a[], ll n) { print_arr(a, 0, n - 1); } template<class A> void set_arr(A a[], A val, ll from, ll to) { for (ll i = from; i <= to; i++) { a[i] = val; } } template<class A> void set_arr(A a[], A val, ll n) { set_arr(a, val, 0, n - 1); } const ll N = 3e5 + 10; ll n, m, k, q; //ll a[N]; string s, s1, s2,s3; void init() { } ll pref[N], vis[N]; ll get_ans() { s = " " + s; FOR(i, 1, n) { ll v = (s[i] == '0') ? 1 : -1; pref[i] =pref[i - 1] + v; } ll cnt_def = 0, cnt = 0; FOR(i, 0, n) { cnt_def += (m == pref[i]); } if (pref[n] == 0) { return (cnt_def > 0) ? -1 : 0; } FOR(i, 0, n) { if (i == 0) { cnt += (m == pref[i]); continue; } cnt += ((m - pref[i]) % pref[n] == 0) && ((m - pref[i]) * pref[n] >= 0); } // print_arr(pref, 1, n); // print_arr(vis, 1, n); // cout << "Ok\n"; return cnt; } void single(ll t_id = 0) { cin >> n >> m >> s; cout << get_ans() << "\n"; } void multiple() { ll t; cin >> t; for (ll i = 0; i < t; i++) { single(i); } } //#endif #if 0 void multiple() { while (cin >> n >> m) { if (n == 0 && m == 0) { break; } single(); } #endif int main(int argc, char *argv[]) { ios_base::sync_with_stdio(false); cin.tie(nullptr); init(); // freopen("feast.in", "r", stdin); // freopen("feast.out", "w", stdout); // freopen("../input.txt", "r", stdin); multiple(); // single(); return 0; };
cpp
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = tuple<ll, ll>; using vi = vector<ll>; using vii = vector<ii>; using vvii = vector<vii>; int n; vi a; vvii t; void build() { t.push_back(vii(n)); for (int i=0; i < n; i++) t[0][i] = {a[i],i}; for (int i=1, k=2; k <= n; i++, k *= 2) { t.push_back(vii(n-k+1)); for (int j = 0; j <= n-k; j++) t[i][j] = min(t[i-1][j], t[i-1][j+k/2]); } } int m(int a, int b) { int d = b-a+1; int i = 0, k = 1; for (; k*2 <= d; i++, k *= 2); return get<1>(min(t[i][a], t[i][b-k+1])); } ii f (int i, int j) { if (i > j) return {0, -1}; if (i == j) return {a[i], i}; int l = m(i, j); ll lsum, li, rsum, ri; tie(lsum, li) = f(i, l-1); lsum += (j-l)*a[l]; tie(rsum, ri) = f(l+1, j); rsum += (l-i)*a[l]; if (lsum > rsum) return {a[l]+lsum, li}; return {a[l]+rsum, ri}; } int main() { cin.tie(0), ios::sync_with_stdio(0); cin >> n; a = vi(n); vi b(n); for (int i = 0; i < n; i++) cin >> a[i]; build(); int k = get<1>(f(0, n-1)); b[k] = a[k]; ll ml = b[k], mr = b[k]; for (int j = k - 1; j >= 0; j--) ml = min(a[j], ml), b[j] = ml; for (int j = k + 1; j < n; j++) mr = min(a[j], mr), b[j] = mr; for (int i = 0; i < n; i++) cout << b[i] << " \n"[i==n-1]; }
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
/// Author : Nguyễn Thái Sơn - Ti20 - THPT chuyên Lương Thế Vinh /// Training VOI 2023 #include<bits/stdc++.h> //#include <ext/pb_ds/assoc_container.hpp> //#include <ext/pb_ds/trie_policy.hpp> //#include <ext/rope> //#pragma GCC optimize("Ofast") //#pragma GCC optimization("unroll-loops, no-stack-protector") //#pragma GCC target("avx,avx2,fma") //using namespace std; //using namespace __gnu_pbds; //using namespace __gnu_cxx; #define fi first #define se second #define TASK "test" #define pb push_back #define EL cout << endl #define Ti20_ntson int main() #define in(x) cout << x << endl #define all(x) (x).begin(),(x).end() #define getbit(x, i) (((x) >> (i)) & 1) #define cntbit(x) __builtin_popcount(x) #define FOR(i,l,r) for (int i = l; i <= r; i++) #define FORD(i,l,r) for (int i = l; i >= r; i--) #define Debug(a,n) for (int i = 1; i <= n; i++) cout << a[i] << " "; cout << endl using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> vii; typedef unsigned long long ull; typedef vector<vector<int>> vvi; int fastMax(int x, int y) { return (((y-x)>>(32-1))&(x^y))^y; } const int N = 2e4 + 5; const int oo = INT_MAX; const int mod = 1e9 + 7; const int d4x[4] = {-1, 0, 1, 0} , d4y[4] = {0, 1, 0, -1}; const int d8x[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, d8y[8] = {0, 1, 1, 1, 0, -1, -1, -1}; int n, a[55][N], m, k; ll dp[55][N]; inline void Read_Input() { cin >> n >> m >> k; FOR(i, 1, n) FOR(j, 1, m) { cin >> a[i][j]; a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + a[i][j]; } } int Get(int x, int y, int xx, int yy) { return a[xx][yy] - a[x - 1][yy] - a[xx][y - 1] + a[x - 1][y - 1]; } struct Segment_Tree { ll st[4 * N + 5], lz[4 * N + 5]; void build(int id, int l, int r, int cur) { lz[id] = 0; if (l == r) { st[id] = dp[cur][l]; return; } int mid = (l + r) >> 1; build(id * 2, l, mid, cur); build(id * 2 + 1, mid + 1, r, cur); st[id] = max(st[id * 2], st[id * 2 + 1]); } void Down(int id) { if (lz[id] == 0) return; lz[id * 2] += lz[id]; lz[id * 2 + 1] += lz[id]; st[id * 2] += lz[id]; st[id * 2 + 1] += lz[id]; lz[id] = 0; } void update(int id, int l, int r, int u, int v, int val) { if (l > v || r < u) return; if (l >= u && r <= v) { st[id] += val; lz[id] += val; return; } int mid = (l + r) >> 1; Down(id); update(id * 2, l, mid, u, v, val); update(id * 2 + 1, mid + 1, r, u, v, val); st[id] = max(st[id * 2], st[id * 2 + 1]); } ll Get(int id, int l, int r, int u, int v) { if (l > v || r < u) return 0; if (l >= u && r <= v) return st[id]; Down(id); int mid = (l + r) >> 1; return max(Get(id * 2, l, mid, u, v), Get(id * 2 + 1, mid + 1, r, u, v)); } }it; inline void Solve() { const int mx = m - k + 1; ll Ans = 0; FOR(i, 1, mx) dp[1][i] = Get(1, i, 1, i + k - 1); if (n > 1) FOR(i, 1, mx) dp[1][i] += Get(2, i, 2, i + k - 1); FOR(i, 2, n) { it.build(1, 1, mx, i - 1); int val = Get(i, 1, i, k); FOR(j, 1, k) { it.update(1, 1, mx, j, j, -val), val -= Get(i, j, i, j); } FOR(j, 1, mx) { dp[i][j] = it.st[1] + Get(i, j, i, j + k - 1); if (i != n) dp[i][j] += Get(i + 1, j, i + 1, j + k - 1); if (j != mx) { // cout << "CHECK " << j << endl; int l = max(1, j - k + 1); // cout << "UPDATE " << l << " " << j << " " << Get(i, j, i, j) << endl; it.update(1, 1, mx, l, j, Get(i, j, i, j)); int cur = j + k; cur = Get(i, cur, i, cur); int r = min(mx, j + k); it.update(1, 1, mx, j + 1, r, -cur); // cout << "UPDATE " << j + 1 << " " << r << " " << -cur << endl; // FOR(k, 1, mx) // cout << it.Get(1, 1, mx, k, k) << " "; cout << endl; } } // FOR(j, 1, mx) // cout << dp[i][j] << " \n"[j == mx]; } cout << *max_element(dp[n] + 1, dp[n] + mx + 1); } Ti20_ntson { // freopen(TASK".INP","r",stdin); // freopen(TASK".OUT","w",stdout); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T = 1; // cin >> T; while (T -- ) { Read_Input(); Solve(); } }
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
// 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
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#include<iostream> #include<cstring> #include<vector> #include<map> #include<queue> #include<unordered_map> #include<cmath> #include<cstdio> #include<algorithm> #include<set> #include<cstdlib> #include<stack> #include<ctime> #define forin(i,a,n) for(int i=a;i<=n;i++) #define forni(i,n,a) for(int i=n;i>=a;i--) #define fi first #define se second using namespace std; typedef long long ll; typedef double db; typedef pair<int,int> PII; const double eps=1e-7; const int N=3e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[N]; int st[32]; void solve() { n=read(); for(int i=1;i<=n;i++) w[i]=read(); for(int i=1;i<=n;i++) { for(int j=0;j<31;j++) { if((w[i]>>j)&1) { st[j]++; } } } int idx=30; while(idx>=0&&st[idx]!=1) idx--; if(idx<0) { for(int i=1;i<=n;i++) printf("%d ",w[i]); }else { int ans=-1; for(int i=1;i<=n;i++) { if((w[i]>>idx)&1) { ans=i; break; } } printf("%d ",w[ans]); for(int i=1;i<=n;i++) if(i!=ans) printf("%d ",w[i]); } } int main() { // init(); // stin(); // scanf("%d",&T); T=1; while(T--) solve(); return 0; }
cpp
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
//______________"In The Name Of GOD"______________ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair <ll, ll> pll; typedef pair <int, int> pii; const int lg = 20; const int mod = 1e9 + 7; const ll inf = 1e9 + 100; const int maxn = 1e6 + 100; #define cl clear #define F first #define S second #define pb push_back #define Sz(x) int((x).size()) #define all(x) (x).begin(), (x).end() int main(){ ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n, m, p, a, b; cin >> n >> m >> p; for (int i = 0; i < n; i ++){ int x; cin >> x; if(x % p) a = i; } for (int i = 0; i < m; i ++){ int x; cin >> x; if(x % p) b = i; } cout << a + b << '\n'; return 0; } /*test case : */
cpp
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <array> #include <unordered_map> #include <unordered_set> #include <iomanip> #include <chrono> #include <random> #define ld long double #define ll long long using namespace std; void solve(){ int n, m, k; cin>>n>>m>>k; k = min(k,m-1); vector<int> arr(n); for(int i=0;i<n;i++) cin>>arr[i]; int rem = m - k-1; int ans = -1e9; for(int l=0;l<=k;l++){ int mn = 1e9; for(int l2=0;l2<=rem;l2++){ int r1 = k-l, r2 = rem-l2; mn = min(mn, max(arr[l+l2], arr[n-r1-r2-1])); // cout<<arr[l+l2]<<" "<<arr[n-(k-l)-(rem-l2)]<<endl; } ans = max(ans,mn); } cout<<ans<<"\n"; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout<<setprecision(15)<<fixed; int t=1; cin >> t; for (int c = 0; c < t; c++) { // cout<<"Case #"<<c+1<<": "; solve(); } }
cpp
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
/*亲爱的上帝,我求你给我力量来赢得这场战斗。*/ #include <bits/stdc++.h> using namespace std ; using i64 = long long; #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << "->"; god(x); cerr << "\n"; #else #define debug(x) #endif void god(i64 UWU) { cerr << UWU;} void god(int UWU) { cerr << UWU;} void god(string UWU) { cerr << UWU;} void god(char UWU) { cerr << UWU;} void god(double UWU) {cerr << UWU;} void god(long double UWU) {cerr << UWU;} template<class T> void god(vector<T> V) {cerr << "["; for(T I:V) {god(I); cerr << " ";} cerr << "]";} void solve() { i64 N, G, B; cin >> N >> G >> B; i64 min_good_days = (N+1) / 2; i64 dx = min_good_days / G * (B + G); dx += ((min_good_days % G)?min_good_days%G:-B); cout << max(N, dx) << "\n"; // i64 max_bad_days = N - min_good_days; // debug(min_good_days); // if(N <= G) { // cout << N << "\n"; // return; // } // i64 dx = ((min_good_days + G - 1) / G); // i64 curr_dx = dx * G; // i64 extra_dx = curr_dx - min_good_days; // i64 dy = (dx - 1) * B; // debug(dx); debug(curr_dx); debug(extra_dx); debug(dy); // i64 fill = 0; // if(extra_dx + dy < max_bad_days) { // fill += (max_bad_days - (extra_dx + dy) + G + B - 1) / (G + B); // } // cout << max(N, curr_dx + dy + fill) << "\n"; } int main() { #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); #endif std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int T; cin >> T; while(T--) { solve(); } return 0; }
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 <iostream> #include <map> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <climits> using namespace std; #define ll long long #define code std::ios::sync_with_stdio(false);::cin.tie(nullptr); bool isPrime(ll n){ if(n < 2) return false; for (ll i = 2; i * i <= n; ++ i) { if (n % i == 0){ return false; } } return true; } int main(){ ll z; cin >> z; while(z--){ string s; cin >> s; ll o = 0; ll k = 0; for(int i = 0;i < s.size()+1;i++){ if(s[i]=='L'){ o++; }else{ k = max(k,o); o = 0; } } cout << k+1 << endl; } }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#include<bits/stdc++.h> using namespace std; #define vt vector #define pb push_back #define ll long long #define sz(x) (int)(x).size #define all(x) (x).begin(),(x).end() #define allb(x) (x).rbegin(),(x).rend() #define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); } void err(istream_iterator<string> it) {} template<typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << endl; err(++it, args...); } const int mxm=1e9+7; const int mx=2e5+5; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; void get_accepted(){ int dp[63]={0}; ll n,m; cin>>n>>m; int a[m]; ll sum=0; for(int i=0;i<m;i++){ cin>>a[i]; sum+=(ll)a[i]; int x=a[i]; int cunt=0; while(x!=1){ x/=2; cunt++; } dp[cunt]++; } if(sum<n){ cout<<"-1\n"; return; } ll r=n; int ans=0; for(int i=0;i<=60;i++){ int e=r%2; r/=2; if(e==1){ if(dp[i]>0){ dp[i]--; goto label; } else{ ans++; int j; for(j=i+1;j<=60;j++){ if(dp[j]>0){ dp[j]--; break; } ans++; } for(int u=i;u<j;u++){ dp[u]++; } } } else{ label: dp[i+1]+=dp[i]/2; } } cout<<ans<<"\n"; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int tt; cin>>tt; // tt=1; while(tt--){ get_accepted(); } }
cpp
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
#include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> using o_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; // 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 template <class key, class value, class cmp = std::less<key>> using o_map = __gnu_pbds::tree<key, value, cmp, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; using i64 = long long; const i64 Mod = 1000000007; const i64 MOD = 998244353; const i64 Inf = 1E18; const int dx[] = {0, 0, 1, -1, -1, -1, 1, 1}; const int dy[] = {1, -1, 0, 0, -1, 1, -1, 1}; //FOR unordered_map<int,int,custom_hash> TO AVOID FALTU TLE'S COZ OF ANTIHASHES. 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); } }; template <typename T> T roundup(T a, T b) { return(a / b + ((a ^ b) > 0 && a % b)); } template <typename T> T choose(T n, T r) { if(n < r) return 0LL; T res = 1; for(T e = 0 ; e < r ; e ++) { res = res * (n - e); res = res / (e + 1); } return res; } template <typename T> bool expotwo(T n) { T val = (n & (n - 1)); if(val == 0LL) return true; return false; } template <typename T> T modexpo(T b, T e, T mod) { T ans = 1; while(e) { if(e & 1) ans = ((ans % mod) * (b % mod)) % mod; b = ((b % mod) * (b % mod)) % mod; e >>= 1; } return ans; } template <typename T> T expo(T b, T e) { T ans = 1; while(e) { if(e & 1) ans = ans * b; b = b * b; e >>= 1; } return ans; } template <typename T> bool eprime(T n) { if(n < 2) return false; for(T e = 2; e * e <= n; e ++) { if(n % e == 0) return false; } return true; } template <typename T> bool eparity(T x, T y) { return !((x & 1) ^ (y & 1)); }; template <typename T> void amax(T& a, T b) { a = max(a, b); } template <typename T> void amin(T& a, T b) { a = min(a, b); } template <typename T> void add(T& a, T b, T M) { a = ((a % M) + (b % M)) % M; } template <typename T> void mul(T& a, T b, T M) { a = ((a % M) * (b % M)) % M; } template <typename T> void sub(T& a, T b, T M) { a = (a - b + M) % M; } /* ------------------------------------------ lessgo -------------------------------------------------*/ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") vector <vector<int>> divisor(20001); void compute() { for(int i = 1; i < 20001; i ++) { for(i64 j = 1; j * j <= i; j ++) { if(i % j == 0) { int cur = j; divisor[i].push_back(cur); if(j * j != i) divisor[i].push_back(i / cur); } } } } void Solution() { int a, b, c; cin >> a >> b >> c; vector <pair<int, int>> operations(20001,{INT_MAX, INT_MAX}); int ans = INT_MAX; array <int, 3> res = {0, 0, 0}; for(int i = 1; i < 20001; i ++) { operations[i].first = abs(b - i); int add = abs(i - a), prev = i; for(auto &x : divisor[i]) { if(add > abs(x - a)) { add = abs(x - a); prev = x; } } operations[i].first += add; operations[i].second = prev; } for(int i = 1; i < 20001; i ++) { for(auto &x : divisor[i]) { if(operations[x].first < INT_MAX) { int k = abs(i - c) + operations[x].first; if(k < ans) { ans = k; res = {operations[x].second, x, i}; } } } } cout << ans << '\n'; cout << res[0] << ' ' << res[1] << ' ' << res[2] << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int Test_case = 1; cin >> Test_case; compute(); while(Test_case --) Solution(); }
cpp
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
#ifdef MY_LOCAL #include "D://competitive_programming/debug/debug.h" #define debug(x) cerr << "[" << #x<< "]:"<<x<<"\n" #else #define debug(x) #endif #define REP(i, n) for(int i = 0; i < n; i ++) #define REPL(i,m, n) for(int i = m; i < n; i ++) #define SORT(arr) sort(arr.begin(), arr.end()) #define LSOne(S) ((S)&-(S)) #define M_PI 3.1415926535897932384 #define INF 1e18 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef long long ll; #define int ll typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; typedef double ld; typedef tree<int,null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ost; // assume n is odd.... map<int, vi> ask(int l, int r) { int ln = r - l+1; int totc = ln*(ln+1)/2; cout<<"? "<<l+1<<" "<<r+1<<endl; map<int,vi> mp; REP(i, totc) { string s;cin>>s; int l = s.size(); if (mp.find(l) == mp.end()) { mp[l] = vi(26,0); } for (auto x: s) { mp[l][x - 'a']++; } } return mp; } vi mins(vi v1, vi v2) { vi res(26); REP(i, 26) { res[i] = v1[i] - v2[i]; }return res; } vi unflatten(vi &arr) { vi cur; REP(i, 26) { REP(j, arr[i]) { cur.push_back(i); } } return cur; } vector<tuple<int,int,vi>> getedges(int n, int offset = 0) { vector<tuple<int,int,vi>> edges; map<int, vi> mp = ask(offset, n-1 + offset); if (n == 1) { edges.push_back({offset,offset, unflatten(mp[1])});return edges; } if (n == 2) { edges.push_back({offset,offset+1, unflatten(mp[1])});return edges; } //debug(mp); int mid = (n%2==1); vi tominus; if (mid) { int md = n/2; vi res(n,-1); vi curres = mins(mp[md+1], mp[md+2]); REP(i, 26) { if (curres[i] == 1) { res[md] = i; edges.push_back({offset+md,offset+md,{i}}); break; } } tominus.push_back(res[md]); } int curln, curL, curR; if (mid) { curln = n/2+2; curL = n/2-1; curR = n/2+1; } else { curln = n/2+1; curL = n/2-1; curR = n/2; } while (curL != 0) { vi cres = mins(mp[curln], mp[curln+1]); //debug(cres); //debug(curln); for (auto x: tominus) { cres[x]--; } //debug(cres); vi cc = unflatten(cres); edges.push_back({offset+curR, offset+curL, cc}); for (auto x: cc) { tominus.push_back(x); } curL--; curR++; curln++; } vi curr = mp[n]; REP(i, 26) { curr[i] *= 2; } curr = mins(curr, mp[n-1]); edges.push_back({offset, offset+n-1, unflatten(curr)}); return edges; } string trysolve(int n) { if (n == 1) { cout<<"? "<<1<<" "<<1<<endl; string s;cin>>s; return s; } vector<tuple<int,int,vi>> e1; vector<tuple<int,int,vi>> e2; vector<tuple<int,int,vi>> e3; if (n%2 == 0) { e1 = getedges(n-1); int ln = n/2; e2 = getedges(ln); e3 = getedges(ln, n - ln); } else { e1 = getedges(n); int ln = n/2; e2 = getedges(ln); e3 = getedges(ln+1, n-ln-1); } vi res(n,-1); queue<int> q; vector<vector<pair<int,vi>>> adj(n); auto process = [&](vector<tuple<int,int,vi>> &ee) { for (auto &[a,b, cc]: ee) { if (cc.size() == 1) { q.push(a); res[a] = cc[0]; } else { adj[a].push_back({b, cc}); adj[b].push_back({a, cc}); } } }; process(e1);process(e2);process(e3); while (!q.empty()) { auto u = q.front();q.pop(); for (auto &[v,tt]: adj[u]) { if (res[v] != -1) continue; if (tt[0] == res[u]) { res[v] = tt[1]; } else { res[v] = tt[0]; } q.push(v); } } string s; for (auto x: res) { s += (char)('a' + x); }return s; } signed main() { int n;cin>>n; string res = trysolve(n); cout<<"! "<<res<<endl; }
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() { int length; string S; cin >> length >> S; int lefts = 0, rights = 0; for(int i = 0; i < length; i++) { switch(S[i]) { case 'L' : lefts++; break; case 'R' : rights++; break; } } int answer = (lefts + rights + 1); cout << answer << "\n"; return 0; }
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 <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ int x,k; string s;cin>>x>>k>>s; int a[k]; for(int i=0;i<k;i++)cin>>a[i]; sort(a,a+k); map<char,int>mp; int j=k-1; for(int i=x-1;i>=0;i--){ while(a[j]>=i+1&&j>=0)j--; mp[s[i]]+=k-j; } for(char p='a';p<='z';p++)cout<<mp[p]<<" "; cout<<"\n"; } return 0; }
cpp
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; int main() { long long t;cin>>t; while(t--) { map<long long,long long> mp; long long n;cin>>n; vector<long long> v(n); long long s1=0,sum=0; long long maxi= LONG_LONG_MIN; long long neg=0; for(long long i=0;i<n;i++) { cin>>v[i]; s1+=v[i]; sum+=v[i]; if(maxi<=sum) { mp[sum]++; maxi=sum; } if(sum<0) { sum=0; neg++; } else if(sum==0) neg++; } // cout<<maxi<<"\n"; // cout<<mp[maxi]<<"\n"; if(s1==maxi && neg==0 && mp[maxi]==1) cout<<"YES\n"; else if(s1>maxi) cout<<"YES\n"; else cout<<"NO\n"; } }
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include<bits/stdc++.h> using namespace std; int n; vector<int> v[1005]; int vis[1005]={0}; int dfs(int a) { vis[a]=1; for(auto i:v[a]) { if(!vis[i]) return dfs(i); } return a; } int main() { //int n; //vector<int> v[n]; cin>>n; for(int i=1;i<n;i++) { int u,k; cin>>u>>k; v[u].push_back(k); v[k].push_back(u); } int x=0,y=0,r=1; while(1) { x=dfs(r); y=dfs(r); if(x==r) break; cout<<"? "<<x<<" "<<y<<endl; cin>>r; } cout<<"! "<<r<<endl; }
cpp
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
[ "dfs and similar", "dp", "graphs", "trees" ]
#include <bits/stdc++.h> #define ll long long #define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); using namespace std; const int N = 2e5 + 10; const int inf = 0x3f3f3f3f; int head[N], nex[N << 1], to[N << 1], cnt=1; int dp[N], a[N], n; //cnt:start from 1,no need to memset (-1) void add(int x, int y) { to[cnt] = y; nex[cnt] = head[x]; head[x] = cnt++; } void dfs1(int rt, int fa) { if(a[rt] == 0) dp[rt] = -1;//设置dp数组的初值 else dp[rt] = 1; for(int i = head[rt]; i; i = nex[i]) { if(to[i] == fa) continue; dfs1(to[i], rt); dp[rt] = max(dp[rt], dp[rt] + dp[to[i]]);//两种选择,与其子树连接或者不连接。 } } void dfs2(int rt, int fa) { for(int i = head[rt]; i; i = nex[i]) { if(to[i] == fa) continue; dp[to[i]] = max(dp[to[i]], dp[to[i]] + dp[rt] - max(dp[to[i]], 0)); //这个的de[rt] - max(dp[to[i]], 0),表示的意思是:如果这个节点在上一躺的dfs中选择了这个儿子节点那么这个点一定是正数,如果这个点是负数,那么他在上一躺就没有被选择到,所以我们不需要减去这个点的值。 dfs2(to[i], rt); } } int main() { cin>>n; int x,y; for(int i = 1; i <= n; i++) cin>>a[i]; for(int i = 1; i < n; i++) { cin>>x>>y; add(x, y); add(y, x); } dfs1(1, -1); dfs2(1, -1); for(int i = 1; i <= n; i++) printf("%d%c", dp[i], i == n ? '\n' : ' '); return 0; }
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> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define mod 1000000007 #define ll long long int #define endl '\n' #define mem(a,x) memset(a,x,sizeof(a)) #define EPS 1e-12 #define double long double using namespace std; using namespace __gnu_pbds; typedef tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds; //cout << "0th element: " << *A.find_by_order(0) << endl; //cout << "No. of elems smaller than 6: " << A.order_of_key(6) << endl; //priority_queue <int, vector<int>, greater<int>> ll pow1(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod;}else{b--;ans=(ans*a)%mod;}}return ans;} ll mod1=1e9+9; ll pow2(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod1;}else{b--;ans=(ans*a)%mod1;}}return ans;} ll lcm(ll a,ll b) { return (a*b)/__gcd(a,b); } const int N=1e7+2; void solve() { ll i,a,b,j,n; cin>>n; vector<pair<ll,ll> >v; ll ar[n+2]; for(i=1;i<=n;i++) { cin>>ar[i]; } for(i=1;i<=n;i++) { v.push_back({ar[i],1}); int sz=v.size(); while(sz>1&&v[sz-1].first*v[sz-2].second<v[sz-1].second*v[sz-2].first) { pair<ll,ll>p={v[sz-1].first+v[sz-2].first,v[sz-1].second+v[sz-2].second}; v.pop_back(); v.pop_back(); v.push_back(p); sz--; } } cout<<setprecision(9)<<fixed; for(i=0;i<v.size();i++) { double val1=v[i].first; double val2=v[i].second; for(j=0;j<v[i].second;j++) { cout<<val1/val2<<endl; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; t=1; int cs=1; //cin>>t; while (t--) { //cout<<"Case "<<cs<<": "; solve(); cs++; } }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <iostream> using namespace std; int main(){ int n,m; cin >> n >> m; string a[n],b[m]; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < m; i++) cin >> b[i]; int q,t; cin >> q; while(q--){ cin >> t; t--; cout << a[t % n] + b[t % m] << endl; } }
cpp
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
/* Bismillahir Rahmaneer Raheem Rabbi Zidni Ilmah Assalamu wala Manittaba Al huda */ #include<bits/stdc++.h> #define ll long long using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("C:/Users/Mehrab Evan/Desktop/input.txt", "r", stdin); freopen("C:/Users/Mehrab Evan/Desktop/output.txt", "w", stdout); #endif ll t; cin >> t; while(t --) { ll n; cin >> n; cout << 1 << " " << n-1 << 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 mod 1000000007 /*bool isprime(int n){ for (int i=2;i*i<=n;i++){ if (n%i==0) return 0; } return 1; }*/ bool cmp(long long a, long long b){ return a>b; } int main() { long long n,x=0,y; cin >> n; y=n-2; for (int i=2;i<n;i++){ long long faken=n; while (faken){ x+=faken%i; faken/=i; } } cout << x/__gcd(x,y) << "/" << y/__gcd(x,y); }
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 <iostream> #include <algorithm> // #include <vector> // #include <iomanip> // #include <string> #include <bits/stdc++.h> // #include <math.h> #define ll long long int // #define ull unsigned long long int // #define int int64_t #define vi vector<ll> #define map map<ll, ll> #define vii vector<pair<ll, ll>> #define vs vector<string> #define vc vector<char> // #define vb vector<bool> #define pb push_back #define vvi vector<vector<ll>> #define pii pair<ll, ll> // #define mp make_pair // #define all(x) (x).begin(), (x).end() // #define vin(x, v) \ // for (auto& x : v) cin >> x; // #define vout(x, v) \ // for (auto x : v) cout << x << " "; // #define MEM(a, b) memset(a, (b), sizeof(a)) #define forll for (ll i = 0; i < n; i++) #define form for (auto it : m) // #define MP make_pair #define endl "\n" // #define INF (int)1e18 // #define EPS 1e-18 // #define PI 3.1415926535897932384626433832795 // #define MOD 1000000007 // #define MODD 998244353 #define isortarry(arr, n) sort(arr, arr + n) #define dsortarry(arr, n) sort(arr, arr + n, greater<int>()) #define isortstring(str) sort(str.begin(), str.end()) #define dsortstring(str) sort(str.begin(), str.end(), greater<char>()) #define lowtrans(str) transform(str.begin(), str.end(), str.begin(), ::tolower) #define uptrans(str) transform(str.begin(), str.end(), str.begin(), ::toupper) #define isortvec(v, n) sort(v.begin(), v.end()) #define dsortvec(v, n) sort(v.begin(), v.end(), greater<ll>()) #define cin(v, u) \ for (ll i = 0; i < u; ++i) \ { \ ll x; \ cin >> x; \ v.pb(x); \ } #define tc \ ll t; \ cin >> t; \ while (t--) // cout<<fixed<<setprecision(15)<< using namespace std; int digits(ll n) { int k = 0; while (n > 0) { n = n / 10; k++; } return k; } ll gcd(ll a, ll b) { if (b == 0) return a; else return gcd(b, a % b); } ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); } ll power(ll a, ll b) { ll sum = 1; while (b > 0) { sum = sum * a; b--; } return sum; } ll ncr(ll n, ll r) { ll ans = 1; for (ll i = n; i > n - r; i--) { ans *= i; } for (ll i = r; i >= 1; i--) { ans /= i; } return ans; } ll nc2(ll n) { return (n * (n - 1)) / 2; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void sum() { ll n; cin >> n; vi v; cin(v, n); map m; vi a; forll { m[v[i]]++; } forll { a.pb(v[i]); ll x = v[i] + 1; while (1) { if (m[x] >= 1) { x++; // a.pb(x); // m[x]++; // break; } else { a.pb(x); m[x]++; break; } } } vi b = a; ll y = 0; isortvec(b, b.size()); for (ll i = 0; i < 2 * n; ++i) { if (b[i] == i + 1) { y++; } } if (y == 2 * n) { for (ll i = 0; i < 2 * n; ++i) { cout << a[i] << " "; } cout << endl; } else { cout << -1 << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); tc { sum(); } return 0; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include <bits/stdc++.h> #define up(i, j, n, k) for (int i = j; i <= n; i += k) #define dw(i, j, n, k) for (int i = j; i >= n; i -= k) #define int long long using namespace std; typedef pair<int, int> PII; const int mod = 998244353; const int mn = 2e6 + 1000; const int INF = 0x3f3f3f3f; const int LINF = 9223372036854775806; void solve() { int n, m; cin >> n >> m; int ans = n * (n + 1) / 2; int x = (n - m) / (m + 1); int y = (n - m) % (m + 1); if (y == 0) ans -= x * (x + 1) * (m + 1) / 2; else ans -= (x * (x + 1) * (m + 1 - y) / 2 + y * (x + 1) * (x + 2) / 2); cout << ans << "\n"; } signed main() { std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); int t; t = 1; cin >> t; while (t --) solve(); return 0; }
cpp