contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
listlengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
#include <bits/stdc++.h> #define fr first #define sc second #define pb push_back #define ll long long #define maxheap priority_queue<int> #define minheap priority_queue<int,vector<int>,greater<int>> //const double pi = acos(-1.0); const double eps = 1e-10; #define all(x)(x).begin(), (x).end() using namespace std; const int N = 5e3 + 10; const ll MOD = 1e9 + 7; int a[N], total[N]; int n, m; vector <int> color[N]; int pref[N][N], g[N][N]; void solve(){ cin >> n >> m; for (int i = 1; i <= n; i++){ cin >> a[i]; total[a[i]]++; for (int j = 1; j <= n; j++){ pref[j][i] += pref[j][i - 1]; } pref[a[i]][i]++; } for (int i = 1; i <= m; i++){ int f, h; cin >> f >> h; color[f].pb(h); } for (int i = 1; i <= n; i++){ sort(all(color[i])); for (int h : color[i]){ g[i][h]++; } for (int j = 1; j <= n; j++){ g[i][j] += g[i][j - 1]; } } ll ans1 = 0; ll ans2 = 0; for (int posL = 0; posL <= n; posL++){ ll ans = 1; int cntAns = 0; for (int i = 1; i <= n; i++){ if (i == a[posL]){ bool ok = false; int cntR = 0; for (int h : color[i]) if (h == pref[i][posL]) ok = true; else if (h <= total[i] - pref[i][posL]) cntR++; if (ok == false) ans = 0; else{ if (cntR == 0) cntAns++; else cntAns += 2, ans *= cntR; } }else{ int l = pref[i][posL]; int r = total[i] - l; if(g[i][l] * g[i][r] - g[i][min(l, r)] > 0){ cntAns += 2; ans *= 1ll * g[i][l] * g[i][r] - g[i][min(l, r)]; }else if(g[i][l] > 0 || g[i][r] > 0){ cntAns++; ans *= g[i][l] + g[i][r]; } } ans %= MOD; } if (cntAns == ans1){ ans2 = (ans2 + ans) % MOD; }else if (cntAns > ans1){ ans1 = cntAns; ans2 = ans; } } cout << ans1 << " " << ans2 << endl; } int main(){ ios::sync_with_stdio(NULL), cin.tie(0), cout.tie(0); cout.setf(ios::fixed), cout.precision(20); //freopen("input.txt", "r", stdin);//freopen("output1.txt", "w", stdout); //freopen("bonus.in","r",stdin); freopen("bonus.out", "w", stdout); int step; step = 1; //cin >> step; for (int i = 1; i <= step; i++){ solve(); } }
cpp
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
#include <iostream> #include <bits/stdc++.h> using namespace std; #define debug(x) cout<<#x<<" :: "<<x<<endl; #define debug2(x,y) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<endl; #define debug3(x,y,z) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<endl; #define boost ios::sync_with_stdio(0); cin.tie(0) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef unsigned long long ull; #define YES cout<<"YES"<<"\n"; #define NO cout<<"NO"<<"\n"; /***************************************************************************/ const int N= 2e5+1; int n; std::vector<pair<int,int>> graph[N]; int colour[N]; int cols[N]; void dfs(int vertex,int num,int par=0){ int col=1; cols[num]=-1; int i=1; for(auto p: graph[vertex]){ int x=p.fi,in= p.se; if(x==par) continue; if(cols[i]==-1) i++; colour[in]= cols[i++]; } cols[num]=num; for(auto p: graph[vertex]){ int x=p.fi,in= p.se; if(x==par) continue; dfs(x,colour[in],vertex); } return; } int main(){ boost; int k; cin>>n>>k; for(int i=0;i<n-1;i++){ int u,v; cin>>u>>v; graph[u].push_back({v,i}); graph[v].push_back({u,i}); } int sizes[n]; for(int i=0;i<n;i++){ sizes[i]= graph[i+1].size(); } sort(sizes,sizes+n); int greater=0,last=sizes[n-1]; int ans=n-1; int curr_freq=0; // for(int i=0;i<n;i++){ // cout<<sizes[i]<<" "; // } // cout<<"\n"; for(int i=n-1;i>=0;i--){ if(last>sizes[i]) greater++; else{ if(i!=n-1) curr_freq++; } if(last!=sizes[i]){ greater+= curr_freq; curr_freq=0; } if(greater>k){ break; } last=sizes[i]; ans=sizes[i]; } cout<<ans<<"\n"; int num=1; for(int i=1;i<=n+1;i++){ cols[i]=num; num++; num%=ans; if(num==0) num=ans; } dfs(1,0); for(int i=0;i<n-1;i++){ cout<<colour[i]<<" "; } cout<<"\n"; }
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> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define el "\n" #define matrix vector<vector<int>> #define pt complex<ld> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; const ll N = 2e5 + 7, LOG = 20; const ld pi = acos(-1); const ll mod = 1e9 + 7; int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; ll n, m, k, x, y; int a[N]; void dowork() { cin >> n; int ans = 0, cnt = 0; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i <= n; i++) { if (a[i]) { cnt++; } else { cnt = 0; } ans = max(ans, cnt); } for (int i = 1; i <= n; i++) { if (a[i]) { cnt++; } else { break; } ans = max(ans, cnt); } ans = min(ans, (int) n); cout << ans << el; } int main() { fast //freopen("cowland.in", "r", stdin); //freopen("cowland.out", "w", stdout); int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { dowork(); } }
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
//ANY TIME YOU SEE OPTIMIZATION PROBLEM -> BINARY SEARCH THE ANSWER!!! #include <bits/stdc++.h> using namespace std; #define ll long long #define No cout<<"No"<<endl; #define NO cout<<"NO"<<endl; #define Yes cout<<"Yes"<<endl; #define YES cout<<"YES"<<endl; #define MOD 1000000007 #define endl '\n' void solve() { //PIGEON - HOLE PRINCIPLE ll n, i, j, a[200005], pro = 1, m; cin>>n>>m; for(i=0;i<n;i++) { cin>>a[i]; } if(n<=m) { for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { ll p = abs(a[i] - a[j]); pro = (pro * (p%m))%m; } } cout<<pro<<endl; } else { cout<<0<<endl; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //int t; cin>>t; //while(t--) solve(); }
cpp
1290
D
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "constructive algorithms", "graphs", "interactive" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; #define all(x) (x).begin(),(x).end() #define X first #define Y second #define sep ' ' #define debug(x) cerr << #x << ": " << x << endl; const ll MAXN = 1e6 + 10; int n, k; vector<int> B[MAXN]; set<pll> st; inline bool ask(int x) { cout << "? " << x << endl; string ans; cin >> ans; return ans == "Y"; } inline void R() { cout << "R" << endl; } inline vector<int> hamiltonian_path(int n, int i) { vector<int> path; for (int j = 0; j < n; j++) path.push_back((i + (j & 1 ? -1 : 1) * ((j + 1) / 2) + n) % n); return path; } int main() { cin >> n >> k; if (n == 1 && k == 1) return cout << "! 1" << endl, 0; if (n == k) { int ans = 0; for (int i = 1; i <= n; i++) ans += (!ask(i)); return cout << "! " << ans << endl, 0; } if (k > 1) k /= 2; for (int i = 0; i < n / k; i++) { for (int j = 1; j <= k; j++) { int x = i * k + j; if (!ask(x)) B[i].push_back(x); } } R(); for (int i = 0; i < n / k / 2; i++) { vector<int> path = hamiltonian_path(n / k, i); for (int e : path) for (int j = B[e].size() - 1; j >= 0; j--) if (ask(B[e][j])) B[e].erase(B[e].begin() + j); for (int i = 1; i < path.size(); i++) st.insert({min(path[i], path[i - 1]), max(path[i], path[i - 1])}); R(); } int ans = 0; for (int i = 0; i < n / k; i++) ans += B[i].size(); cout << "! " << ans << endl; return 0; }
cpp
1290
E
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5 2 4 1 5 3 OutputCopy1 3 6 8 11 InputCopy6 1 2 4 5 6 3 OutputCopy1 3 6 8 12 17 NoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.
[ "data structures" ]
#include<bits/stdc++.h> #define ll long long #define ls u<<1 #define rs u<<1|1 #define mm(x) memset(x,0,sizeof(x)) using namespace std; int read() { int a=0;int f=0;char p=getchar(); while(!isdigit(p)){f|=p=='-';p=getchar();} while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();} return f?-a:a; } const int INF=998244353; const int P=998244353; const int N=1e6+5; int T; int n,m; int val[N]; ll ans[N]; int pos[N]; bool cmp(int a,int b) { return val[a]<val[b]; } int cnt[N]; int mn[N],mnn[N],tag1[N],tag2[N]; int tot[N]; ll sum[N]; void update(int u,int X,int Y) { if(!tot[u]) return ; mn[u]+=Y; mnn[u]+=Y; tag1[u]+=Y; tag2[u]+=Y; sum[u]+=(ll)tot[u]*Y; if(mn[u]>=X) return ; sum[u]=sum[u]+(ll)cnt[u]*(X-mn[u]); mn[u]=X; tag1[u]=max(X,tag1[u]);//X; } void pushdown(int u) { update(ls,tag1[u],tag2[u]); update(rs,tag1[u],tag2[u]); tag1[u]=tag2[u]=0; } void pushup(int u) { cnt[u]=0; tot[u]=tot[ls]+tot[rs]; sum[u]=sum[ls]+sum[rs]; mn[u]=min(mn[ls],mn[rs]); mnn[u]=min(mnn[ls],mnn[rs]); if(mn[u]==mn[ls]) cnt[u]+=cnt[ls]; else mnn[u]=min(mnn[u],mn[ls]); if(mn[u]==mn[rs]) cnt[u]+=cnt[rs]; else mnn[u]=min(mnn[u],mn[rs]); } void build(int u,int l,int r) { sum[u]=0; mn[u]=mnn[u]=INF; tag1[u]=tag2[u]=cnt[u]=tot[u]=0; if(l==r) return ; int mid=(l+r)>>1; build(ls,l,mid); build(rs,mid+1,r); } int query(int u,int l,int r,int X) { if(l==r) { mn[u]=0; cnt[u]=tot[u]=1; return 1; } int mid=(l+r)>>1; pushdown(u); int res=0; if(X<=mid) res=query(ls,l,mid,X); else res=tot[ls]+query(rs,mid+1,r,X); pushup(u); return res; } void modify1(int u,int l,int r,int L,int R,int X) { if(L<=l&&r<=R) { update(u,0,X); return ; } int mid=(l+r)>>1; pushdown(u); if(L<=mid) modify1(ls,l,mid,L,R,X); if(R>mid) modify1(rs,mid+1,r,L,R,X); pushup(u); } void modify2(int u,int l,int r,int L,int R,int X) { if(L<=l&&r<=R) { if(!tot[u]) return ; if(mn[u]>=X) return ; if(mnn[u]>=X) { update(u,X,0); return ; } int mid=(l+r)>>1; pushdown(u); modify2(ls,l,mid,L,R,X); modify2(rs,mid+1,r,L,R,X); pushup(u); } int mid=(l+r)>>1; pushdown(u); if(L<=mid) modify2(ls,l,mid,L,R,X); if(R>mid) modify2(rs,mid+1,r,L,R,X); pushup(u); } void solve() { for(int i=1;i<=n;++i) pos[i]=i; sort(pos+1,pos+n+1,cmp); build(1,1,n); for(int i=1;i<=n;++i) { int now=pos[i]; int pre=query(1,1,n,now); if(now!=n) { modify1(1,1,n,now+1,n,1); modify2(1,1,n,now+1,n,pre); } ans[i]-=sum[1]; } } int main() { n=read(); for(int i=1;i<=n;++i) ans[i]=(ll)i*i; for(int i=1;i<=n;++i) val[i]=read(); solve(); reverse(val+1,val+n+1); solve(); for(int i=1;i<=n;++i) printf("%lld\n",ans[i]); return 0; }
cpp
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
#include <bits/stdc++.h> #define int long long using namespace std; const int inf = 1e9; const int maxn = 3e5 + 10; typedef pair<int,int> ii; #define ff first #define ss second int n,m,k; vector <int> adj[maxn],b[maxn]; int a[maxn]; ii e[maxn]; int ans=0; ii p[maxn],num[maxn]; int s[maxn]; ii get(int x) { if (p[x].ff!=x) { ii temp = get(p[x].ff); p[x].ff=temp.ff; p[x].ss^=temp.ss; } return p[x]; } void hop(int x, int y, int w) { ii xx = get(x); ii yy = get(y); x=xx.ff; y=yy.ff; // cout<<x<<' '<<y<<' '<<w<<"!!\n";; if (x==y) return; if (s[x]>s[y]) { swap(x,y); swap(xx,yy); } ans -= min(num[x].ff,num[x].ss); ans -= min(num[y].ff,num[y].ss); int val = (xx.ss^yy.ss^w); if (val==0) { num[y].ff+=num[x].ff; num[y].ss+=num[x].ss; } else { num[y].ff+=num[x].ss; num[y].ss+=num[x].ff; } p[x]={y,val}; s[y]+=s[x]; ans+=min(num[y].ff,num[y].ss); } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin>>n>>k; for (int i=1; i<=n; i++) { char c; cin>>c; a[i]=(c=='1'); } for (int i=1; i<=k; i++) { int m; cin>>m; while (m--) { int x; cin>>x; b[x].push_back(i); } } for (int i=1; i<=k; i++) { p[i]={i,0}; s[i]=1; num[i]={1,0}; } for (int i=1; i<=n; i++) { if (b[i].size()==2) { int u=b[i][0]; int v=b[i][1]; hop(u,v,a[i]^1); } else if (b[i].size()==1) { int u=b[i][0]; ii uu=get(u); u=uu.ff; ans-=min(num[u].ff,num[u].ss); if (uu.ss==(a[i]^1)) num[u].ff+=inf; else num[u].ss+=inf; ans+=min(num[u].ff,num[u].ss); } cout<<ans<<'\n'; } }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define oo 1000000010 #define mod 1000000007 const int N = 510 , LOG = 10; char grid[N][N]; int val[N][N] , sum[N][N][4]; int st[N][N][LOG][LOG] , lg[N]; int n , q , m , r1 , c1 , r2, c2 , nr , nc; string S = "RGYB"; int dr[4] = {0 , 0 , 1 , 1}; int dc[4] = {0 , 1 , 0 , 1}; inline bool check(int r1,int c1,int r2,int c2,int k){ r1++,c1++,r2++,c2++; return ((sum[r2][c2][k] - sum[r1 - 1][c2][k] - sum[r2][c1 - 1][k] + sum[r1 - 1][c1 - 1][k]) == (r2 - r1 + 1) * (c2 - c1 + 1)); } inline bool can(int r,int c,int s){ if(r < 0 || c < 0) return false; if(r + (s << 1) - 1 >= n || c + (s << 1) - 1 >= m) return false; for(int i =0 ;i < 4;i++){ nr = r + dr[i] * s ; nc = c + dc[i] * s; if(!check(nr , nc , nr + s - 1 , nc + s - 1 , i)) return false; } return true; } void build(){ lg[1] = 0; for(int i = 2;i<N;i++){ lg[i] = lg[i - 1]; if((1 << (lg[i] + 1)) == i) lg[i]++; } for(int k = 1;k < LOG;k++){ for(int i=0;i + (1 << k) <= n;i++){ for(int j=0;j<m;j++){ st[i][j][k][0] = max(st[i][j][k - 1][0] , st[i + (1 << (k - 1))][j][k - 1][0]); } } } for(int l = 1;l < LOG;l++){ for(int k = 0;k < LOG;k++){ for(int i=0;i+(1 << k) <= n;i++){ for(int j = 0;j + (1 << l) <= m;j++){ st[i][j][k][l] = max(st[i][j][k][l - 1] , st[i][j + (1 << (l - 1))][k][l-1]); } } } } } int a , b; inline int getmax(int r1,int c1,int r2,int c2){ if(r2 < r1 || c2 < c1 || r1 < 0 || r2 >= n || c1 < 0 || c2 >= m) return -oo; a = lg[(r2 - r1) + 1]; b = lg[(c2 - c1) + 1]; return max(max(st[r1][c1][a][b] , st[r2 - (1 << a) + 1][c1][a][b]) , max(st[r1][c2 - (1 << b) + 1][a][b] , st[r2 - (1 << a) + 1][c2 - (1 << b) + 1][a][b])); } int main(){ scanf("%d%d%d",&n,&m,&q); for(int i=0;i<n;i++){ scanf(" %s",grid[i]); for(int j=0;j<m;j++){ for(int k=0;k<4;k++){ sum[i + 1][j + 1][k] = sum[i][j + 1][k] + sum[i + 1][j][k] - sum[i][j][k] + (S[k] == grid[i][j]); } } } int low , high , mid , res; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ low = 1 , high = min(min(i + 1,n - i) , min(j + 1,m - j)); while(high >= low){ mid = ((low + high) >> 1); if(can(i - mid + 1,j - mid + 1,mid)) st[i][j][0][0] = mid, low = mid + 1; else high = mid - 1; } } } build(); while(q--){ scanf("%d%d%d%d",&r1,&c1,&r2,&c2); r1--,c1--,r2--,c2--; low = 1 , high = (n >> 1) , res = 0; while(high >= low){ mid = ((low + high) >> 1); if(getmax(r1 + mid - 1,c1 + mid - 1,r2 - mid , c2 - mid) >= mid) res = mid, low = mid + 1; else high = mid - 1; } printf("%d\n",res * res * 4); } return 0; }
cpp
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
#include <bits/stdc++.h> #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-6; const ll MAX_N = 202020; const ll mod = 1e9 + 7; // 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; } vll adj[MAX_N]; ll dis[MAX_N], dup[MAX_N]; void bfs(ll start) { INF(dis); dis[start] = 0; queue<ll> q; q.push(start); while(sz(q)) { queue<ll> qq; while(sz(q)) { auto u = q.front(); q.pop(); for(auto& v : adj[u]) { if(dis[u] + 1 < dis[v]) { dis[v] = dis[u] + 1; qq.push(v); } else if(dis[u] + 1 == dis[v]) { dup[v] = true; } } } swap(q,qq); } } vll solve(ll n, vpll E, vll seq) { rep(i,0,sz(E)) { auto [u,v] = E[i]; adj[v].push_back(u); } bfs(seq.back()); ll res = 0, fix = 0; rep(i,0,sz(seq) - 1) { ll u = seq[i], v = seq[i+1]; if(dis[u] - 1 != dis[v]) res += 1; else if(dup[u]) fix += 1; } return {res, res + fix}; } int main() { Code By Sumfi cout.precision(12); ll tc = 1; //in(tc); rep(i,1,tc+1) { ll n,m,q; in(n,m); vpll A(m); readvp(A); in(q); vll B(q); readv(B); printv(solve(n,A,B)); } return 0; }
cpp
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
/// Do the solution on the paper #include <bits/stdc++.h> using namespace std; #define int long long #define rep(i, n) for(int i = 0;i < n;++i) #define FOR(i, l, r) for(int i = l; i <= r; ++i) #define FOD(i, r, l) for(int i = r; i >= l; --i) #define dem(x) __builtin_popcount(x) #define endl '\n' #define all(a) (a).begin(), (a).end() #define pb emplace_back #define SZ(x) (int)((x).size()) #define fi first #define se second typedef pair<int,int> ii; //const int dx[4] = {-1, 0, 0, 1}; //const int dy[4] = {0, -1, 1, 0}; //const int base = 311; const int mod = 1e9 + 7; const int N = 5e3 + 5; int n, m, s[N], l[N], r[N], cntL[N], cntR[N]; int f[N], h[N], cntB[N], ans1, ans2 = 1; vector<int> pos[N]; signed main(){ ios::sync_with_stdio(false); cin.tie(0); if(fopen("c.inp", "r")){ freopen("c.inp", "r", stdin); // freopen("c.out", "w", stdout); } cin >> n >> m; FOR(i, 1, n)cin >> s[i], pos[s[i]].pb(i); FOR(i, 1, m){ cin >> f[i] >> h[i]; if(SZ(pos[f[i]]) >= h[i]){ l[i] = pos[f[i]][h[i]-1]; r[i] = pos[f[i]][SZ(pos[f[i]])-h[i]]; } } FOR(t, 0, n){ int res1 = 0, res2 = 1; if(t){ int id = -1; FOR(i, 1, m)if(l[i] == t)id = f[i]; if(id == -1)continue; int cnt = 0; FOR(i, 1, m)if(f[i] == id && l[i] != t && r[i] > t)cnt++; res1++; if(cnt){ res1++; res2 = cnt; } } memset(cntL, 0, sizeof cntL); memset(cntR, 0, sizeof cntR); memset(cntB, 0, sizeof cntB); FOR(i, 1, m)if(l[i]){ if(l[i] <= t)cntL[f[i]]++; if(r[i] > t)cntR[f[i]]++; if(l[i] <= t && r[i] > t)cntB[f[i]]++; } FOR(i, 1, n){ if(t && s[t] == i)continue; int cnt = cntL[i] * cntR[i] - cntB[i]; if(cnt){ res1 += 2; (res2 *= cnt) %= mod; } else if(cntL[i] + cntR[i]){ res1++; (res2 *= cntL[i] + cntR[i]) %= mod; } } if(res1 > ans1) ans1 = res1, ans2 = res2; else if(res1 == ans1)(ans2 += res2) %= mod; } if(ans1 == 0)ans2 = 1; cout << ans1 << ' ' << ans2; }
cpp
1284
E
E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5 -1 0 1 0 -10 -1 10 -1 0 3 OutputCopy2InputCopy8 0 1 1 2 2 2 1 3 0 -1 -1 -2 -2 -2 -1 -3 OutputCopy40InputCopy10 588634631 265299215 -257682751 342279997 527377039 82412729 145077145 702473706 276067232 912883502 822614418 -514698233 280281434 -41461635 65985059 -827653144 188538640 592896147 -857422304 -529223472 OutputCopy213
[ "combinatorics", "geometry", "math", "sortings" ]
#include<bits/stdc++.h> using namespace std; #define int long long #define double long long #define X first #define Y second typedef pair<double,double>pdd; pdd operator+(pdd a,pdd b){return {a.X+b.X,a.Y+b.Y }; } pdd operator-(pdd a,pdd b){return {a.X-b.X,a.Y-b.Y}; } pdd operator*(pdd a,double b){return {a.X*b,a.Y*b}; } pdd operator/(pdd a,double b){return {a.X/b,a.Y/b}; } double cross(pdd a,pdd b){return a.X*b.Y-a.Y*b.X; } double dot(pdd a,pdd b){return a.X*b.X+a.Y*b.Y;} bool ptinline(pdd a,pdd b,pdd c){return (cross(b-a,c-a)==0); } int sgn(int a){if(a==0){return 0;}if(a<0){return -1;}if(a>0){return 1;} } bool cmp(pdd i,pdd j){ int ac=0;int bc=0; if(i.X>0){ac=1;} if(i.X==0&&i.Y>0){ac=1;} if(j.X>0){bc=1;} if(j.X==0&&j.Y>0){bc=1;} if(ac&&!bc){return 1;} if(bc&&!ac){return 0;} if(cross(i,j)<0){return 1;} return 0; } bool same(pdd a,pdd b){if(sgn(a.X)!=sgn(b.X)){return 0;}if(sgn(a.Y)!=sgn(b.Y)){return 0;}return 1;} int n; pdd tar[3000]; vector<pdd>ar; int ans; void solve(){ int nn=ar.size(); for(int i=0;i<nn;i++){ ar.push_back(ar[i]); } int rit=0;//cout<<endl; for(int i=0;i<nn;i++){ rit=max(rit,i); while(cross(ar[i],ar[rit+1])<0){rit++;} int vtc=rit-i; // cout<<i<<" "<<rit<<endl; ans-=(vtc*(vtc-1)*(vtc-2))/6; } } signed main(){ cin>>n; for(int i=1;i<=n;i++){ cin>>tar[i].X>>tar[i].Y; } ans=0; for(int i=1;i<=n;i++){ ar.clear(); for(int j=1;j<=n;j++){ if(i==j){continue;} ar.push_back(tar[i]-tar[j]); } sort(ar.begin(),ar.end(),cmp); solve(); ans+=((n-1)*(n-2)*(n-3)*(n-4))/24; } cout<<ans<<endl; }
cpp
1320
F
F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1×1×11×1×1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1×1×11×1×1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x,y,z)(x,y,z) (the cell with these coordinates is a cube with opposite corners in (x,y,z)(x,y,z) and (x+1,y+1,z+1)(x+1,y+1,z+1)) and its contents ax,y,zax,y,z; if the cell is empty, then ax,y,z=0ax,y,z=0, otherwise ax,y,zax,y,z is equal to the type of the block placed in it (the types are integers from 11 to 2⋅1052⋅105).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n×m×kn×m×k, containing all cells (x,y,z)(x,y,z) such that x∈[1,n]x∈[1,n], y∈[1,m]y∈[1,m], and z∈[1,k]z∈[1,k]. After that, Polycarp has installed 2nm+2nk+2mk2nm+2nk+2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 66 types: there are mkmk sensors of the first type; each such sensor is installed in (0,y,z)(0,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the same direction; there are mkmk sensors of the second type; each such sensor is installed in (n+1,y,z)(n+1,y,z), where y∈[1,m]y∈[1,m] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OxOx axis and has the opposite direction; there are nknk sensors of the third type; each such sensor is installed in (x,0,z)(x,0,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the same direction; there are nknk sensors of the fourth type; each such sensor is installed in (x,m+1,z)(x,m+1,z), where x∈[1,n]x∈[1,n] and z∈[1,k]z∈[1,k], and it sends a ray that is parallel to the OyOy axis and has the opposite direction; there are nmnm sensors of the fifth type; each such sensor is installed in (x,y,0)(x,y,0), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the same direction; finally, there are nmnm sensors of the sixth type; each such sensor is installed in (x,y,k+1)(x,y,k+1), where x∈[1,n]x∈[1,n] and y∈[1,m]y∈[1,m], and it sends a ray that is parallel to the OzOz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers nn, mm and kk (1≤n,m,k≤2⋅1051≤n,m,k≤2⋅105, nmk≤2⋅105nmk≤2⋅105) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 00, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 11 to 2⋅1052⋅105 denoting the type of the first block hit by the ray. The data is divided into 66 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (0,i,j)(0,i,j).The second section consists of mm lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (n+1,i,j)(n+1,i,j).The third section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,0,j)(i,0,j).The fourth section consists of nn lines containing kk integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,m+1,j)(i,m+1,j).The fifth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,0)(i,j,0).Finally, the sixth section consists of nn lines containing mm integers each. The jj-th integer in the ii-th line is the data from the sensor installed in (i,j,k+1)(i,j,k+1).OutputIf the information from the input is inconsistent, print one integer −1−1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmknmk integers: a1,1,1a1,1,1, a1,1,2a1,1,2, ..., a1,1,ka1,1,k, a1,2,1a1,2,1, ..., a1,2,ka1,2,k, ..., a1,m,ka1,m,k, a2,1,1a2,1,1, ..., an,m,kan,m,k, where ai,j,kai,j,k is the type of the block in (i,j,k)(i,j,k), or 00 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are nn separate sections for blocks having x=1x=1, x=2x=2, ..., x=nx=n; each section consists of mm lines containing kk integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInputCopy4 3 2 1 4 3 2 6 5 1 4 3 2 6 7 1 4 1 4 0 0 0 7 6 5 6 5 0 0 0 7 1 3 6 1 3 6 0 0 0 0 0 7 4 3 5 4 2 5 0 0 0 0 0 7 OutputCopy1 4 3 0 6 5 1 4 3 2 6 5 0 0 0 0 0 0 0 0 0 0 0 7 InputCopy1 1 1 0 0 0 0 0 0 OutputCopy0 InputCopy1 1 1 0 0 1337 0 0 0 OutputCopy-1 InputCopy1 1 1 1337 1337 1337 1337 1337 1337 OutputCopy1337
[ "brute force" ]
#include<bits/stdc++.h> #define ll long long #define f(i,a,b) for (ll i=a;i<=b;i++) #define fx(i,a,b) for (ll i=a;i>=b;i--) using namespace std; const ll maxn=2e5+5; inline ll read() { ll l=0,f=1; char c=getchar(); while (c<'0' || c>'9') { if (c=='-') f=-1; c=getchar(); } while (c>='0' && c<='9') l=(l<<3)+(l<<1)+(c-'0'),c=getchar(); return l*f; } ll n,m,k,t; inline ll id(ll x,ll y,ll z) { return (x-1)*m*k+(y-1)*k+z; } ll a[maxn]; vector<ll> tag[maxn]; ll dx[6]={1,-1,0,0,0,0},dy[6]={0,0,1,-1,0,0},dz[6]={0,0,0,0,1,-1}; inline bool chk(ll x,ll y,ll z) { return 1<=x && x<=n && 1<=y && y<=m && 1<=z && z<=k; } void ins(ll,ll,ll,ll,ll); void del(ll,ll,ll); void ins(ll x,ll y,ll z,ll d,ll t) { ll i=id(x,y,z); if (!chk(x,y,z)) { if (!t) return; puts("-1"); exit(0); } if (!t) { if (a[i]>0) del(x,y,z); a[i]=0; ins(x+dx[d],y+dy[d],z+dz[d],d,t); } else if (a[i]==-1 || a[i]==t) a[i]=t,tag[i].push_back(d); else if (!a[i]) ins(x+dx[d],y+dy[d],z+dz[d],d,t); else del(x,y,z),a[i]=0,ins(x+dx[d],y+dy[d],z+dz[d],d,t); } inline void del(ll x,ll y,ll z) { ll i=id(x,y,z); while (!tag[i].empty()) { ll d=tag[i].back(); tag[i].pop_back(); if (chk(x+dx[d],y+dy[d],z+dz[d])) { ins(x+dx[d],y+dy[d],z+dz[d],d,a[i]); } } } signed main() { n=read(); m=read(); k=read(); memset(a,-1,sizeof(a)); f(i,1,m) f(j,1,k) t=read(),ins(1,i,j,0,t); f(i,1,m) f(j,1,k) t=read(),ins(n,i,j,1,t); f(i,1,n) f(j,1,k) t=read(),ins(i,1,j,2,t); f(i,1,n) f(j,1,k) t=read(),ins(i,m,j,3,t); f(i,1,n) f(j,1,m) t=read(),ins(i,j,1,4,t); f(i,1,n) f(j,1,m) t=read(),ins(i,j,k,5,t); f(i,1,n*m*k) if (a[i]==-1) cout<<"1 ";else cout<<a[i]<<" ";cout<<endl; }
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 <iostream> using namespace std; int main() { int n; string s, t = ""; cin >> n >> s; char c = 'a', d = 'a'; for (int i = 0; i < n; i++) { if (c <= s[i]) { c = s[i]; t += "0"; } else if (d <= s[i]) { d = s[i]; t += "1"; } else { cout << "NO"; return 0; } } cout << "YES" << endl; cout << t; }
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
/// In the name of ALLAH /// #include <bits/stdc++.h> #define ll long long using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll x; cin >> x; ll a,b; for(ll i=1; i*i <= x; i++) { if(x % i == 0) { if(__gcd(i,x/i) == 1) { a = i; } } } cout << a << " " << x / a << '\n'; return 0; }
cpp
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
#include<bits/stdc++.h> #define ll long long int #define pa pair<int,int> #define f first #define s second #define sz 200005 #define vec array<int,4> using namespace std; std::vector<int> adj[sz]; int deg[sz],ans[sz],deg1[sz]; int r; map<pa,int>mp; void solve(int node,int par,int clr) { for(int u:adj[node]) { if(u == par) continue; clr = (clr%r)+1; ans[mp[{node,u}]] = (clr)%r+1; solve(u,node,clr); } return; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int test_case = 1; //cin >> test_case; for(int cs = 1;cs <= test_case; cs++) { int n,k; cin >> n >> k; for(int i = 1;i<n;i++) { int a,b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); deg[a]++; deg[b]++; mp[{a,b}]=mp[{b,a}] = i; } for(int i = 1;i<=n;i++) deg1[deg[i]]++; for(int i = n;i >= 1; i--) { deg1[i] += deg1[i+1]; if(deg1[i] <= k) r = i-1; } solve(1,0,0); cout << r <<"\n"; for(int i = 1;i<n;i++) cout << ans[i] <<" "; cout <<"\n"; } return 0; }
cpp
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
// LUOGU_RID: 95229403 #include<bits/stdc++.h> #define Tp template<typename Ty> #define Ts template<typename Ty,typename... Ar> #define W while #define I inline #define RI int #define LL long long #define Cn const #define CI Cn int& #define gc getchar #define D isdigit(c=gc()) #define pc(c) putchar((c)) using namespace std; namespace Debug{ Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;} Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;} #define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; namespace FastIO{ Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;} Ts I void read(Ty& x,Ar&... y){read(x),read(y...);} Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'),0);} Tp I void writeln(Cn Ty& x){write(x),pc('\n');} }using namespace FastIO; Cn int N=110; int n,vis[N],col[N]; struct node{int a[27],L;}A,B,lst[N]; I node Mul(node a,int b){for(int i=0;i<26;i++)a.a[i]*=b;return a;} I node Sub(node a,node b){for(int i=0;i<26;i++)a.a[i]-=b.a[i];return a;} I node RD(){node t;memset(t.a,0,sizeof(t.a));string s;cin>>s;RI l=s.length(),i;for(t.L=l,i=0;i<l;i++) t.a[s[i]-'a']++;return t;} #define fi first #define se second vector<pair<int,pair<int,int> > > G[N]; #define pb push_back I void U(CI a,CI b,CI x,CI y){ if(a==b) return assert(x==y),vis[a]=1,col[a]=x,void(); G[a].pb({b,{x,y}}),G[b].pb({a,{x,y}}); } I void Q(CI l,CI r){ cout<<"? "<<l<<" "<<r<<endl; RI i,j,k,m=r-l+1,t=m*(m+1)/2;vector<node> v; for(i=0;i<t;i++) v.pb(RD()); for(i=0;i<t;i++) if(v[i].L==m) A=v[i]; for(i=1;i<=(m+1)/2;i++){ B=Mul(A,i+1);for(auto k:v) if(k.L==m-i) B=Sub(B,k); for(j=1;j<i;j++) B=Sub(B,Mul(lst[j],i-j+1)); lst[i]=B;for(j=0;j<26;j++) if(B.a[j]){B.a[j]--;for(k=j;k<26;k++) if(B.a[k]){U(l+i-1,r-i+1,j,k);break ;}break ;} }return ; } queue<int> q; int main(){ RI i,u,y,z,l,r;read(n); if(n==1){cout<<"? 1 1"<<endl;string s;cin>>s;cout<<"! "<<s<<endl;return 0;} Q(1,n),Q(1,n/2),Q((n+1)/2,n); W(!q.empty()) q.pop(); for(i=1;i<=n;i++) vis[i]&&(q.push(i),0); W(!q.empty()){u=q.front(),q.pop();for(auto i:G[u]) y=i.fi,z=col[u]==i.se.fi?i.se.se:i.se.fi,!vis[y]&&(vis[y]=1,col[y]=z,q.push(y),0),assert(col[y]==z);} cout<<"! ";for(i=1;i<=n;i++) pc(col[i]+'a');pc('\n');return 0; }
cpp
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { cin.tie(0), ios::sync_with_stdio(0); ll t, n; string s; cin >> t; while (t--) { cin >> n >> s; vector<int> a(n), b(n); int i = 0, j = 0, k = 1; while (i < n) { if (s[i] == '<') { for (int l = i; l >= j; l--) a[l] = k++; j = i+1; } i++; } for (int l = i-1; l >= j; l--) a[l] = k++; i = n-1, j = n-1, k = 1; while (i >= 0) { if (s[i] == '>') { for (int l = i+1; l <= j; l++) b[l] = k++; j = i; } i--; } for (int l = i+1; l <= j; l++) b[l] = k++; for (int i = 0; i < n; i++) cout << b[i] << " \n"[i==n-1]; for (int i = 0; i < n; i++) cout << a[i] << " \n"[i==n-1]; } }
cpp
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define M_PI 3.14159265358979323846 #define Speed_UP ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define pb push_back #define ff first #define ss second #define pii pair<int,int> #define sz(x) (int)x.size() #define all(x) (x).begin(), (x).end() #define FOR(i, j, k, in) for (int i=j ; i<k ; i+=in) #define RFOR(i, j, k, in) for (int i=j ; i>=k ; i-=in) #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << " " << x <<"\n"; #else #define debug(x) #endif #ifndef ONLINE_JUDGE #define debugg(x) cerr << #x << " " << x <<"\n"; #else #define debugg(x) #endif using namespace __gnu_pbds; using namespace std; template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update> ; // order_of_key (k) : Number of items strictly smaller than k . // find_by_order(k) : K-th element in a set (counting from zero). #define precise std::setprecision(20) typedef long long ll; typedef long double ld; inline void setIO(string ); mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // use setprecision before not after // don't modify map while iterating // beware of precendence bitwise with arithmetic, use sz(arr) instead of arr.size() // can't think of anything then think of xor // pigeonhole and bruteforce mostly go together // powl() instead of pow() for 64 bit // vector.assign(size, value) it resizes if necessary. // use fill() works with vectors as well as arrays int solve(){ ll n; cin >> n; string s; cin >> s; vector<ll> adj[n], indeg(n, 0); for(int i = 0; i < n - 1; i++) { if(s[i] == '<') { adj[i].pb(i + 1); indeg[i + 1]++; } else { adj[i + 1].pb(i); indeg[i]++; } } vector<ll> a1(n, 0), a2(n, 0); { vector<ll> dindeg = indeg; priority_queue<ll> q; for(int i = 0; i < n; i++) { if(dindeg[i] == 0) q.push(i); } ll c = 1; while(!q.empty()) { ll u = q.top(); a1[u] = c; c++; q.pop(); for(auto v: adj[u]) { dindeg[v]--; if(dindeg[v] == 0) q.push(v); } } } { vector<ll> dindeg = indeg; priority_queue<ll, vector<ll>, greater<ll>> q; for(int i = 0; i < n; i++) { if(dindeg[i] == 0) q.push(i); } ll c = 1; while(!q.empty()) { ll u = q.top(); a2[u] = c; c++; q.pop(); for(auto v: adj[u]) { dindeg[v]--; if(dindeg[v] == 0) q.push(v); } } } for(auto u: a1) cout << u << " "; cout << "\n"; for(auto u: a2) cout << u << " "; cout << "\n"; return 0; } int main(){ Speed_UP #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("error.txt", "w", stderr); //freopen("output.txt", "w", stdout); #endif ll t = 1; cin >> t; for(int i = 1; i <= t; i++) { // cout << "Case #"<<i<<": "; solve(); } } inline void setIO(string name="") { #ifndef ONLINE_JUDGE freopen((name+".in").c_str(), "r", stdin); freopen((name+".out").c_str(), "w", stdout); #endif }
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" ]
/// What are you doing now? Just go f*cking code now dude? #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #define TASK "codin" #define int long long using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long llu; #define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fi first #define se second #define mp make_pair #define pb push_back #define is insert #define eb emplace_back #define FOR(x,a,b) for (ll x=a;x<=b;x++) #define FOD(x,a,b) for (ll x=a;x>=b;x--) #define FER(x,a,b) for (ll x=a;x<b;x++) #define FED(x,a,b) for (ll x=a;x>b;x--) #define EL "\n" #define ALL(v) v.begin(),v.end() #define vi vector<ll> #define vii vector<pii> #define pii pair<int,int> ///---------- TEMPLATE ABOUT BIT ----------/// ll getbit(ll val, ll num){ return ((val >> (num)) & 1LL); } ll offbit(ll val, ll num){ return ((val ^ (1LL << (num - 1)))); } ll setbit(ll k, ll s) { return (k &~ (1 << s)); } ///---------- TEMPLATE ABOUT MATH ----------/// ll lcm(ll a, ll b){ return a * b/__gcd(a, b); } ll bmul(ll a, ll b, ll mod){ if(b == 0){return 0;} if(b == 1){return a;} ll t = bmul(a, b/2, mod);t = (t + t)%mod; if(b%2 == 1){t = (t + a) % mod;}return t; } ll bpow(ll n, ll m, ll mod){ ll res = 1; while (m) { if (m & 1) res = res * n % mod; n = n * n % mod; m >>= 1; } return res; } ///----------------------------------------/// const int S = 5e5 + 5, M = 2e3 + 4; const ll mod = 1e9 + 7, hashmod = 1e9 + 9, inf = 1e18; const int base = 311, BLOCK_SIZE = 420; const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; const int dxx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dyy[8]={0, 1, 1, 1, 0, -1, -1, -1}; ///------ The main code starts here ------/// string s; int dp[100][100], cnt[S]; void solve(){ cin >> s; int ans = 0; FOR(i, 0, s.size() - 1){ FOR(j, 0, 25){ dp[s[i] - 'a'][j] += cnt[j]; ans = max(ans, dp[s[i] - 'a'][j]); } cnt[s[i] - 'a']++; ans = max(ans, cnt[s[i] - 'a']); } cout << ans; } signed main(){ IO if(fopen(TASK".inp","r")){ freopen(TASK".inp","r",stdin); freopen(TASK".out","w",stdout); } int t = 1; //cin >> t; while(t--){ solve(); } }
cpp
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" ]
// @cvtrana #include <bits/stdc++.h> using namespace std; #define jai__Bhawanii ios:: sync_with_stdio(0);cin.tie(0);cout.tie(0); #define all(v) (v).begin(), (v).end() #define int long long #define pb push_back #define vi vector<int> #define mod 1000000007 #ifdef ONLINE_JUDGE #define de(...) #define de2(...) #endif map<int,vector<int>> m; vector<int> v(200005); vector<int> dp(200005); vector<int> ans(200005); void dfs(int node,int par){ dp[node] = v[node]; for(auto x:m[node]){ if(x==par)continue; dfs(x,node); dp[node] += max((int)0,dp[x]); } } // to get rid of rollbacks , we can also create a new DP void dfs2(int node,int par){ ans[node] = dp[node]; for(auto x:m[node]){ if(x==par)continue; // reroot the adjacent node dp[node] -= max((int)0,dp[x]); dp[x] += max((int)0,dp[node]); dfs2(x,node); // rollback for others dp[x]-= max((int)0,dp[node]); dp[node] += max((int)0,dp[x]); } } void solve(){ int n; cin >> n; for(int i=0;i<n;i++){ cin >> v[i]; // colors; if (v[i] == 0) v[i] = -1; } int t = n-1; while(t--){ int a,b; cin >> a >> b; a--; b--; m[a].pb(b); m[b].pb(a); } //de(m); dfs(0,-1); dfs2(0,-1); for(int i=0;i<n;i++){ cout << ans[i] <<" "; } cout << endl; } signed main() { jai__Bhawanii; // int t; cin >> t; // while (t--) // { solve(); // } }
cpp
13
C
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1
[ "dp", "sortings" ]
#include <bits/stdc++.h> using namespace std; #define endl "\n" typedef long long ll; int main() { ll n,ans=0,arr[5005]; priority_queue<ll> pq; cin >> n; for(ll i=1;i<=n;i++) { cin >> arr[i]; if(!pq.empty()&&pq.top()>arr[i]) { ans=ans+pq.top()-arr[i]; pq.pop(); pq.push(arr[i]); } pq.push(arr[i]); } cout << ans << endl; return 0; }
cpp
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The 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≤10001≤n≤1000) — 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.
[ "brute force", "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
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" ]
#ifdef LOCAL #define _GLIBCXX_DEBUG #endif #include "bits/stdc++.h" using namespace std; typedef long long ll; #define sz(s) ((int)s.size()) #define all(v) begin(v), end(v) typedef long double ld; const int MOD = 1000000007; #define ff first #define ss second mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); // *-> KISS* int solve() { ll n, g, b; cin >> n >> g >> b; ll num = (n + 1) / 2; ll how1 = num / g, how2 = num % g; ll ans = how1 * (g + b); if(!how2) { ans -= b; } else ans += how2; ans += (max(0LL, n - ans)); cout << ans; return 0; } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); int TET = 1; cin >> TET; cout << fixed << setprecision(6); for (int i = 1; i <= TET; i++) { #ifdef LOCAL cout << "##################" << '\n'; #endif if (solve()) { break; } cout << '\n'; } #ifdef LOCAL cout << endl << "finished in " << clock() * 1.0 / CLOCKS_PER_SEC << " sec" << endl; #endif return 0; } // -> Keep It Simple Stupid!
cpp
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define sws ios_base::sync_with_stdio(false);cout.tie(NULL);cin.tie(NULL); #define mp make_pair #define pb push_back #define rep(i, a, b) for (int i = a; i < b; i++) #define dbg(msg,x) cout<<msg<<" "<<x<<endl; #define output(x) for(auto c:x){cout<<c<<" ";}cout<<" "; #define ll long long #define ff first #define ss second #define pq priority_queue typedef vector<int> vi; typedef vector<bool> vb; typedef pair<int, int> pii; typedef vector<pair<int,int> > vpp; int charToInt(char a){ return a-(int)'a'; } char intToChar(int a){ return (char)(a+'a'); } int main(){ sws int t;cin>>t; while(t--){ string s;cin>>s; bool adj[26][26]; memset(adj,false,sizeof(adj)); int n = s.size(); rep(i,0,n){ if(i>0){ char bf = s[i-1]; adj[charToInt(bf)][charToInt(s[i])]=1; adj[charToInt(s[i])][charToInt(bf)]=1; } if(i<n-1){ char bf = s[i+1]; adj[charToInt(bf)][charToInt(s[i])]=1; adj[charToInt(s[i])][charToInt(bf)]=1; } } bool visited[26]; int connections[26]; memset(visited,false,sizeof(visited)); memset(connections,0,sizeof(connections)); string ans=""; bool poss = true; rep(i,0,26){ int counter=0; rep(j,0,26){ counter+=adj[i][j]; } if(counter>2){ poss=false; } connections[i]=counter; } if(!poss){ cout<<"NO\n"; continue; } rep(i,0,26){ if(!visited[i] && connections[i]!=2){ stack<pii>s; s.push(mp(i,-1)); while(!s.empty()){ int cur = s.top().ff, p = s.top().ss; s.pop(); visited[cur]=true; ans+=intToChar(cur); rep(c,0,26){ if(adj[cur][c]==1){ if(c==p)continue; if(visited[c]){ poss=false; break; }else{ s.push(mp(c,cur)); } } } } } } if(!poss || ans.size()!=26){ cout<<"NO\n"; continue; } cout<<"YES\n"<<ans<<"\n"; } }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define mk make_pair #define lowbit(x) (x&(-x)) #define pb emplace_back #define pr pair<int,int> #define let const auto const int N=1e5+5; int read(){ int x=0,f=1; char c=getchar(); while(('0'>c||c>'9')&&c!='-') c=getchar(); if(c=='-') f=0,c=getchar(); while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return f?x:-x; } int n,a[N],cnt[35]; int main(){ n=read(); for(int i=1; i<=n; i++) a[i]=read(); for(int i=1; i<=n; i++) for(int j=0; j<=30; j++) if(a[i]&(1<<j)) cnt[j]++; auto calc = [&](int i){ int res=0; for(int j=0; j<=30; j++) if((a[i]&(1<<j))&&cnt[j]==1) res|=1<<j; return res; }; int Max=calc(1),p=1; for(int i=2,v; i<=n; i++) if((v=calc(i))>Max) Max=v,p=i; printf("%d ",a[p]); for(int i=1; i<=n; i++) if(i!=p) printf("%d ",a[i]); puts(""); return 0; }
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define fr(i,a,b,k) for(int i=a;i<b;i+=k) #define frrev(i,a,b,k) for(int i=a;i>b;i-=k) #define NO cout<<"NO\n" #define YES cout<<"YES\n" #define V vector<ll int> #define VP vector<pair<ll int,ll int>> #define MP map<ll int,ll int> #define pb push_back #define ff first #define ss second #define input(A) for(auto &i:A)cin>>i #define output(A) for(auto &i:A)cout<<i<<" " int H[100],L[100],T[100]; void solve(int t) { int n,m; cin>>n>>m; fr(i,0,n,1) cin>>T[i]>>L[i]>>H[i]; int pt=0; int mini=m; int maxi=m; bool f=true; fr(i,0,n,1) { mini-=T[i]-pt; maxi+=T[i]-pt; if(maxi<L[i] || mini>H[i]) { f=false; break; } maxi=min(maxi,H[i]); mini=max(mini,L[i]); pt=T[i]; } if(f) YES; else NO; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; for(int i=1;i<=t;i++) { solve(t); } return 0; }
cpp
1286
F
F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort; Harry needs to destroy all horcruxes first. The last horcrux is an array aa of nn integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index ii (1≤i≤n1≤i≤n), an integer xx, and subtract xx from aiai. choose two indices ii and jj (1≤i,j≤n;i≠j1≤i,j≤n;i≠j), an integer xx, and subtract xx from aiai and x+1x+1 from ajaj. Note that xx does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer nn — the size of the array aa (1≤n≤201≤n≤20). The following line contains nn integers a1,a2,…,ana1,a2,…,an — array elements (−1015≤ai≤1015−1015≤ai≤1015).OutputOutput a single integer — the minimum number of operations required to destroy the array aa.ExamplesInputCopy3 1 10 100 OutputCopy3 InputCopy3 5 3 -2 OutputCopy2 InputCopy1 0 OutputCopy0 NoteIn the first example one can just apply the operation of the first kind three times.In the second example; one can apply the operation of the second kind two times: first; choose i=2,j=1,x=4i=2,j=1,x=4, it transforms the array into (0,−1,−2)(0,−1,−2), and then choose i=3,j=2,x=−2i=3,j=2,x=−2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed.
[ "brute force", "constructive algorithms", "dp", "fft", "implementation", "math" ]
#include <bits/stdc++.h> using namespace std; #define Int register int #define MAXM 2000005 #define int long long #define MAXN 25 //char buf[1<<21],*p1=buf,*p2=buf; //#define getchar() (p1==p2 && (p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) template <typename T> inline void read (T &x){char c = getchar ();x = 0;int f = 1;while (c < '0' || c > '9') f = (c == '-' ? -1 : 1),c = getchar ();while (c >= '0' && c <= '9') x = x * 10 + c - '0',c = getchar ();x *= f;} template <typename T,typename ... Args> inline void read (T &x,Args& ... args){read (x),read (args...);} template <typename T> inline void write (T x){if (x < 0) x = -x,putchar ('-');if (x > 9) write (x / 10);putchar (x % 10 + '0');} template <typename T> inline void chkmax (T &a,T b){a = max (a,b);} template <typename T> inline void chkmin (T &a,T b){a = min (a,b);} int n,a[MAXN]; int z[MAXN],sl[MAXM],sr[MAXM],s0[MAXM],s1[MAXM]; void getnum (int *s,int &k,int l,int r){//将所有情况枚举出来并排序 k = 1,s[0] = 0; for (Int i = l;i < r;++ i,k <<= 1){ for (Int j = 0;j < k;++ j) s0[j] = s[j] + z[i],s1[j] = s[j] - z[i]; int p = 0,q = 0,now = 0; while (p < k && q < k){ if (s0[p] <= s1[q]) s[now ++] = s0[p ++]; else s[now ++] = s1[q ++]; } while (p < k) s[now ++] = s0[p ++]; while (q < k) s[now ++] = s1[q ++]; } } bool checkit (int S){ int siz = 0,sum = 0,ql,qr; for (Int x = 0;x < n;++ x) if (S >> x & 1) z[siz ++] = a[x],sum += a[x]; if (abs(sum) % 2 != (siz - 1) % 2) return 0; getnum (sl,ql,0,siz >> 1),getnum (sr,qr,siz >> 1,siz); int ned = 1 + (abs(sum) < siz) * 2;//显然我们不能把所有的dep都设为相同的深度 for (Int i = qr - 1,j = 0;~i;-- i){ while (j < ql && sr[i] + sl[j] <= -siz) ++ j; for (Int k = j;k < ql && ned && sr[i] + sl[k] < siz;++ k) -- ned; } return !ned; } int f[MAXM],sum[MAXM]; signed main(){ read (n); for (Int x = 0;x < n;++ x) read (a[x]); memset (f,0x3f,sizeof (f)),f[0] = 0; for (Int S = 1;S < (1 << n);++ S) sum[S] = sum[S >> 1] + (S & 1); // cout << checkit (3) << endl;return 0; for (Int S = 1;S < (1 << n);++ S) if (sum[S] == 1 || checkit (S)){ int rst = ((1 << n) - 1) ^ S,con = (sum[S] != 1 ? sum[S] - 1 : (a[(int)log2(S)] == 0 ? 0 : 1)); for (Int T = rst;T >= 0;T = (T - 1) & rst){ if (f[T] <= n) chkmin (f[T | S],f[T] + con); if (!T) break; } } write (f[(1 << n) - 1]),putchar ('\n'); return 0; }
cpp
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
#include <bits/stdc++.h> // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> using namespace std; // using namespace chrono; // using namespace __gnu_pbds; typedef vector<long long> vi; typedef pair<int, int> pii; #define endl "\n" #define sd(val) scanf("%d", &val) #define ss(val) scanf("%s", &val) #define sl(val) scanf("%lld", &val) #define debug(val) printf("check%d\n", val) #define all(v) v.begin(), v.end() #define sai(a, n) sort(a, a + n); #define sad(a, n) sort(a, a + n, greater<int>()); #define svi(x) sort(x.begin(), x.end()); #define svd(a) sort(a.begin(), a.end(), greater<int>()); #define fi(i, x, n) for (int i = x; i < n; i++) #define PB push_back #define MP make_pair #define FF firstṇ #define SS second #define ull unsigned long long #define int long long // #define MOD 1000000007 #define MOD 998244353 #define clr(val) memset(val, 0, sizeof(val)) #define what_is(x) cerr << #x << " is " << x << endl; #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); #define FIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); // template <class T> // using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // Function to find a^b % MOD. Time Complexity : O(log b). int highPowerMod(int a, int b) { // a %= MOD; int res = 1; while (b > 0) { if (b & 1) res = (res * a); a = (a * a); b >>= 1; } return res; } // Function to find the lcm of a and b. Time Complexity : O(log(min(a, b))). int lcm(int a, int b) { return a / __gcd(a, b) * b; } void bfs(int start, vector<vector<int>> &g2, vector<pair<int, bool>> &dp, int m) { queue<int> q; q.push(start); int cnt = 0; bool flag = false; while (!q.empty()) { cnt = q.front(); if (cnt < m) flag = true; q.pop(); dp[cnt].second = flag; for (const auto &nbr : g2[cnt]) { if (dp[nbr].first == -1) { dp[nbr].first = dp[cnt].first + 1; q.push(nbr); } } } } int compliment(int x, int n) { return (x ^ (n - 1)); } void dfs(int start, vector<vi> &graph, vector<bool> &vis) { vis[start] = true; for (const auto &nbr : graph[start]) { if (!vis[nbr]) { dfs(nbr, graph, vis); } } } pair<int, int> intersection(pair<int, int> a, pair<int, int> b) { if (a.first > b.second || b.first > a.second) return {-1, -1}; return {max(a.first, b.first), min(a.second, b.second)}; } int cntDigits(int n) { string t = to_string(n); return (int)t.size(); } int bs_sqrt(int x) { int left = 0, right = 2000000123; while (right > left) { int mid = left + (right - left) / 2; if (mid * mid > x) right = mid; else left = mid + 1; } return left - 1; } void primeFactors(int n, vi &arr) { int t = 1e5 + 7; fi(i, 1, t) { if (i * i > n) break; if (n % i == 0) { arr.push_back(i); arr.push_back(n / i); } } } void SieveOfEratosthenes(int n, vi &primess) { bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int p = 2; p <= n; p++) if (prime[p]) primess.push_back(p); } // And of a Range of numbers from a to b. int andOperator(int a, int b) { int shiftcount = 0; while (a != b and a > 0) { shiftcount++; a = a >> 1; b = b >> 1; } return int64_t(a << shiftcount); } void solve(int cake) { int n; cin >> n; int k; cin >> k; // vi arr(n); // fi(i, 0, n) cin >> arr[i]; string s; vector<string> v1, v2; fi(i, 0, n) { cin >> s; v1.push_back(s); } fi(i, 0, k) { cin >> s; v2.push_back(s); } int q; cin >> q; fi(i, 0, q) { int y; cin >> y; y--; int x1 = y % n, x2 = y % k; string res = v1[x1] + v2[x2]; cout << res << endl; } } int32_t main() { // OJ; FIO; int t = 1; int cake = 1; // cin >> t; // vi primes; // int N = 31622; // SieveOfEratosthenes(N, primes); while (t--) { solve(cake); cake++; } return 0; }
cpp
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
#include <bits/stdc++.h> using namespace std; using LL = long long; #define endl '\n' using db = double; template <class T> using max_heap = priority_queue<T>; template <class T> using min_heap = priority_queue<T, vector<T>, greater<>>; int main() { // ios::sync_with_stdio(false); // cin.tie(nullptr); int n; cin >> n; vector<int> fa(n + 1), c(n + 1); int root; vector<vector<int>> g(n + 1); for (int i = 1; i <= n; ++i) { cin >> fa[i] >> c[i]; if (fa[i] == 0) root = i; else g[fa[i]].push_back(i); // cout << "i = " << i << " fa[i] = " << fa[i] << " c[i] = " << c[i] << endl; } bool ok = 1; vector<int> sz(n + 1); function<void(int)> dfs = [&](int u) -> void { sz[u] = 1; for (auto to : g[u]) { dfs(to); sz[u] += sz[to]; } if (c[u] >= sz[u]) ok = 0; }; dfs(root); if (ok == 0) { cout << "NO" << endl; return 0; } vector<int> a(n + 1), in(n + 1), out(n + 1); int id = 0; function<void(int)> dfs2 = [&](int u) -> void { in[u] = ++id; int pre = 0; for (auto to : g[u]) { dfs2(to); for (int i = in[to]; i <= out[to]; ++i) a[i] += pre; pre += sz[to]; } out[u] = id; a[in[u]] = c[u]; for (int i = in[u] + 1; i <= out[u]; ++i) if (a[i] >= a[in[u]]) a[i]++; // for (auto to : g[u]) // { // } }; dfs2(root); cout << "YES" << endl; // for (int i = 1; i <= n; ++i) // cout << "i = " << i << " in[i] = " << in[i] << " out[i] = " << out[i] << endl; for (int i = 1; i <= n; ++i) cout << a[in[i]] + 1 << " "; cout << endl; return 0; }
cpp
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
#include<bits/stdc++.h> using namespace std; long long n , x , y , z , dp [10004][4] , arr [300005]; vector < int > bt [4]; int grundy ( long long x , int y ) { if ( x < 15e2 ) return dp [x][y]; else { int xx = ( x - 1000 ) % bt [y] . size (); return bt [y][xx]; } } int main() { int t; cin >> t; while ( t -- ) { scanf ( "%lld%lld%lld%lld" , &n , &x , &y , &z ); int xr = 0; for ( int i = 1 ; i <= 15e2 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { int a = max ( i - x , 0ll ); int b = max ( i - y , 0ll ); int c = max ( i - z , 0ll ); vector < int > v; if ( j == 0 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); v . push_back ( dp [c][2] ); } if ( j == 1 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [c][2] ); } if ( j == 2 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); } sort ( v . begin () , v . end () ); v . resize ( unique ( v . begin () , v . end () ) - v . begin () ); dp [i][j] = -1; for ( int z = 0 ; z < v . size () ; z ++ ) { if ( v [z] != z ) { dp [i][j] = z; break; } } if ( dp [i][j] == -1 ) dp [i][j] = v . size (); } } bt [0] . clear (); bt [1] . clear (); bt [2] . clear (); for ( int i = 30 ; i <= 70 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { vector < int > a , b; int x = 1000 , y = i; while ( y -- ) a . push_back ( dp [ x ++ ][j] ); y = i; while ( y -- ) b . push_back ( dp [ x ++ ][j] ); if ( a == b ) bt [j] = a; } } if ( bt [0] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [1] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [2] . size () == 0 ) cout << 0 / 0 << endl; for ( int i = 0 ; i < n ; i ++ ) { scanf ( "%lld" , &arr [i] ); xr ^= grundy ( arr [i] , 0 ); } int ans = 0; for ( int i = 0 ; i < n ; i ++ ) { if ( grundy ( max ( arr [i] - x , 0ll ) , 0 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - y , 0ll ) , 1 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - z , 0ll ) , 2 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; } printf ( "%d\n" , ans ); } }
cpp
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4 OutputCopy2 3 1InputCopy1 3 OutputCopy3 1 1 1InputCopy8 5 OutputCopy-1InputCopy0 0 OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
// LUOGU_RID: 101180519 #include <bits/stdc++.h> #define fi first #define se second #define pb emplace_back #define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) using namespace std; using ll = long long; using PII = pair <int, int>; using vi = vector <int>; const int N = 2e5 + 10; const int mod = 1e9 + 7; int t, n, a[N]; int qpow(int a, int b) { int res = 1; while (b) { if (b & 1)res = (ll)res * a % mod; a = (ll)a * a % mod; b >>= 1; } return res; } int main() { ios; ll u, v; cin >> u >> v; if(u == v && u == 0) { cout << "0"; return 0; } if(u == v) { cout << "1\n"; cout << u; return 0; } if(v < u) cout << "-1"; else { if((v - u) % 2 == 1) cout << "-1"; else { ll p = v - u; p /= 2; if((p & u) > 0) { cout << "3\n"; cout << u << " " << p << " " << p << '\n'; } else { cout << "2\n"; cout << u + p << " " << p; } } } 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 ull unsigned long long #define mk make_pair #define lowbit(x) (x&(-x)) #define pb emplace_back #define pr pair<int,int> #define let const auto const int N=1e5+5; int read(){ int x=0,f=1; char c=getchar(); while(('0'>c||c>'9')&&c!='-') c=getchar(); if(c=='-') f=0,c=getchar(); while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return f?x:-x; } int n,x[N],y[N]; int main(){ n=read(); for(int i=1; i<=n; i++) x[i]=read(),y[i]=read(); if(n&1) return puts("NO"),0; int sx=x[1]+x[n/2+1],sy=y[1]+y[n/2+1]; for(int i=2; i<=n/2; i++) if(x[i]+x[n/2+i]!=sx||y[i]+y[n/2+i]!=sy) return puts("NO"),0; puts("YES"); return 0; }
cpp
1290
D
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2 N N Y N N N N OutputCopy? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 InputCopy8 8 N N N N Y Y OutputCopy? 2 ? 6 ? 4 ? 5 ? 2 ? 5 ! 6 NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.
[ "constructive algorithms", "graphs", "interactive" ]
// LUOGU_RID: 93829821 #include<bits/stdc++.h> using namespace std; #define pi pair<int,int> #define mp make_pair #define fi first #define se second #define pb push_back #define ls (rt<<1) #define rs (rt<<1|1) #define mid ((l+r)>>1) #define lowbit(x) (x&-x) const int maxn=1e4+5,M=2e5+5,mod=998244353; inline int read(){ char ch=getchar();bool f=0;int x=0; for(;!isdigit(ch);ch=getchar())if(ch=='-')f=1; for(;isdigit(ch);ch=getchar())x=(x<<1)+(x<<3)+(ch^48); if(f==1){x=-x;}return x; } void print(int x){ static int a[55];int top=0; if(x<0) putchar('-'),x=-x; do{a[top++]=x%10,x/=10;}while(x); while(top) putchar(a[--top]+48); } int n,k,flag[maxn],x,ans=0,z=0; int g[1055][1055]; char a[5]; void query(int x){ cout<<"? "<<x<<endl; fflush(stdout); scanf("%s",a); if(a[0]=='Y')flag[x]=1; } void solve(int x,int y){ cout<<"R \n"; fflush(stdout); for(int i=0;i<k/2;i++) query(g[x][i]); for(int i=0;i<k/2;i++) query(g[y][i]); } void add(int x,int y){ cout<<"R \n"; fflush(stdout); for(int i=x;i<=z;i+=y){ for(int j=0;j<k/2;j++) query(g[i][j]); } } signed main(){ n=read(),k=read(); if(n<=k){ for(int i=1;i<=n;i++){ query(i);ans+=!flag[i]; } cout<<"! "<<ans<<endl; fflush(stdout); exit(0); } if(k==1){ for(int i=2;i<=n;i++) for(int j=1;j<i;j++){ cout<<"R \n"; fflush(stdout); query(j),query(i); if(flag[i])break; } for(int i=1;i<=n;i++) if(!flag[i])ans++; cout<<"! "<<ans<<endl; fflush(stdout);exit(0); }z=0; for(int i=1;i<=n;i+=k/2){++z; for(int j=0;j<k/2;j++) g[z][j]=i+j; } for(int i=1;i<=z;i++){ for(int j=1;j<=i;j++){ if(j+i<=z){ add(j,i); } } } for(int i=1;i<=n;i++) if(!flag[i])ans++; cout<<"! "<<ans<<endl; fflush(stdout); return 0; }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int main () { ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); ll t; cin >> t; while( t-- ){ string s; cin >> s; ll cnt = 0, z = 0, cal = 0 , ans = 0; for(ll i = 0; i < s.size(); i++)if(s[i] == '1') {cal = i, z++; break;} for(ll i = s.size() - 1; i >= 0; i--)if(s[i] == '1') {ans = i; break;} for(ll i = cal; i <= ans; i++)if(s[i] == '0') cnt++; if(z == 0) cout << false << endl; else cout << cnt << endl; } } /* */
cpp
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
#include<bits/stdc++.h> using namespace std; #pragma GCC optimize ("Ofast") #define all(x) x.begin() , x.end() #define sze(x) (ll)(x.size()) #define mp(x , y) make_pair(x , y) #define wall cout<<"--------------------------------------\n"; typedef long long int ll; typedef pair<ll , ll> pll; typedef pair<int , int> pii; typedef double db; typedef pair<pll , ll> plll; typedef pair<int , pii> piii; typedef pair<pll , pll> pllll; const ll maxn = 3e5 + 17 , md = 1e9 + 7 , inf = 2e16; ll ds[maxn] , dsz[maxn][2]; bool dt[maxn] , dl[maxn]; ll ans = 0; pll dsu(ll v){ if(v == ds[v]) return {v , dt[v]}; pll p = dsu(ds[v]); p.second ^= dt[v]; dt[v] = p.second ^ dt[p.first]; return {ds[v] = p.first , p.second}; } void merge(ll v , ll u , bool t){ pll pv = dsu(v) , pu = dsu(u); v = pv.first; u = pu.first; if(v == u) return; ans -= dsz[v][1 ^ dt[v]]; ans -= dsz[u][1 ^ dt[u]]; if(dl[v] && dl[u]){ ds[u] = v; bool h = dt[u] ^ dt[v]; dsz[v][0] += dsz[u][h]; dsz[v][1] += dsz[u][1 ^ h]; dt[u] ^= dt[v]; ans += dsz[v][1 ^ dt[v]]; return; } if(dl[u]) swap(v , u); if(dl[v]){ ds[u] = v; bool h = pv.second ^ pu.second ^ t ^ dt[u] ^ dt[v]; dsz[v][0] += dsz[u][h]; dsz[v][1] += dsz[u][1 ^ h]; dt[u] ^= h ^ dt[u]; ans += dsz[v][1 ^ dt[v]]; return; } ds[u] = v; bool h = pv.second ^ pu.second ^ t ^ dt[u] ^ dt[v]; dsz[v][0] += dsz[u][h]; dsz[v][1] += dsz[u][1 ^ h]; dt[u] ^= h ^ dt[u]; if(dsz[v][dt[v]] < dsz[v][1 ^ dt[v]]) dt[v] ^= 1; ans += dsz[v][1 ^ dt[v]]; return; } void fix(ll v , bool t){ pll p = dsu(v); v = p.first; ans -= dsz[v][1 ^ dt[v]]; if(p.second != t) dt[v] ^= 1; ans += dsz[v][1 ^ dt[v]]; dl[v] = true; return; } string s; vector<ll> a[maxn]; /* 2 3 00 1 1 1 2 2 1 2 */ int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n , k; cin>>n>>k>>s; for(ll i = 0 ; i < k ; i++){ ll m; cin>>m; for(ll j = 0 ; j < m ; j++){ ll h; cin>>h; a[--h].push_back(i); } } for(ll i = 0 ; i < k ; i++){ dt[i] = 0; ds[i] = i; dsz[i][0] = 1; dsz[i][1] = 0; dl[i] = false; } for(ll i = 0 ; i < n ; i++){ bool t = (s[i] ^ '1'); if(a[i].empty()){ cout<<ans<<'\n'; continue; } if(sze(a[i]) == 1){ fix(a[i][0] , t); cout<<ans<<'\n'; continue; } merge(a[i][0] , a[i][1] , t); cout<<ans<<'\n'; } return 0; }
cpp
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
#ifndef _GLIBCXX_NO_ASSERT #include <cassert> #endif #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #if __cplusplus >= 201103L #include <ccomplex> #include <cfenv> #include <cinttypes> //#include <cstdalign> #include <cstdbool> #include <cstdint> #include <ctgmath> #include <cwchar> #include <cwctype> #endif // C++ #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> #if __cplusplus >= 201103L #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <forward_list> #include <future> #include <initializer_list> #include <mutex> #include <random> #include <ratio> #include <regex> #include <scoped_allocator> #include <system_error> #include <thread> #include <tuple> #include <typeindex> #include <type_traits> #include <unordered_map> #include <unordered_set> #endif using namespace std; using i64 = long long; using i128 = __int128; #define MAXN 5005 #define MAXM 5005 #define M 1000000 #define K 17 #define MAXP 25 #define MAXK 55 #define MAXC 255 #define MAXERR 105 #define MAXLEN 105 #define MDIR 10 #define MAXR 705 #define BASE 102240 #define MAXA 28 #define MAXT 100005 #define LIMIT 86400 #define MAXV 305 #define LEQ 1 #define EQ 0 #define OP 0 #define CLO 1 #define DIG 1 #define C1 0 #define C2 1 #define PLUS 0 #define MINUS 1 #define MUL 2 #define CLO 1 #define VERT 1 //#define B 31 #define B2 1007 #define W 1 #define H 19 #define SPEC 1 #define MUL 2 #define CNT 3 #define ITER 1000 #define INF 1e9 #define EPS 1e9 #define MOD 1000000007 #define FACT 100000000000000 #define PI 3.14159265358979 #define SRC 0 typedef long long ll; typedef ll hash_t; typedef __int128_t lint; typedef long double ld; typedef pair<int,int> ii; typedef pair<double,int> ip; typedef pair<ll,ii> pl; typedef pair<int,ll> pll; typedef pair<ll,int> li; typedef pair<ll,ll> iv; typedef tuple<int,int,int> iii; typedef tuple<ll,ll,int> tll; typedef vector<vector<int>> vv; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<ii> vii; typedef vector<vector<ll>> vll; typedef complex<ld> cd; #define pb push_back #define eb emplace_back #define ins insert #define er erase #define sc second #define fr first #define repl(i,x,y) for (int i = (x); i <= (y); ++i) #define rep(i,x,y) for (int i = (x); i < (y); ++i) #define rev(i,x,y) for (int i = (x); i >= (y); --i) #define LSOne(S) (S & (-S)) #define trav(i,v) for (auto &i : v) #define foreach(it,v) for (auto it = begin(v); it != end(v); ++it) #define bend(v) (v).begin(), (v).end() #define rbend(v) (v).rbegin(), (v).rend() #define sortarr(v) sort(bend(v)) #define rsortarr(v) sort(rbend(v)) #define sz(v) (int)((v).size()) #define unique(v) v.erase(unique(v.begin(), v.end()), v.end()) #define combine(A,B) A.insert(end(A), bend(B)) template<class T> bool ckmin(T &a, T &b) { return a > b ? a = b, 1 : 0; }; template<class T> bool ckmax(T &a, T &b) { return a < b ? a = b, 1 : 0; }; template<class T> void amax(T &a, T b, T c) { a = max(b, c); }; template<class T> void amin(T &a, T b, T c) { a = min(b, c); }; template<class T> T getmax(vector<T> &v) { return *max_element(bend(v)); }; template<class T> T getmin(vector<T> &v) { return *min_element(bend(v)); }; template<class T> int compress(vector<T> &v, T &val) { return (int)(lower_bound(bend(v), val) - begin(v)); }; template<class T> auto vfind(vector<T> &v, T val) { return find(bend(v), val); } template<class T> auto verase(vector<T> &v, T val) { return v.er(vfind(v, val)); } int n,m; //candidate stores all possible cows with favourite jelly i vv cand, occ; int pos[MAXN]; //idea is to find an invariant(in this case rightmost point of the left queue and fix it) //now we want to count the number of cows in the left and right queue respectively //for all cows that likes the same jelly, 2 cows of the same type cannot both appear on the left of right queue but separately //calculate the number of ways to add the pair of cows to the left and right queue independently //only need to choose a subset so ordering of the cows do not matter int main() { cin >> n >> m; vector<int> a(n); cand.resize(n), occ.resize(n); rep(i,0,n) { int x; cin >> x; x--; a[i] = x; occ[x].pb(i); } rep(i,0,m) { int f,h; cin >> f >> h; f--; if (h <= sz(occ[f])) cand[f].pb(h), pos[occ[f][h - 1]] = true; } pll ans = {0, 1}; //consider the case where we leave the right queue empty rep(i,0,n) { if (sz(cand[i]) > 0) ans.fr++, ans.sc = (1LL * ans.sc * sz(cand[i])) % MOD; } //fix the valid starting positions rep(i,0,n) { if (pos[i]) { pll tmp = {1, 1}; //calculate all possible ending points for cows that like the same candy int canrgt = 0; trav(j, cand[a[i]]) { if (occ[a[i]][sz(occ[a[i]]) - j] > i) { if (occ[a[i]][j - 1] != i) canrgt++; } } if (canrgt) tmp.fr++, tmp.sc = (tmp.sc * canrgt) % MOD; rep(j,0,n) { if (a[i] == j) continue; int cntlft = 0, cntrgt = 0, cntdup = 0; trav(k, cand[j]) { if (occ[j][k - 1] < i) cntlft++; if (occ[j][sz(occ[j]) - k] > i) cntrgt++; if (occ[j][k - 1] < i && occ[j][sz(occ[j]) - k] > i) cntdup++; } int c2 = cntlft * cntrgt - cntdup; int c1 = cntlft + cntrgt; if (c2) { //add this pair of cows to the left and right queues respectively tmp.fr += 2; tmp.sc = (tmp.sc * c2) % MOD; } else if (c1) { tmp.fr++; tmp.sc = (tmp.sc * c1) % MOD; } } if (tmp.fr > ans.fr) { ans = tmp; } else if (tmp.fr == ans.fr) ans.sc = (ans.sc + tmp.sc) % MOD; } } cout << ans.fr << ' ' << ans.sc; }
cpp
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The 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≤10001≤n≤1000) — 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.
[ "brute force", "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> using namespace std; #define ll long long int #define ull unsigned long long int #define endl '\n' #define yes cout<<"YES\n" #define no cout<<"NO\n" #define f(i,a,b) for(ll i = a; i <= b; i++) #define fr(i,a,b) for(ll i = a; i >= b; i--) #define pb push_back #define all(x) x.begin(),x.end() #define sz(x) ((int)(x).size()) #define llceil(a,b) ceil(((double)a)/((double)b)) #define llfloor(a,b) floor(((double)a)/((double)b)) #define vec vector<ll> #define dvec vector<vector<ll>> //////*************Nitin1605***************////// int main() { ios_base::sync_with_stdio(false);cin.tie(0),cout.tie(0); cout << fixed << setprecision(0); ll n,a=LLONG_MAX,x,ans=-1,mi=LLONG_MAX; cin>>n; vec v(n); f(i,0,n-1)cin >> v[i]; f(j,0,n-1) { x=v[j];a=0; f(i,j,n-1) { if(v[i]>x)a+=(v[i]-x); else x=v[i]; } x=v[j]; fr(i,j,0) { if(v[i]>x)a+=(v[i]-x); else x=v[i]; } if(mi>a) { ans=j; mi=a; } } x=v[ans]; f(i,ans+1,n-1) { if(v[i]>v[i-1])v[i]=v[i-1]; } x=v[ans]; fr(i,ans-1,0) { if(v[i]>v[i+1])v[i]=v[i+1]; } for(auto i:v) cout << i << " "; }
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> 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() { ll h; cin >> h; int n; cin >> n; vll vec(n); for (int i = 0; i < n; ++i) { cin >> vec[i]; vec[i] = -vec[i]; } deb(vec); vll pref(n + 1), max_pref(n + 1); for (int i = 1; i <= n; ++i) { pref[i] = pref[i - 1] + vec[i - 1]; max_pref[i] = max({0LL, max_pref[i - 1], pref[i]}); } deb(pref); deb(max_pref); { auto it = lower_bound(ALL(max_pref), h); if (it != max_pref.end()) { cout << it - max_pref.begin() << "\n"; return; } } if (pref.back() <= 0) { cout << "-1\n"; return; } ll times = (h - max_pref.back() + pref.back() - 1) / pref.back(); h -= times * pref.back(); auto it = lower_bound(ALL(max_pref), h); cout << times * n + it - max_pref.begin() << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin ("puzzle_name.in"); //ofstream cout ("puzzle_name.out"); solve(); return 0; }
cpp
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3 5 7 10 19 10 18 OutputCopyYES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO NotePictures corresponding to the first and the second test cases of the example:
[ "brute force", "constructive algorithms", "trees" ]
#define _CRT_SECURE_NO_WARNINGS #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,abm,mmx,tune=native") #include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> #include <cmath> #include <bitset> #include <iomanip> #include <queue> #include <stack> #include <map> #include <unordered_map> #include <unordered_set> #include <chrono> #include <random> #include <complex> #include <bitset> #include <fstream> #include <list> #include <numeric> #include <sstream> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); inline void boostIO() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed << setprecision(10); } bool isPrime(int x) { if (x <= 4 || x % 2 == 0 || x % 3 == 0) return x == 2 || x == 3; for (int i = 5; i * i <= x; i += 6) if (x % i == 0 || x % (i + 2) == 0) return 0; return 1; } typedef long long int ll; typedef long double ld; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<ll> vll; typedef pair<ll, ll> pll;; typedef pair<int, int> pii; #define fori(n) for(int i = 0; i < (n); ++i) #define forj(n) for(int j = 0; j < (n); ++j) #define fork(n) for(int k = 0; k < (n); ++k) #define forx(n) for(int x = 0; x < (n); ++x) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define ff first #define ss second #define debug(x) cerr << #x << " = " << x << endl; #define debug_p(x) cerr << #x << " " << x.ff << " " << x.ss << endl; #define debug_v(x) cerr << #x << " "; for (auto ii : x) cout << ii << " "; cout << endl; #define debug_vp(x) cerr << #x << " "; for (auto ii : x) cout << '[' << ii.ff << " " << ii.ss << ']'; cout << endl; #define mp make_pair #define rand kjsdflsdfsdlsjdlkfsdjflsjdfl #define prev sdjfsldfkjsdlkfjsldkfjlsdkjf #define next oiasjdoiasjdasljdalsjdlaksjasd #define time zsdfsijfsldfj83fsdfsdfsdfsdfsd #define y1 ujqwoejqowiejqowiejqowiejqowij #define Return cerr<<endl<<"RUNTIME: "<<1.0*clock()/CLOCKS_PER_SEC << " s" <<endl; return 0; #define PI 3.141592653589793238462643383279502884L ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } ll lcm(int a, int b) { return 1ll * a * b / gcd(a, b); } //MAY BE DANGEROUS bool BREAKTIME(ld v) { return 1.0 * clock() >= v * CLOCKS_PER_SEC; } #define OR(a, b) ((a) | (b)) #define AND(a, b) ((a) & (b)) #define XOR(a, b) ((a) ^ (b)) #define BIT(a) (1ll << (a)) ll COUNT(ll n) { ll count = 0; while (n) { count += n & 1ll; n >>= 1ll; } return count; } /////////////////////// #define int long long const ll inf = 3e18 + 5; //const int inf = 1e9 + 5; //ll mod = 1e9 + 7; #define endl "\n" ////////////////////// vector<int> MIN(5001); vector<int> MAX(5001); vector<int> Prev; void f(int i, int am, int sum) { if (am == 1 && sum == 0) { return; } { int SUM = sum - am + 1; int AM = am - 1; if (MIN[AM] <= SUM && SUM <= MAX[AM]) { Prev[i + 1] = i; f(i + 1, AM, SUM); return; } } for (int l = 1; l < am-1; ++l) { int r = am - 1 - l; if (l > r) break; int SUM = sum - am + 1; int AM = am - 1; for (int vl = MIN[l]; vl <= MAX[l]; ++vl) { int vr =SUM - vl; if (MIN[r] <= vr && vr <= MAX[r]) { Prev[i + 1] = i; Prev[i + l + 1] = i; f(i + 1, l, vl); f(i + l + 1, r, vr); return; } } } } void solve() { { int sum = 0; int am = 1; int s = 2; int z = 0; for (int i = 1; i <= 5000; ++i) { sum += z; MIN[i] = sum; --am; if (am == 0) { am = s; s *= 2; ++z; } } } { for (int i = 1; i <= 5000; ++i) { int sum = 0; for (int g = 1; g <= i; ++g) { sum += (g - 1); int left = i - g; MAX[i] = max(MAX[i], sum + left * (g - 1)); } } } int kek = 1; int q; cin >> q; while (q--) { int am, sum; cin >> am >> sum; if (sum < MIN[am] || sum > MAX[am]) { cout << "NO" << endl; continue; } cout << "YES" << endl; Prev.assign(am + 1, 0); f(1, am, sum); for (int i = 2; i <= am; ++i) { cout << Prev[i] << " "; } cout << endl; } } int32_t main() { boostIO(); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int TT = 1; //cin >> TT; while (TT--) { solve(); } //Return; }
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: 101817286 #include<bits/stdc++.h> //#define int long long #define pb push_back #define pii pair<int,int> #define x first #define y second #define vi vector<int> #define vpi vector<pii> #define all(x) (x).begin(),(x).end() #define WT int TT=read();while(TT--) using namespace std; inline int read() { char c=getchar();int x=0;bool f=0; for(;!isdigit(c);c=getchar())f^=!(c^45); for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48); if(f)x=-x;return x; } inline void ckmax(int &a,int b){a=(a>b?a:b);} inline void ckmin(int &a,int b){a=(a<b?a:b);} const int M=2e5+10; int n,m,k,l[M],r[M],p[M],id[M],dp[M][256],vis[M]; vi e[M],tmp[M]; signed main() { n=read(),m=read(),k=read(); for (int i=1;i<=n;i++) { l[i]=read(),r[i]=read()+1; p[i*2-1]=l[i],p[i*2]=r[i]; } sort(p+1,p+1+2*n);int L=unique(p+1,p+1+2*n)-p-1; for (int i=1;i<=n;i++)l[i]=lower_bound(p+1,p+1+L,l[i])-p,r[i]=lower_bound(p+1,p+1+L,r[i])-p; // for (int i=1;i<=n;i++)cerr<<l[i]<<' '<<r[i]<<'\n'; // cerr<<L<<'\n'; for (int i=1;i<=n;i++) { for (int j=l[i];j<r[i];j++)e[j].pb(i); tmp[l[i]].pb(i); } memset(vis,-1,sizeof(vis)); for (int i=1;i<=L-1;i++) { int cnt=p[i+1]-p[i],S=0; for (int j=0;j<(int)(e[i].size());j++)vis[e[i][j]]=j; for (auto x:tmp[i])S|=1ll<<vis[x]; for (int j=0;j<(1<<e[i-1].size());j++) { int s=0; for (int w=0;w<(int)(e[i-1].size());w++) if ((j>>w&1)&&vis[e[i-1][w]]!=-1)s|=1<<vis[e[i-1][w]]; // cerr<<"change:"<<i<<' '<<j<<' '<<s<<'\n'; for (int tmp=S;;tmp=(tmp-1)&S) { ckmax(dp[i][tmp|s],dp[i-1][j]); if (tmp==0)break; } } for (int j=0;j<(1<<e[i].size());j++) { if (__builtin_popcount(j)&1)dp[i][j]+=cnt; // cerr<<i<<' '<<j<<' '<<dp[i][j]<<'\n'; } for (int j=0;j<(int)(e[i].size());j++)vis[e[i][j]]=-1; } int ans=0; for (int i=0;i<256;i++)ckmax(ans,dp[L-1][i]); cout<<ans<<'\n'; return 0; }
cpp
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include <sstream> #include <vector> #include <stack> #include <queue> #include <tuple> #include <cmath> #include <valarray> #include <set> #include <unordered_set> #include <ctime> #include <iomanip> #include <map> #include <unordered_map> #define pb push_back #define mp make_pair #define mt make_tuple #define ll long long #define ull unsigned long long #define ssp system("PAUSE") #define fi first #define se second #define all(x) x.begin(),x.end() using namespace std; void solution() { ll i, n, x; cin >> n >> x; vector <ll> R(n); for (i = 0; i < n; i++) { cin >> R[i]; } sort(all(R)); if (binary_search(all(R), x)) { cout << "1\n"; return; } if (x - 2 * R[n - 1] <= 0) { cout << "2\n"; return; } cout << ((x - 2 * R[n - 1]) / R[n - 1]) + 2 + ((x - 2 * R[n - 1]) % R[n - 1] != 0) << endl; } int main() { int t; cin >> t; while (t--) solution(); ssp; }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
#include <bits/stdc++.h> using namespace std; template<class A, class B> bool maximize(A& x, B y) {if (x < y) return x = y, true; else return false;} template<class A, class B> bool minimize(A& x, B y) {if (x >= y) return x = y, true; else return false;} void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(long long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ", "; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? ", " : ""), __print(i); cerr << "}";} void _print() {cerr << " ]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #define deb(x...) cerr << "[ in " <<__func__<< "() : line " <<__LINE__<< " ] : [ " << #x << " ] = [ "; _print(x); cerr << '\n'; typedef long long ll; typedef unsigned long long ull; typedef double db; typedef long double ld; typedef pair<db, db> pdb; typedef pair<ld, ld> pld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ll, int> plli; typedef pair<int, ll> pill; #define all(a) a.begin(), a.end() #define pb(a) push_back(a) #define pf(a) push_front(a) #define fi first #define se second // #define int long long const int MAX_N = 500 + 5; int n, m, q; string a[MAX_N]; int prefSum[4][MAX_N][MAX_N]; int b[MAX_N][MAX_N]; int rmq[10][MAX_N][10][MAX_N]; int convert(const char& h) { if (h == 'R') return 0; if (h == 'G') return 1; if (h == 'Y') return 2; return 3; } bool inside(const int& x, const int& y) { return x > 0 && x <= n && y > 0 && y <= m; } int get(int t, int x, int y, int u, int v) { if (x > u) swap(x, u); if (y > v) swap(y, v); return prefSum[t][u][v] - prefSum[t][u][y - 1] - prefSum[t][x - 1][v] + prefSum[t][x - 1][y - 1]; } int getMax(int x, int y, int u, int v) { int k1 = __lg(u - x + 1); int k2 = __lg(v - y + 1); int mx1 = max(rmq[k1][x][k2][y], rmq[k1][x][k2][v - (1 << k2) + 1]); int mx2 = max(rmq[k1][u - (1 << k1) + 1][k2][y], rmq[k1][u - (1 << k1) + 1][k2][v - (1 << k2) + 1]); return max(mx1, mx2); } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m >> q; for (int i = 1; i <= n; i++) { cin >> a[i]; a[i] = ' ' + a[i]; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { for (int t = 0; t < 4; t++) { prefSum[t][i][j] = prefSum[t][i - 1][j] + prefSum[t][i][j - 1] - prefSum[t][i - 1][j - 1]; } prefSum[convert(a[i][j])][i][j]++; } } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { if (a[i][j] == 'R' && a[i][j + 1] == 'G' && a[i + 1][j] == 'Y' && a[i + 1][j + 1] == 'B') { int low = 1, high = min(n, m); while (low <= high) { int mid = (low + high) >> 1; if (inside(i - mid + 1, j - mid + 1) && inside(i - mid + 1, j + mid) && inside(i + mid, j - mid + 1) && inside(i + mid, j + mid) && get(0, i - mid + 1, j - mid + 1, i, j) == mid * mid && get(1, i, j + 1, i - mid + 1, j + mid) == mid * mid && get(2, i + 1, j, i + mid, j - mid + 1) == mid * mid && get(3, i + 1, j + 1, i + mid, j + mid) == mid * mid) { b[i][j] = mid; low = mid + 1; } else { high = mid - 1; } } } } } for (int ir = 1; ir <= n; ir++) { for (int ic = 1; ic <= m; ic++) { rmq[0][ir][0][ic] = b[ir][ic]; } for (int jc = 1; jc < 10; jc++) { for (int ic = 1; ic <= m; ic++) { if (ic + (1 << jc) > m) break; rmq[0][ir][jc][ic] = max(rmq[0][ir][jc - 1][ic], rmq[0][ir][jc - 1][ic + (1 << (jc - 1))]); } } } for (int jc = 0; jc < 10; jc++) { for (int ic = 1; ic <= m; ic++) { if (ic + (1 << jc) > m) break; for (int jr = 1; jr < 10; jr++) { for (int ir = 1; ir <= n; ir++) { if (ir + (1 << jr) > n) break; rmq[jr][ir][jc][ic] = max(rmq[jr - 1][ir][jc][ic], rmq[jr - 1][ir + (1 << (jr - 1))][jc][ic]); } } } } while (q--) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; int low = 1, high = min(n, m); int ans = 0; while (low <= high) { int mid = (low + high) >> 1; int u1 = x1 + mid - 1; int v1 = y1 + mid - 1; int u2 = x2 - mid; int v2 = y2 - mid; if (u1 <= u2 && v1 <= v2 && getMax(u1, v1, u2, v2) >= mid) { ans = mid; low = mid + 1; } else { high = mid - 1; } } cout << 4 * ans * ans << '\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; 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, m; cin >> n >> m; string s; cin >> s; vi queries(m); for (int i = 0; i < m; ++i) { cin >> queries[i]; } deb(queries) vector<vi> pref(n + 1, vi(26)); for (int i = 1; i <= n; ++i) { for (int j = 0; j < 26; ++j) { pref[i][j] = pref[i - 1][j]; } pref[i][s[i - 1] - 'a']++; } vll ans(26); for (int q : queries) { for (int j = 0; j < 26; ++j) { ans[j] += pref[q][j]; } } for (int j = 0; j < 26; ++j) { ans[j] += pref[n][j]; } for (ll v : ans) { cout << v << " "; } cout << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin ("puzzle_name.in"); //ofstream cout ("puzzle_name.out"); int t; cin >> t; while (t--) { solve(); } return 0; }
cpp
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
#include <bits/stdc++.h> using namespace std; int main() { int n,q; cin >> n >> q; map<int,bool> a; map<int,bool> b; int cnt(0); while(q--){ int x,y; cin >> x >> y; if(x == 1){ if(a[y] == false){ a[y] = true; if(b[y-1] == true){ cnt++; } if(b[y] == true){ cnt++; } if(b[y+1] == true){ cnt++; } } else{ a[y] = false; if(b[y-1] == true){ cnt--; } if(b[y] == true){ cnt--; } if(b[y+1] == true){ cnt--; } } } else{ if(b[y] == false){ b[y] = true; if(a[y-1] == true){ cnt++; } if(a[y] == true){ cnt++; } if(a[y+1] == true){ cnt++; } } else{ b[y] = false; if(a[y-1] == true){ cnt--; } if(a[y] == true){ cnt--; } if(a[y+1] == true){ cnt--; } } } if(a[1] == true){ cout << "NO" << endl; } else if(b[n] == true){ cout << "NO" << endl; } else if(cnt == 0){ cout << "YES" << endl; } else{ cout << "NO" << endl; } // cout << endl; } return 0; }
cpp
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int32_t test; cin >> test; int32_t m, n; while (test--) { cin >> m >> n; if (m%n == 0) cout << "YES\n"; else cout << "NO\n"; } return 0; }
cpp
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
//Author: Ankush Bhagat (https://github.com/ankushbhagat124) //RFIPITIDS #include <bits/stdc++.h> #define int unsigned long long const int N = (int)(3e5 + 1); const int mod = (int)(998244353); using namespace std; void init() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int power( int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y & 1ll) res = (res * x) % p; y = y >> 1ll; x = (x * x) % p; } return res; } int modInverse( int n, int p) { return power(n, p - 2, p); } int nCrModPFermat( int n, int r, int p) { if (n < r) return 0; if (r == 0) return 1; int fac[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } signed main() { init(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); /* Ans = mC(n-1) * (n-2) * (2^(n-3)) */ int n, m; cin >> n >> m; if (n > 2) cout << (nCrModPFermat(m, n - 1, mod) * (n - 2) % mod * power((int)2, n - 3, mod)) % mod; else cout << 0; cout << endl; }
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" ]
//Your worst fear owns this #include <bits/stdc++.h> #define ll long long int #define srv(v) sort(v.begin(),v.end()) #define rrv(s1) sort(s1.begin(),s1.end(),greater<ll>()) #define str string #define sz size() #define dv(v) vector<ll> v #define ds(s) set<ll> s #define dm(mp) map<ll,ll> mp #define debug(x) cout<<#x<<" "<<x<<endl #define MOD 1000000007 int binpow(int a, int b){if (b==1){return a;}else if (b==0){return 1;}ll one = binpow(a,b/2);if (b%2==0){return one*one;}else{return a*one*one;}} using namespace std; int main() { int q,j=0; cin>>q; int arr[q]; while(j<q){ ll n,m; cin>>n>>m; str s; cin>>s; ll one=0,zero=0; ll xxx=0; if ((zero-one)==m) { xxx++; } for (ll i = 0; i < n; i++) { if (s[i]=='1') { one++; } else { zero++; } if ((zero-one)==m) { xxx++; } } // 10 12 20 24 30 36 ll cost = zero-one; if (zero==one&&xxx>0) { // cout<<'g'; cout<<-1<<endl; j++; continue; } else if (cost==0) { ll o=0,z=0; ll op=0; if ((z-o)==m) { op++; } for (ll i = 0; i < s.sz; i++) { if (s[i]=='1') { o++; } else { z++; } if ((z-o)==m) { op++; } } cout<<op<<endl; j++; continue; } // cout<<cost<<endl; ll pp = cost*m; // cout<<m<<endl; // cout<<pp<<endl; if (1>=0) { ll c=cost; ll o=one; ll z=zero; ll st=2; o=0,z=0; ll op=0; // if (m%cost==0) // { // op++; // } // cout<<'g'; if (m==0) { op++; } for (int i = 0; i < s.sz; i++) { if (s[i]=='1') { o++; } else { z++; } int cx = z-o; int mm = m-cx; // cout<<mm<<" "<<c<<endl; if (mm*c>=0) { /* code */ if (mm%c==0) { op++; } } // } } cout<<op<<endl; } else { // cout<<'g'; int op=0; if (m==0) { op++; } int z=0,o=0; for (int i = 0; i < s.sz; i++) { if (s[i]=='1') { o++; } else { z++; } if ((z-o)==m) { op++; } } cout<<op<<endl; } j++; } return 0; }
cpp
1313
E
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1≤l1≤r1≤n1≤l1≤r1≤n) and a segment [l2,r2][l2,r2] (1≤l2≤r2≤n1≤l2≤r2≤n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2a[l1,r1]+b[l2,r2]=al1al1+1…ar1bl2bl2+1…br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1≤x≤r1l1≤x≤r1 and l2≤x≤r2l2≤x≤r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1≤n≤500000,2≤m≤2⋅n1≤n≤500000,2≤m≤2⋅n) — the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5];
[ "data structures", "hashing", "strings", "two pointers" ]
#include<bits/stdc++.h> #define f first #define s second #define int long long #define pii pair<int,int> using namespace std; const int N = 1e6 + 5, mod = 1e9 + 7; // ! int t, fw[2][N], n, h[N], hA[N], hB[N], pwr[N]; vector<int> en[N], st[N]; void upd(int t, int id, int v) { for(id; id <= n; id += id & (-id)) fw[t][id] += v; } int get(int t, int id) { int ans = 0; id = min(id, n); for(id; id >= 1; id -= id & (-id)) ans += fw[t][id]; return ans; } //int h[N], hA[N], hB[N]; main(){ int m; cin >> n >> m; string a, b, s; cin >> a >> b >> s; a = '#' + a; b = '#' + b; s = '#' + s; pwr[0] = 1; int p = 37; for(int i = 1; i <= m; i++) { h[i] = (h[i - 1] * p + s[i] - 'a' + 1) % mod; pwr[i] = pwr[i - 1] * p % mod; } for(int i = 1; i <= n; i++) { hA[i] = (hA[i - 1] * p + a[i] - 'a' + 1) % mod; hB[i] = (hB[i - 1] * p + b[i] - 'a' + 1) % mod; } for(int i = 1; i <= n; i++) { int l = 1, r = min(m, n - i + 1), x = 0; while(l <= r) { int mid = (l + r) / 2; if((hA[i + mid - 1] - hA[i - 1] * pwr[mid] % mod + mod) % mod == h[mid]) x = mid, l = mid + 1; else r = mid - 1; } if(x) en[x + 1].push_back(i), upd(0, i, 1); l = 1, r = min(i, m), x = 0; while(l <= r) { int mid = (l + r) / 2; if((hB[i] - hB[i - mid] * pwr[mid] % mod + mod) % mod == (h[m] - h[m - mid] * pwr[mid] % mod + mod) % mod) x = mid, l = mid + 1; else r = mid - 1; } st[min(x, m - 1)].push_back(i); // en - st < m - 1; en < st + m - 1 } int cur = 0, ans = 0; for(int i = 1; i < m; i++) { for(int j = 0; j < en[i].size(); j++) { cur -= get(1, en[i][j] + m - 2) - get(1, en[i][j] - 1); upd(0, en[i][j], -1); } for(int j = 0; j < st[m - i].size(); j++) { int x = st[m - i][j]; // cout << "++++ " << 1 << " " << x << " " << get(0, st[m - i][j]) << endl; cur += get(0, st[m - i][j]) - get(0, st[m - i][j] - m + 1); upd(1, st[m - i][j], 1); } ans += cur; } cout << ans; }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
// LUOGU_RID: 94410454 #include<bits/stdc++.h> #define ll long long using namespace std; ll n,m,k,ans[10001],ansn; char ansf[10001]; inline ll read() { ll x = 0; char ch = getchar(); while (ch > '9' || ch < '0') ch = getchar(); while (ch <= '9' && ch >= '0') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return x; } signed main() { n=read(); m=read(); k=read(); if(k>(4*n*m-2*n-2*m)) { puts("NO"); return 0; } puts("YES"); for(ll i=1;i<m;i++) { if(k>(n-1<<1)) { k-=(n-1<<1)+1; if(n-1) { ans[++ansn]=n-1; ansf[ansn]='D'; ans[++ansn]=n-1; ansf[ansn]='U'; } ans[++ansn]=1; ansf[ansn]='R'; } else { if(k>n-1&&n-1) { ans[++ansn]=n-1,ansf[ansn]='D'; ans[++ansn]=k-n+1,ansf[ansn]='U'; } else if(k&&n-1)ans[++ansn]=k,ansf[ansn]='D'; cout<<ansn<<endl; for(ll i=1;i<=ansn;i++) { printf("%lld ",ans[i]); putchar(ansf[i]); putchar(10); } return 0; } } for(ll i=2;i<=n;i++) { if(k>(m-1<<1)) { k-=(m-1<<1)+1; ans[++ansn]=1; ansf[ansn]='D'; if(m-1) { ans[++ansn]=m-1; ansf[ansn]='L'; ans[++ansn]=m-1; ansf[ansn]='R'; } } else { if(k) { k--; ans[++ansn]=1; ansf[ansn]='D'; } if(k>m-1&&m-1) { if(m-1)ans[++ansn]=m-1; ansf[ansn]='L'; ans[++ansn]=k-m+1; ansf[ansn]='R'; } else if(k&&m-1) ans[++ansn]=k,ansf[ansn]='L'; cout<<ansn<<endl; for(ll i=1;i<=ansn;i++) { printf("%lld ",ans[i]); putchar(ansf[i]); putchar(10); } return 0; } } if(k>n-1) { if(n-1)ans[++ansn]=n-1,ansf[ansn]='U'; ans[++ansn]=k-n+1; ansf[ansn]='L'; } else if(k&&n-1) { ans[++ansn]=k; ansf[ansn]='U'; } cout<<ansn<<endl; for(ll i=1;i<=ansn;i++) { printf("%lld ",ans[i]); putchar(ansf[i]); putchar(10); } return 0; }
cpp
1286
C1
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard 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 (n+1)2(n+1)2.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 (n+1)2(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", "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, bool mid = true) { vector<tuple<int,int,vi>> edges; map<int, vi> mp = ask(0, n-1); //debug(mp); 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({md,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({curR, 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({0, 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 = getedges(n); vector<tuple<int,int,vi>> e2 = getedges(n-1, false); vi res(n,-1); int st; vector<vector<pair<int,vi>>> adj(n); for (auto &[a,b, cc]: e1) { if (cc.size() == 1) { st = a; res[a] = cc[0]; } else { adj[a].push_back({b, cc}); adj[b].push_back({a, cc}); } } for (auto &[a,b, cc]: e2) { adj[a].push_back({b, cc}); adj[b].push_back({a, cc}); } queue<int> q; q.push(st); 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; if (n%2 == 1) { res = trysolve(n); } else{ res= trysolve(n-1); cout<<"? "<<n<<" "<<n<<endl; string s;cin>>s; res += s; } cout<<"! "<<res<<endl; }
cpp
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
#include<bits/stdc++.h> using namespace std; #define maxn 200005 int *a[maxn],c[maxn]; int main(){ int n,m,ans=0;scanf("%d%d",&n,&m); for(int i=0;i<n;i++){ a[i]=new int[m]; for(int j=0;j<m;j++)scanf("%d",a[i]+j),a[i][j]--; } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(a[j][i]%m!=i||a[j][i]<0||a[j][i]>=n*m)continue; c[(-a[j][i]/m+n+j)%n]++; } int w=n; for(int j=0;j<n;j++)w=min(n-c[j]+j,w),c[j]=0; ans+=w; } printf("%d",ans); 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" ]
#import<iostream> int a[101],i,t; main() { for(std::cin>>t;t--;i=0) for(;i<=*a || puts(*a==1?a[1]&1?"-1":"1 1":a[1]&1?a[2]&1?"2 1 2":"1 2":"1 1"); std::cin>>a[i++]); }
cpp
1301
F
F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105)  — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m)  — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5 1 2 1 3 4 4 5 5 1 2 1 3 2 1 1 3 4 2 2 2 2 OutputCopy2 0 InputCopy4 4 8 1 2 2 8 1 3 4 7 5 1 7 6 2 3 8 8 4 1 1 2 2 1 1 3 4 1 1 2 4 1 1 4 4 OutputCopy2 3 3 4 NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4).
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
/// Nu am loc de lista de adicenta? Calculez singur vecinii. /// Nota: Nu e nev de nodurile auxiliare pentru a compresa graful - daca ma joc odata prin culoare, nu ma mai uit #include <bits/stdc++.h> #pragma GCC optimize("Ofast") #define debug(x) cerr << #x << " " << x << "\n" #define debugs(x) cerr << #x << " " << x << " " using namespace std; typedef long long ll; typedef pair <short, short> pii; const ll NMAX = 1002; const ll VMAX = 41; const ll INF = (1LL << 59); const ll MOD = 1000000009; const ll BLOCK = 318; const ll base = 31; const ll nrbits = 21; short dist[NMAX][NMAX][41]; short mat[NMAX][NMAX]; vector <pii> v[41]; struct ura { short pf, ps; int cost; }; vector <ura> muchii; short dx[] = {0, 1, -1, 0}; short dy[] = {1, 0, 0, -1}; short n, m; bool OK(short i, short j) { if(i > 0 && i <= n && j > 0 && j <= m) return 1; return 0; } int main() { #ifdef HOME ifstream cin(".in"); ofstream cout(".out"); #endif // HOME ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); short k, i, j; cin >> n >> m >> k; for(i = 1; i <= n; i++) { for(j = 1; j <= m; j++) { cin >> mat[i][j]; v[mat[i][j]].push_back({i, j}); } } deque <pii> dq; for(int col = 1; col <= k; col++) { for(i = 1; i <= n + 1; i++) { for(j = 1; j <= max(m, k); j++) { dist[i][j][col] = 32767; } } for(auto x : v[col]) { dist[x.first][x.second][col] = 0; dq.push_back({x.first, x.second}); } while(dq.size()) { pii x = dq.front(); dq.pop_front(); if(x.first != n + 1) { for(int d = 0; d < 4; d++) { pii care = {x.first + dx[d], x.second + dy[d]}; if(!OK(care.first, care.second)) continue; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1; dq.push_back({care.first, care.second}); } } pii care = {n + 1, mat[x.first][x.second]}; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col]; dq.push_front({care.first, care.second}); } } else { for(auto y : v[x.second]) { pii care = y; if(dist[care.first][care.second][col] == 32767) { /// Hmm... dist[care.first][care.second][col] = dist[x.first][x.second][col] + 1; dq.push_back({care.first, care.second}); } } } } } int q; cin >> q; while(q--) { int a, b, c, d; cin >> a >> b >> c >> d; int minim = abs(c - a) + abs(d - b); for(int col = 1; col <= k; col++) { minim = min(minim, (int)dist[a][b][col] + (int)dist[c][d][col] + 1); } cout << minim << "\n"; } return 0; }
cpp
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) int main(){ fast_cin(); int test; cin >> test; while(test--){ int n; cin >> n; int a[n]; unordered_map<int,int> mp; for(int i=0;i<n;i++){ cin >> a[i]; mp[a[i]]++; } vector<int> res; bool ck = false; for(int i=0;i<n;i++){ int k = a[i]; if(k>2*n){ cout << -1 << endl; ck = true; break; } else res.push_back(k); while(mp[k]){ k++; } if(k>2*n){ cout << -1 << endl; ck= true; break; } else{ res.push_back(k); mp[k]++; } } if(ck) continue; for(int i:res) cout << i << " "; cout << endl; } return 0; }
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" ]
/* . . . . . i72 . . . . . . . . ,. . . . . . iS: ..,,,.:.:,,.. . . . Xr::;X77;;;;iiiiiiii::::ii::.. . . . .;rX;SXi., . .:iii::.. . .7aaX;: :X .,::., . . .rSaS: iS .,::: :X27 ,, :,. .:i:, . . . ;XX, . .,;;;i,. . .,i.. . . ;Sr ,,ri:. .,, .:i. . . . 7Zr .,r;: :, i,. . :a2. .. .;r, . .,:. .:: . . aa ... . . iX; .., .:,. .i, . . ;87 .:. . .. ir: ... ,. ,::. ::. X2 ,. :. ::.;i. ,. ;r. ,, .,. ..:i. .:: . . . 8r :. . i, .;r2X;2BBS;..,, .i: .: .::.. ,i: :i . . . . . . ;W, 7. ;7 .. ,r i,X8i ,Xa27: ::. . . ,; :, :i,, :; :. . . :W, iBX .X . ; ,r: aB. r2S;,.: ,, ,.. .. i, :,. ,:i, .i ;: . . . . . . :Z .aZiX; ::. .i7 :: aB. ,SXi:i: .i. ,.. ... ii ,:. :::: i, ;i 2. XXiXXr:,..: ,,:XS0. :i:2ai :,.,. ,....., ,i. .i. .:,:i :. :, X , 7 iZZ8aXS08a8S2:2; . .:208.:: .. ,,..:.,. .:. ,i, .,.:; i. ,, . Xi i. ;r ;7ZZ8ZS7;:. ,:Z XB0;7S, : .i .,:,. i. .,:. :, ;; i. :: . . . XZ i; a .X:: : Xr0, . . . . i08r8Zi . i: :i,. .;. ..,:. : ri . X r. ,B S, . 7Z ;i;: : .r 8SX 7;iX7ai X; .iii .X. .,,, .: r. ..; ; Zr r7 0; X X: :; r ZB;, . ,aiZ7 Xr :ri ,7 :.,..,. .r ,.:, :7 . i8 Xr .B :i S: r. 0 00r ;X X2 7r .;i iS :...., :i i , ;i . . 2, iS: . a0 r .a ir 88r88; , ;2 ,;8S i: 2X ., ,. ;.. .. . ; . XB rS. , 87 7 :X:.7: BaZ7Xi . ,7 7782 7r 8i ,. : .X , 7 ,r . . . BX .;S .; 0 :: :r7,: S0rZ , . . . .; XSrr. X. B . ., iir i, 7i . ;W XX, ;:.0 ;. :Xr 022X ,.8a aX. r ;Z . .rS, . X . Z2 XX:. X.r0 r :Z7 28 Zr . i8 2X 7r Zi 7S: i :; . ... . . Z, Sr;, a 28 i i2: 88 0i . . :;X7r;rXX;;ir707 27 Z ,0 iX. ;, r. ..::,::,ii:,:, . . .Z i 77ri :2 a2 , ,,X .B: aX . . . ;Zar;;:.. .. ,7X. ,Zr 7S Br .X :i ii ..::;i;ii:,:i::,,.. . . . S0 .r rr7: rS 8a ;i X. ;B .: .ZZi ,. 8i 0 :8 ,. .B. .r .:,.,Xiii;::,,..,:.,,, . ,i . . . 0S 7r :7rr Xr 80 Si 7. XB . . ;, . i0 82 0: i :B Sai;:. . . ,.. . .,i:. B, 0X .r7X 7; 08 0, ;; X8 . . . . Z7i8 8Z i. iZ i .,,.X7,. .::,. . . . . . . 0. B; ;X2:7: Z0 B: X2 28 :,. . . .aXZi70 i, 2; iaXi:: r :;i, . .. . . .B 0, ,7SXr. 7B W, ;8 8Z rXa88aZ0W07. . . . ;SrXrZ .r 8 X7. , .::: . . . ,8 B: ;SZX iW Bi ,BaZa ;X2Xi, ,. . . 2.Z;X, S X; : X i :;;. . .. . . . :a @7 .r8S W. 0, XWZZZ87. . . ,iii7Z880008a2r: . 8i7r S :7 X, X . .:r, . . ... . . iZ WX ,8Z BX 8S rZZBZ, 7;7ZB@M@@WB0BBWW@WBZ. S 7; Z X Xi 0, ,i,. . . ... . ;a 08 S8 00 80 ;B70a. . . X828B@W0r ,70aS: ;:.0 ; 77 .W; . :;: , ... ... . X8 .0B 0: 2B rB rB :0, . . . 28ZW@WZ i X0: Xr 28 .i :;2Z . .. . . . X0 ZaW ;a B 0 B , . . . . . ;BXWB0r .. . r:2S Xi ..X i :XX: 7 . ..... . rB 0r0: X: B8 B2 0; . . . . , ... . ....:., . 0i:;7 i:i : ;Xi . :r , .,.. ... ,W 0ZZZ . .; aB 8B 02 . . .,,,:,,:;:, XaZ0, XiX iXX:Z .. S . . , ,.. ..... B aWr8 . W.rB;Z8 rr7SaZaaaSr;, . . . ,,:,,::.,,:. ..:i2Z8ZXZa ,Sri,S87. X2 : X; ... . , .......... Z: @2ar ZB 0SaZ 80ZSa8B@MMMMMMMWBX . . ,i,.... . ,:7X; a2Z, 8iSa2r ,8 ,..0 . ... . , ,.,,,.,... ;X B820 @SS22Z: 22;8MMMWBZZ2aZ80WBS . . .,,. . . ;8aS 8Z2: , S. .:: 8r ,., , ,,........ .S aWS0Z . W0 222: 2aBMMW; . i:: . :87Xr 80r8X ,: ;i ,:; :X . ... , ,.....,.,.. 2 WZS0 ;WX220i ;WMMB , :r;r;r;. . . . :X XZ S0; r02 ., ;7 iii S. . . .,. . . .,...,.,.,. 0W 08220 . W@SrZZ .@Z; . .::: . . SS;;;;;7. . . . i0 X8aZ 08 ; i0 :ii 7a . . . . , ,.....,... @B 02aZ8 . aMBS ; . ..: ,ii:. .,,rrr;;. . . ;B ,80ri0; 88, .; iB ,i,: B ... . , .,,,.,.,.. XB S a0ZZZX . 0MBS ,i:,.::i,. ,:: . :0 i88Zi 80 XB: 7. .S. r.i rX . : :.,.,.. 0Z @Z 8r ZZZ 8MM: . .i;,,,,,. . ,r iZ8XiZ,:iB 07 :7: :S.. ;.,: a .. . . , ... :rXa0: .8r ZSZ88a ZM@ .i;,., . ,i:;rX8i iXiXXXS. 8X::.02 0X iX: :a i i..r ;; ..,. . . . ,X8S7Srr:77SZBr a Z80. S rMB .ri..i .:r7X22X7X222Z80MZ SBX;, 28.i;.88 8S .i7i ;a,i :, ZS X .,,. . . : iX2SSa77aSZ2;, 0S,Z, X80. Br.B8 :. . . ;Z0882Xrr;;i;::,. SW. i82, .07:;i:20 0X i:Si rXi;., r0 Z: .:,., . . BZSXX;i:i 8ZXZX a8. Ba 88 . 2WBZriiii;i;i;i;iii 80 ;, 8X,;;i:rZ 0; .r,S. r.;;. .0 i7 .,.i, . 77X7XX72S7;8SriX:7r.78a2ZZ 7i ,.8822X @MM8.,;;;;;;;i;;;iii,XW 0Z:i;;;;iX Z, :r:S ,a i7. B: S .:::.. .. .BX72Z7BiW0XZaa2ZZ8Z0B0 .ia8ZZZZS, XMMa r;r;r;;;;i;;;::XBi . 08:r;;;ii;S:; ;:S; a8 i;. 0r 2. ,.,.:,,::., , ,..,,,. r0 :Z7;W @r XZ7rZ8088Z00Z ,2aZMW2XZ8X BWX:;;r;;;;;r;;ii8B. .B0.;;;;;;:i8i ,ria ,82 .i . B8 S; .....,i:::;; : :,:,:,: aX,;0:,@,0i Sa8 .,.r;[email protected] 2B0X;;;ir;;i;rZ8a . X20Z:;;;;;;ir8: ;.Xi a82 ; ; 0B ;X .. ...,.,:: , ::,::,. 8i,2B: W7B7 ZXZ X0X BaZ,aWW80Z; ;88SXSXXSa2S; . . .ZX ZZ:;;r;r;iX0 ::.7 a,0 ; .7 :0Z r . ... :. : i::,:,,.0 ,Z0: 00ir BrZ @8 7BZZ 28Z2 .. . .;X;rri. . . rZ: ;Z;;;;rr;:ZS i X.a::; ,; i7 ;XZ; 7 ,. . . . . : ::,:,,.i0 .ZZ: XB Waa7 . 0W i0Za 02X8Z . . . :BS .8;rr;;r;;8. . r,rr 7 :: X, ;.XX 7 .. ..... . i i::,:,.iB ZSZ, B7 B8rZ i XW: Z0r B2;XZ8; . . . . . . . 827. 87;rrr;iaS ,S,;7 ii : .S 7 ;X ;. ,.. ... .. : :,,:,, ;0 BXa2 .W0 8B ZS r: W8 88i 0SX7ra082 . . . . . Z00r 2X;rrrr7a .SZ:X0 i 2X .Z iX S...... . . .. ; :,:::, XW W8 8.S0Z; SMZ.Z2 2 0W Z0; B27XXXraZ08; . . . ... 80S 2BS; SZ;rrrXZX80; ZB: . .B S2 7X X, ,...:.. ... ; i:,:,, rW 8M 788a.B BWX:Z2 :8 WZ XBZ BSXXXXX77XaZZ2XXX: . . ... . .0W0 a0S;.:.S02SSS8Zi ,8Br . . B2 Bi.aX a:,,....:.,.,, 7 i::,::..W :WX ,BZ Wa XW8::SZ SZ iB W8 8arSXXXXXX7XXSSaZ8a0Z2;: . . :8@@: 7ZZZX. iZ88; . . XB Z8i;Zi ar;i:i: .:..,, r :::,::. BZ 88,r.2aWB 80a;.7Z7aa: 0B XW ZZ7XXXSrXXXXXXX7X7,8B2Z808ZZ2, .80WBZ .a80ZZ8ZX;i.;08ZZ: . :B. .0: ,X .8i;;7r7;:::,,. 7 i::,::: Z0 Bi Za:XZ 7B882 :Z8aaX 00 Z8.ZXSXXra2XXXXS;a2i2M8XXSSaaZZ8ZZa2XZZ08Z2 ,iSZZ88Z88088: :ZWZr2:.. . . :W7 0S . 7 i7 :i;77r::i., X i:,:,,,. B, rW ZZ2Zi7. :; X; 78SS2i ZZ Za2a7XXSZ272XSr28S,8MMWB8Z22S2S22ZZZZ8ZaXXSZZ8808088ZZZ2S7 .XZBWZ,;,:. 2@Z aZ ..,Z r; . ..,i;;;ri X ;:,,:,,. iB :80a 0:8BX 8Z7. ;r;XX,aZ :XZ27Xa27SSXXS8ZriZMW@@@@@@@WWWWW@MMMBZaZ008Za2SSSX;;;;,:Xa00BB8iii. . 8@8 ra ..7X 7..,, ,.. ,iXX; X i:,:,,,:. a0 B0 0 00 ZB8Z, . .;i2Z :aZ2S2SSXX2S2B2X:a@BWWBWWWW@W@W@MBXX2ZaaaZaZZZZZZZaZa80888Z80Z ,,. . ,08, a8...,.2: ;,,. ..:,. .:XX X ;::.,,,,,, 8B rZW r0X X80Zi .ZZ 2Z2SXX22SS8a;XXXZWWBWBWWWW@W@BZa7X0aZaZaaaZaZaZaZaZa88aZ0a:.Xi . 0W8 .Z8 ,:,,X .:,, ,.,:.,, ,X: 7 ii,,.:,,,:, XB; 887: aS; .ZZ0; rS.r7:XaaZ2 iZ2222S2B@WWW@W@@@B80BSZZZZ0aZaZaZZZaZaZaaaaZ0ZZr ,7. rBWW2 7aB8Sr: :: 2,,:: .,:,::,,.,, X ;:::::i:i::: ;0a: ;X2Xr .r882 iri:,:ZZiX2ZaZ0Z.,a8aaX 78@M@M@M@@WBZ2XZBaaZaaZZZZZaaaaZaZZZZ8aaS222S; . ,SB@MWZ irr: ,;S00a7 ri .,..:,,,,,. . r ;i:i:i:i:i::,. 7B0: ;aaXriaWMZ S8ZZ2:;8ZX 7Z2rrS8@MMM@WWWB0ZaXSSaZBaZZZaZ2X288ZZZZ8aaZZ2277i raX:iX8BMBZi .72: Z7 B0Xr,. . .:...,. r ;ii:iiiiiiiiiii 28SW02i . ,;XZZ822Saa2:,:7iiX7i78MMMMMMBZZaS7:iSZZaZWZaZ88ZZaX,SZ08088a2:XS;:7X2aZ00X. .SB0; . . X ri;Z08Z0ZXr;:,.. . r ii:i:iiiiiiiii::.8 BZiaZZ0ZZX77XZ008ZZ2X7X2a27;;i:. 7Z8ZZaZaWZZ7.a8aZZZX ;: ,X2Z7i:, ;2a8W@MMi ... a,:i :7XXaSZZaXr; r ;iiiii;iii;iii:, ;.X0a0B08r;SXXrSXX2ZZZZaZZaZS, .,S28W8ZZZaa2aBZ227ZZa2ZZ8ZaaZ22Z00W@MZ 7SZ8BW@@@WB8MMZ .. 2S22 ,:,r7Sa r ;;i;i;;;;;:::, .X80 0Z: .i;X00aZ0ZaS22ZZBB0WBaBMMZ08BW0ZMB8808880ZZZ0WW8ZBMWW0aXS0MMM@W00ZZ22S0M8 . .. 2Z8B . . B r ;i;i;ii:ii:. ,888SZZ,a . . ... ... .. 2MM08MMMMMMM@0Z@M8S8WMB2a0@BaB088MWB8ZZBBZ2ZWM8a0aaMMM0Za2222a222WM0 . . 2ZZB .. . . . 20 ; ;;iii;i;ii.S8MMa B:2i ........,.......... MMMM8@MMM@@82Z0WMWZa0@BZXZWZS22ZZZZ0BWW0SZ@B2288Z@BZS22aaaaZaaSBMB ... ZZZ8 . . . . BB r r;;;;;;;;,8ZZM@a rBi8, ...,...,.,.......,.. 0MMMM@@MMZWZaZ82@MMZSWWWW8MMM@WBB000822S8W8S2a0ZB8a2aaZaZaZaaS0MW ... :88Za . . . . . ZMB r ;;;r;;;r;.8r:MWZ .. 08aB ...........,...,... XMMM@M@M@Z8ZaZ0a2MM a0WMMMW8aX , Z0aS2ZB8Z28ZaaZaZaaaa20MW . 78ZZX . ..... .. .@@0 7 r;;;;;;;; ZZ 0M0 , Z20W ..............,,, @MMM@MMW002aZMBZ@M. iZ00Za ZW0a8WBZZ2a8ZaZaZaZaaS8M@ . ,08Xa; . ... . B@MS r rr;r;r;;.aMW ZMMi ., :8i0@, ....,...,...,.,.: 2MM@M@MWW8ZZBMB.:Z80B2 ;Z0WBaa8@B2ZZZa8ZaaZaZaa28MW ,Z0S2X ..... . . . 8MMB 7 r;;;r;r.ZWS8iXMM0 .. iX 0M8 ..........,,,.,. MMM@MMM@0BBWM272a0; .. ,Z@MMM@ZZZM@22Z80aZ0ZaZZZaZ28MW ;08a7r: . . . . .. X@M@; 7 rr;r;r:2@7 8Z MMW .,. .i.;W0: ... ..... ;a8MMM@M@@0W@MB 2@Z . . ,00MMMMMWZaWMMM@0Za808Z0aZZZZZ20M0 .;808Xrri ..... . .. .... .WM@Z , X 7rr;;iiBa .0 ZMMa .,.. .;;,X2S7: .:rZZ87 WMMM@M@@MMa Z8 .. :0@0,ZMMB0BBMMWZ27a2,:SX2aaaZZ8ZBM0 :2ZSS;,;Xi . . . . ..... . . WMM8 :a 7 rr;r;:88 .. a7 MMM .,... rSaSaS;;;rXSS;r8B0Z. SMMMMMMMMXi8X .,. 007 .XBB8ZaX Z .ZZ2XX,. i2S iiri,.:;: . . . . ........ ... BMM0 8 X rrrr:80 .., ,8 ZMMZ .,,.. . iXa82SXXrrX2ZaX. .. ZMMMMW2.Z8 ,,,. .BBZ 70B8 .r8ari:,8080B@0 .77r;i,. .. . . . . ... ... . 0MMW 0, 7.rr;iX0 .,.. 0Z MMM ,.,..... :i;;:.:. ..,, WMZ. 20S .., ;WZ;WBX: . ;X2a8X.7i 2WBB@M@r . ... . . .. ....... 0MMW ai X 7r;iBX .,.,. .@ aMM0 ,,,.,.... . ...,,,., Wa :W0 ., 0@0aX. . ZBB0ar: .;:ZMBW@M8 ..,.... . ....... . . .. ....... BMM@ 2; . X.XXi8B ,,,,:. Z0 MMMr .:,::,,,.,,,.,.,,,.,,:,,,:, rM rW7 .,,rBB0W@2 ,,:. X0WBa. ., 2BMWWMMX ,,,.,.,...,.,.... .. ... .,..., BMM@, ar .. r 8 Z MM0 i0 a ZS ,70M@0Z8a 8WB8 7, */ #include<bits/stdc++.h> using namespace std; #define ll long long const int N=3009; ll dp[N][N]; int par[N][N],chil[N][N]; int n; vector<int>a[N]; ll res=0; void dfs1(int u,int pa,int g){ chil[g][u]=1; for(int v:a[u]){ if(v!=pa){ par[g][v]=u; dfs1(v,u,g); chil[g][u]+=chil[g][v]; } } } ll bt(int u,int v){ if(dp[u][v]!=0||u==v)return dp[u][v]; dp[u][v]=1LL*chil[u][v]*chil[v][u]+max(bt(u,par[u][v]),bt(v,par[v][u])); return dp[u][v]; } void giai(){ cin>>n; for(int i=1;i<n;i++){ int x,y; cin>>x>>y; a[x].push_back(y); a[y].push_back(x); } for(int i=1;i<=n;i++)dfs1(i,i,i); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++)res=max(res,bt(i,j)); } //for(int i=1;i<=n;i++)dfs2(i,i,i); // for(int i=1;i<=n;i++){ // for(int j=1;j<=n;j++)cout<<i<<" "<<j<<" "<<chil[i][j]<<'\n'; // } // cout<<'\n'; cout<<res; } int main(){ if(fopen("solve.inp","r")){ freopen("solve.inp","r",stdin); freopen("solve.out","w",stdout); } ios_base::sync_with_stdio(false); cin.tie(NULL); giai(); }
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; 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; } vi vals(n); map<char, int> target; for (int i = 0; i < 26; ++i) { if (indexes[i].first == indexes[i].second) continue; target[char('a' + i)] = indexes[i].first; } //deb(target) map<char, int> temp; for (int i = 0; i < n; ++i) { if (i > indexes[s[i] - 'a'].first + temp[s[i]]) { vals[i] = 1; } temp[s[i]]++; } vi og = vals; //deb(vals) for (int i = 0; i < n; ++i) { map<char, int> seen; char lowest_char = 'z' + 1; int char_index = -1; int target_index = -1; for (int j = 0; j < n; ++j) { if (j > indexes[s[j] - 'a'].first + seen[s[j]] && s[j] < lowest_char) { lowest_char = s[j]; char_index = j; target_index = seen[s[j]] + indexes[s[j] - 'a'].first; //deb(j) } seen[s[j]]++; } if (target_index == -1) break; //deb(lowest_char, char_index, target_index); for (int j = char_index; j != target_index; --j) { if (vals[j] == vals[j - 1]) { cout << "NO\n"; return; } swap(s[j], s[j - 1]); swap(vals[j], vals[j - 1]); } //deb(s) } cout << "YES\n"; for (int i = 0; i < n; ++i) { cout << og[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
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define int long long #define sort(v) sort(v.begin(),v.end()) void solve(){ int n,x; cin>>n>>x; vector<int> v; int ans=1e10; int mx=0; for(int i=0;i<n ;i++) { int t; cin>>t; if (x%t==0) { ans=min(ans,x/t); } mx=max(mx,t); v.push_back(t); } // cout<<ans<<endl; if (ans==1) { cout<<ans<<endl; return; } int ct=0; ct=(x/mx); if (ct==0) { ct+=2; } else { ct+=1; } ans=min(ans,ct); cout<<ans<<endl; } signed main(){ fast int t; cin>>t; while(t--) { solve(); } return 0; }
cpp
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
#include <bits/stdc++.h> using namespace std; const int N = 5005; int n; basic_string<int> e[N]; int d[N], p[N], w[N]; void dfs(int x) { for (int y : e[x]) { if (y == p[x]) continue; p[y] = x; d[y] = d[x] + 1; dfs(y); } } void vis(int a, int b, auto f) { while (a != b) { if (d[a] > d[b]) swap(a, b); f(b); b = p[b]; } } pair<int, int> g[N]; struct upit { int a, b, c; }; int main() { cin >> n; for (int i = 1, u, v; i < n; ++i) cin >> u >> v, e[u] += v, e[v] += u, g[i] = {u, v}; dfs(1); int q; cin >> q; vector<upit> v(q); fill(w + 2, w + n + 1, 1); for (auto &[a, b, c] : v) { cin >> a >> b >> c; vis(a, b, [&] (int x) { w[x] = max(w[x], c); }); } for (auto &[a, b, c] : v) { int mn = 1e9; vis(a, b, [&] (int x) { mn = min(mn, w[x]); }); if (mn != c) { cout << "-1"; return 0; } } for (int i = 1; i < n; ++i) { auto [a, b] = g[i]; cout << w[d[a] < d[b] ? b : a] << " \n"[i == n - 1]; } }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
#include<bits/stdc++.h> using namespace std; const int maxn=2e5+10; typedef pair<int,char>pii; vector<pii>ans; int n,m,k; void run(int cnt,char ch){ if(!k||!cnt)return; if(cnt>=k){ ans.push_back({k,ch}); k=0; return ; } k-=cnt; ans.push_back({cnt,ch}); } void solve(){ cin>>n>>m>>k; if(4*n*m-2*n-2*m<k){ cout<<"NO"<<endl; return; } cout<<"YES"<<endl; run(m-1,'R'); for(int i=1;i<m;i++) run(n-1,'D'),run(n-1,'U'),run(1,'L'); for(int i=1;i<n;i++) run(1,'D'),run(m-1,'R'),run(m-1,'L'); run(n-1,'U'); cout<<ans.size()<<endl; for(auto x:ans) cout<<x.first<<" "<<x.second<<endl; } int main(){ int t; t=1; while(t--){ solve(); } return 0; }
cpp
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
#include<iostream> #include<iterator> #include<algorithm> #include<bits/stdc++.h> using namespace std; #ifndef ONLINE_JUDGE #include "local_dbg.cpp" #else #define debug(...) 101; #endif typedef long long int ll; typedef long double ld; typedef std::vector<int> vi; typedef std::vector<ll> vll; typedef std::vector<ld> vld; typedef std::vector<std::vector<ll> > vvll; typedef std::vector<std::vector<ld> > vvld; typedef std::vector<std::vector<std::vector<ll> > > vvvll; typedef std::vector<string> vstr; typedef std::vector<std::pair<ll,ll> > vpll; typedef std::pair<ll,ll> pll; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update> #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define pb push_back #define nl "\n" #define all(c) (c).begin(),(c).end() #define iotam1 cout<<-1<<nl #define cty cout<<"YES"<<nl #define ctn cout<<"NO"<<nl #define lmax LLONG_MAX #define lmin LLONG_MIN #define sz(v) (v).size() #define deci(n) fixed<<setprecision(n) #define c(x) cout<<(x) #define csp(x) cout<<(x)<<" " #define c1(x) cout<<(x)<<nl #define c2(x,y) cout<<(x)<<" "<<(y)<<nl #define c3(x,y,z) cout<<(x)<<" "<<(y)<<" "<<(z)<<nl #define c4(a,b,c,d) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<nl #define c5(a,b,c,d,e) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<nl #define c6(a,b,c,d,e,f) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<" "<<(e)<<" "<<(f)<<nl #define f(i_itr,a,n) for(ll i_itr=a; i_itr<n; i_itr++) #define rev_f(i_itr,n,a) for(ll i_itr=n; i_itr>a; i_itr--) #define arri(n, arr) for(ll i_itr=0; i_itr<n; i_itr++) cin>>arr[i_itr] #define a_arri(n, m, arr) for(ll i_itr=0; i_itr<n; i_itr++) for (ll j_itr=0; j_itr<m; j_itr++) cin>>arr[i_itr][j_itr] #define pb push_back #define fi first #define se second #define print(vec,a,b) for(ll i_itr=a;i_itr<b;i_itr++) cout<<vec[i_itr]<<" ";cout<<"\n"; #define input(vec,a,b) for(ll i_itr = a;i_itr<b;i_itr++) cin>>vec[i_itr]; #define ms(a,val) memset(a,val,sizeof(a)) const ll mod = 1000000007; const long double pi=3.14159265358979323846264338327950288419716939937510582097494459230; ll pct(ll x) { return __builtin_popcount(x); } // #of set bits ll poww(ll a, ll b) { ll res=1; while(b) { if(b&1) res=(res*a); a=(a*a); b>>=1; } return res; } ll modI(ll a, ll m=mod) { ll m0=m,y=0,x=1; if(m==1) return 0; while(a>1) { ll q=a/m; ll t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; } if(x<0) x+=m0; return x;} ll powm(ll a, ll b,ll m=mod) {ll res=1; while(b) { if(b&1) res=(res*a)%m; a=(a*a)%m; b>>=1; } return res;} void ipgraph(ll,ll); void ipgraph(ll); ///for tree void dfs(ll node,ll par); //******************************************************************************************************************************************* / const ll N=2e5+5; // ll inp[N]; // vll adj[N]; ///for graph(or tree) use this !!-><-!! void ok_boss() { ll n,m,moves; cin >> n>>m>>moves; ll tot_moves=4ll*n*m - 2ll*n - 2ll*m; if(moves>tot_moves) { c1("NO"); return; } vector<pair<ll,char>> needed; f(i,1,m) { if(n-1) { needed.pb({min(moves,n-1),'D'}); moves-=min(moves,n-1); if(!moves) break; } if(n-1) { needed.pb({min(moves,n-1),'U'}); moves-=min(moves,n-1); if(!moves) break; } needed.pb({min(moves,1ll),'R'}); moves-=min(moves,1ll); if(!moves) break; } f(i,1,n) { if(!moves) break; needed.pb({min(moves,1ll),'D'}); moves-=min(moves,1ll); if(!moves) break; if(m-1) { needed.pb({min(moves,m-1),'L'}); moves-=min(moves,m-1); if(!moves) break; } if(m-1) { needed.pb({min(moves,m-1),'R'}); moves-=min(moves,m-1); if(!moves) break; } } if(moves && (n-1)) { needed.pb({min(moves,n-1),'U'}); moves-=min(moves,n-1); } if(moves && (m-1)) { needed.pb({min(moves,m-1),'L'}); moves-=min(moves,m-1); } c1("YES"); c1(sz(needed)); for(auto ok : needed) { c2(ok.fi,ok.se); } return; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("error.txt", "w", stderr); #endif fast; /// std::cout << fixed<<setprecision(15); ///activate it if the answers are in decimal. ll qq_itr = 1; //cin >> qq_itr; while (qq_itr--) ok_boss(); return 0; } /* void ipgraph(ll nodes_ipg,ll edgs_ipg) { f(i,0,nodes_ipg) adj[i].clear(); ll fir,sec; while(edgs_ipg--) { cin>>fir>>sec; fir--,sec--; ///turn it off if it is 0-indexed adj[fir].pb(sec); adj[sec].pb(fir); ///remove this if directed !!! } return; } void ipgraph(ll nodes_ipg) { ipgraph(nodes_ipg,nodes_ipg-1); } void dfs(ll node,ll par=-1) { for(ll chd : adj[node]) { if(chd==par) continue; dfs(chd,node); } return; } */
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include <bits/stdc++.h> using namespace std; int t,a,b,p,i,c; string s; main() { cin>>t; while (t--) { cin>>a>>b>>p>>s; for (i=s.size()-2,c=0; i>=0; --i) { if (c!=s[i]) { c=s[i]; p-=(c=='A'? a: b); if (p<0) break; } } cout<<i+2<<endl; } }
cpp
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
[ "data structures", "dsu" ]
// LUOGU_RID: 102527342 #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int ch[N][2], fa[N], siz[N], rev[N], n, m, a[N], pid[N], id[N]; inline bool is_root(int x) { return ch[fa[x]][0] != x && ch[fa[x]][1] != x; } inline bool get(int x) { return ch[fa[x]][1] == x; } inline void pushup(int x) { pid[x] = max({id[x], pid[ch[x][0]], pid[ch[x][1]]}); siz[x] = siz[ch[x][0]] + siz[ch[x][1]] + 1; } inline void pushdown(int x) { if (rev[x]) { int &ls = ch[x][0], &rs = ch[x][1]; swap(ls, rs); if (ls) rev[ls] ^= 1; if (rs) rev[rs] ^= 1; rev[x] = 0; } } inline void pushall(int x) { if (!is_root(x)) pushall(fa[x]); pushdown(x); } inline void rorate(int x) { int y = fa[x], z = fa[y], chx = get(x), chy = get(y), &t = ch[x][chx ^ 1]; fa[x] = z; if (!is_root(y)) ch[z][chy] = x; ch[y][chx] = t, fa[t] = y, t = y, fa[y] = x; pushup(y); } inline void splay(int x) { pushall(x); for (int f; f = fa[x], !is_root(x); rorate(x)) { if (!is_root(f)) rorate(get(f) == get(x) ? f : x); } pushup(x); } inline void access(int x) { for (int f = 0; x; f = x, x = fa[x]) { splay(x), ch[x][1] = f, pushup(x); } } inline void make_root(int x) { access(x), splay(x); rev[x] ^= 1; } inline int find_root(int x) { access(x), splay(x); while (ch[x][0]) pushdown(x), x = ch[x][0]; splay(x); return x; } inline void split(int x, int y) { make_root(x); access(y), splay(y); } inline void link(int x, int y) { make_root(x); fa[x] = y; } inline void cut(int x, int y) { make_root(x); if (find_root(y) == x && fa[y] == x && ch[x][1] == y) { ch[x][1] = fa[y] = 0; pushup(x); } } signed main() { // freopen("P3203_1.in", "r", stdin); cin.tie(nullptr)->sync_with_stdio(false); cin >> n >> m; for (int i = 1; i <= n; i++) siz[i] = 1, pid[i] = id[i] = i; for (int i = 1; i <= n; i++) { cin >> a[i]; if (i + a[i] > n) link(i, n + 1); else link(i, i + a[i]); } for (int i = 1, op, v, k; i <= m; i++) { cin >> op >> v; if (op == 1) { split(v, n + 1); cout << pid[n + 1] << ' ' << siz[n + 1] - 1 << '\n'; } else { cin >> k; if (v + a[v] > n) cut(v, n + 1); else cut(v, v + a[v]); a[v] = k; if (v + a[v] > n) link(v, n + 1); else link(v, v + a[v]); } } return 0; }
cpp
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int n, m; cin >> n >> m; vector<int>a(n); ll sm = 0; for (int i = 0; i < n; i++) { cin >> a[i]; sm += a[i]; } cout << min(1ll * m, sm) << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } return 0; }
cpp
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
#include<bits/stdc++.h> using namespace std; //common file for PBDS #include<ext/pb_ds/assoc_container.hpp> //including tree_order_statistics_node_update #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; //macro definition template <typename T> using ordered_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 (0-indexed) //3. st.erase(st.find_by_order(st.order_of_key(k))) :to erase a single occurence of k from the set //Optimisations (Black Magic) #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #define ll long long #define lld long double #define ull unsigned long long #define rep(i, n) for (ll i = 0; i < n; i++) #define repk(i, k, n) for (ll i = k; k < n ? i < n : i > n; k < n ? i++ : i--) #define input(vec) for (auto &el : vec) cin >> el; #define print(vec) for (auto &el : vec) cout << el<<" "; #define bit(x) __builtin_popcount(x) #define bitll(x) __builtin_popcountll(x) #define popb pop_back #define pb push_back #define eb emplace_back #define ub upper_bound #define lb lower_bound #define ff first #define ss second #define um unordered_map #define om ordered_map #define all(x) (x).begin(),(x).end() #define minpq priority_queue<ll,vl,greater<ll>>pq; #define maxpq priority_queue<ll>pq; #define uniq(x) (x).erase(unique(all(x)), (x).end()) #define precision(x, y) fixed << setprecision(y) << x #define PI 3.1415926535897932384626 #define sz(x) ((ll)(x).size()) #define r_search(a,b) regex_search(a,regex(b)) //search b in a #define r_match(a,b) regex_match(a,regex(b)) //match b in a #define r_replace(a,b,c) regex_replace(a,regex(b),c) //replace b with c in a #define present(b, a) ((a).find((b)) != (a).end()) //if b is present in a #define nl '\n' const ll mod = 1e9 + 7; //1000000007 const ll mod2 = 998244353; const ll inf = LLONG_MAX; const lld epsilon = 1e-12; typedef pair<ll, ll> pl; typedef pair<char,char> pc; typedef pair<int, int> pi; typedef pair<lld, lld> pd; typedef vector<ll> vl; typedef vector<char> vc; typedef vector<pl> vpl; typedef vector<vl> vvl; typedef vector<int> vi; typedef vector<pc> vpc; typedef vector<pi> vpi; typedef vector<vi> vvi; typedef vector<string> vs; typedef vector<vector<string>> vvs; // #ifndef ONLINE_JUDGE #define debug(x) cerr << #x <<" "; _print(x); cerr << endl; // #else // #define debug(x) // #endif void _print(ll t) {cerr << t;} void _print(int t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(lld t) {cerr << t;} void _print(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(unordered_map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} 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); } }; // ------------------------Do not write above this line----------------------------------------------------------------------------------------------------------------- void solve(){ ll n,m,k; cin>>n>>m>>k; vl vec(k); input(vec); vl adj[n+1]; for(int i=1;i<=m;i++){ ll a,b; cin>>a>>b; adj[a].pb(b); adj[b].pb(a); } vl start(n+1,1e18),end(n+1,1e18),visited(n+1,0); queue<ll>q; q.push(1); ll d=0; while(!q.empty()){ auto sz=q.size(); for(int i=0;i<sz;i++){ auto f=q.front(); q.pop(); visited[f]=1; start[f]=min(start[f],d); for(auto child:adj[f]){ if(!visited[child]){ q.push(child); } } } d++; } for(int i=1;i<=n;i++){ visited[i]=0; } q.push(n); d=0; while(!q.empty()){ auto sz=q.size(); for(int i=0;i<sz;i++){ auto f=q.front(); q.pop(); visited[f]=1; end[f]=min(end[f],d); for(auto child:adj[f]){ if(!visited[child]){ q.push(child); } } } d++; } // debug(start); // debug(end); ll ans=start[n]; ll res=0; ll mx=-1e18; vpl v; for(auto it:vec){ v.pb({start[it]-end[it],it}); } sort(all(v)); // debug(v); for(auto it:v){ ll node=it.ss; res=max(res,mx+end[node]); mx=max(mx,start[node]); } res++; res=min(res,ans); cout<<res<<endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll t; t=1; // cin>>t; while(t--){ solve(); } return 0; }
cpp
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> #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}; int dp[N][3]; int freq[3]; int mul(int x, int y) { return ((x % mod) * (y % mod)) % mod; } int sum(int x, int y) { return ((x % mod) + (y % mod)) % mod; } void testCase(int cs) { int n; cin >> n; vector<int>v(n - 1); int mn = 0, sum = 0; for (int i = 0; i < n - 1; ++i) { cin >> v[i]; sum += v[i]; mn = min(mn, sum); } vector<int>ans(n); ans[0] = 1 - mn; // 1 - mn + mn ==> 1 set<int>st; st.insert(ans[0]); for (int i = 0; i < n - 1; ++i) { ans[i + 1] = ans[i] + v[i]; st.insert(ans[i + 1]); } if(sz(st) != n) { cout << -1 << endl; return; } for (int i = 0; i < n; ++i) { if(ans[i] < 1 || ans[i] > n) { cout << -1 << endl; return; } } for (int i = 0; i < n; ++i) { cout << ans[i] <<" "; } cout << endl; } signed main() { // files(); Source ll t = 1; int cs = 0; // cin >> t; while (t--) { testCase(++cs); } return 0; }
cpp
1310
E
E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1 OutputCopy6 InputCopy5 6 OutputCopy1 InputCopy10 1 OutputCopy138 InputCopy10 2 OutputCopy33
[ "dp" ]
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> using namespace std; const int N=3000+5; const int Mod=998244353; int n,k,ans,f[N]; vector<int> vc,t,nw; void solve1() { f[0]=1; for(int i=1;i<=n;i++) for(int j=i;j<=n;j++)f[j]=(f[j]+f[j-i])%Mod; for(int i=1;i<=n;i++)ans=(ans+f[i])%Mod; } void solve2() { f[0]=1; for(int i=1;(i*(i+1)>>1)<=n;i++) for(int j=i*(i+1)>>1;j<=n;j++) f[j]=(f[j]+f[j-(i*(i+1)>>1)])%Mod; for(int i=1;i<=n;i++)ans=(ans+f[i])%Mod; } bool check() { t=vc; for(int j=1;j<k;j++,nw.clear()) { int s=0; sort(t.begin(),t.end()),reverse(t.begin(),t.end()); for(int i=0;i<(int)t.size();i++)s+=t[i]*(i+1); if(s>n)return 0; if(j+3<k&&s>23)return 0; for(int i=0;i<(int)t.size();i++) for(int j=0;j<t[i];j++)nw.push_back(i+1); t=nw; } return 1; } bool dfs(int x) { if(!check())return 0; ans++; for(int i=x;;i++) { vc.push_back(i); int res=dfs(i); vc.pop_back(); if(!res)return 1; } return 1; } int main() { scanf("%d%d",&n,&k); if(k==1)solve1(); else if(k==2)solve2(); else dfs(1),ans--; printf("%d\n",ans); return 0; }
cpp
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
#include <bits/stdc++.h> using namespace std; long long st[800009]; long long lazy[800009]; long long a[200009]; long long b[200009]; void push(int id){ lazy[id*2]+=lazy[id]; lazy[id*2+1]+=lazy[id]; st[id*2]+=lazy[id]; st[id*2+1]+=lazy[id]; lazy[id]=0; } void update(int id,int l,int r,int u,int v,long long val){ if (l>v||r<u||u>v)return; if (u<=l&&r<=v){ st[id]+=val; lazy[id]+=val; return; } int mid=(l+r)/2; push(id); update(id*2,l,mid,u,v,val); update(id*2+1,mid+1,r,u,v,val); st[id]=min(st[id*2],st[id*2+1]); } signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); int n; cin>>n; for (int i=1;i<=n;i++)cin>>a[i]; for (int i=1;i<=n;i++){ cin>>b[i]; update(1,1,n,1,a[i]-1,b[i]); } long long ans=1e18; for (int i=n;i>=2;i--){ update(1,1,n,1,a[i]-1,-b[i]); update(1,1,n,a[i]+1,n,b[i]); ans=min(ans,st[1]); } cout<<ans; }
cpp
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
// LUOGU_RID: 102530371 #include<bits/stdc++.h> using namespace std; #define ll long long #define N 101 #define bas (133) #define yu (998244353) ll n; inline void ask(ll x,ll y){ cout<<"? "<<x<<' '<<y<<'\n'; cout.flush(); return ; } string s1[N*N/2],s2[N*N/2]; char ans[N]; ll hs1[N*N/2],hs2[N*N/2]; bool vis[N*N/2]; ll p[N],len[N*N/2],cn=0; inline bool cmp(ll x,ll y){return len[x]<len[y];} inline void solve(ll x){ if(x==1){ ask(1,1); cin>>s1[0];ans[1]=s1[0][0]; return ; } ask(1,x); ll cnt[N]; for(int i=1;i<=x*(x+1)/2;i++){ cin>>s1[i];memset(cnt,0,sizeof(cnt)); for(int j=0;j<s1[i].size();j++)cnt[s1[i][j]-'a']++; for(int j=0;j<26;j++)hs1[i]=(hs1[i]*bas+cnt[j])%yu; }ask(1,x-1); for(int i=1;i<=(x-1)*x/2;i++){ cin>>s2[i];memset(cnt,0,sizeof(cnt)); for(int j=0;j<s2[i].size();j++)cnt[s2[i][j]-'a']++; for(int j=0;j<26;j++)hs2[i]=(hs2[i]*bas+cnt[j])%yu; } for(int i=1;i<=(x-1)*x/2;i++){ for(int j=1;j<=x*(x+1)/2;j++){ if(vis[j])continue; if(hs2[i]==hs1[j]){ vis[j]=1;break; } } }for(int i=1;i<=x*(x+1)/2;i++){ if(vis[i])continue;p[++cn]=i;len[i]=s1[i].length(); }sort(p+1,p+cn+1,cmp); for(int j=1;j<=cn;j++){ memset(cnt,0,sizeof(cnt)); ll o=p[j];for(int g=0;g<s1[o].length();g++)cnt[s1[p[j]][g]-'a']++; if(j>1)for(int g=0;g<s1[p[j-1]].length();g++)cnt[s1[p[j-1]][g]-'a']--; for(int g=0;g<26;g++)if(cnt[g])ans[cn-j+1]=g+'a'; } return ; } ll cnt[N*N][26]; bool vv[N*N]; ll tmp[26]; inline void del(){ for(int i=1;i<=(n+1)*n/2;i++){ bool kz=1;if(vv[i])continue; for(int j=0;j<26;j++)if(cnt[i][j]!=tmp[j])kz=0; if(kz){ vv[i]=1;break; } } return ; } int main() { // freopen("test1.in","r",stdin); //freopen(".in","r",stdin); //freopen("test1.out","w",stdout); ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n;ll o=(n+1)/2,p=n-o;solve(o); ask(1,n); for(int i=1;i<=n*(n+1)/2;i++){ string s;cin>>s; for(int j=0;j<s.length();j++)cnt[i][s[j]-'a']++; } for(int i=1;i<=n;i++){ if(i>o){ ll p=n-i,an[26];memset(an,0,sizeof(an)); for(int j=1;j<=n*(n+1)/2;j++){ if(vv[j])continue; ll tot=0; for(int k=0;k<26;k++)tot+=cnt[j][k]; if(tot==p+1)for(int k=0;k<26;k++)an[k]+=cnt[j][k]; if(tot==p)for(int k=0;k<26;k++)an[k]-=cnt[j][k]; }for(int j=i-1;j>=i-p;j--)an[ans[j]-'a']--; for(int j=0;j<26;j++)if(an[j])ans[i]=j+'a'; } memset(tmp,0,sizeof(tmp)); for(int j=i;j>=1;j--){ tmp[ans[j]-'a']++; del(); } } cout<<"! ";for(int i=1;i<=n;i++)cout<<ans[i]; 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; int main() { float n,ans=0; cin>>n; while(n>0) { ans+= 1/n; n--; } cout<<ans<<endl; }
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; #define PI 3.14159265358979323846 #define ll long long int vector<int> adj[1005],good(1005,1); int query(int u,int v){ cout<<"? "<<u<<' '<<v<<'\n'; int ret; cin>>ret; assert(ret!=-1); return ret; } int bfs(int st,int n){ deque<int> q; vector<int> dis(n+1,-1); q.push_back(st); dis[st]=0; int last; while(!q.empty()){ int v=q.front(); q.pop_front(); if(good[v]) last=v; for(auto u : adj[v]){ if(dis[u]==-1){ if(!good[u]){ dis[u]=dis[v]; q.push_front(u); } else{ dis[u]=dis[v]+1; q.push_back(u); } } } } assert(dis[last]>0); return last; } void del_path(int a,int b,int n){ queue<int> q; vector<int> dis(n+1,-1),par(n+1); q.push(a); dis[a]=0; while(!q.empty()){ int v=q.front(); q.pop(); for(auto u : adj[v]){ if(dis[u]==-1){ dis[u]=dis[v]+1; q.push(u); par[u]=v; } } } int curr=b; while(curr!=a){ good[curr]=0; curr=par[curr]; } } int main(){ // ios_base::sync_with_stdio(false); // cin.tie(0); // cout.tie(0); int test = 1; // cin>>test; while(test--){ int n; cin>>n; int cnt=n; for(int i=1;i<n;i++){ int a,b; cin>>a>>b; adj[a].push_back(b); adj[b].push_back(a); } while(cnt>=2){ int root; for(int i=1;i<=n;i++){ if(good[i]){ root=i; } } int first=bfs(root,n); int second=bfs(first,n); int lca=query(first,second); if(lca==first || lca==second){ cout<<"! "<<lca<<'\n'; return 0; } del_path(lca,first,n); del_path(lca,second,n); cnt=0; for(int i=1;i<=n;i++){ cnt+=good[i]; } } int ans; for(int i=1;i<=n;i++){ if(good[i]){ ans=i; } } cout<<"! "<<ans; cout<<'\n'; } 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" ]
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Solution // Webbly, 27.01.2023 // // llll$lL |$$T ,,,ggg,,,||||||||||||||||||||||||||||llll // $lll$lL ,gg@@@@@@@@@@@@@@@@@@@@@@,|||||||||||||||||||||llll // $@&$ll|$lg,,, $*****Ywggg@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,||||||||||||||||lllll // *M$lll|$l$$$$l$l$$$$$$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|||||||||||||||llll // "*%Wll|$l$glllll||j@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@||||||||||||lllll // llll$lL ``']@@@@@@@@@@@@@@@@@@@@@@$@@@@@@@@@@$@@@@@@@@@@@@@||||||||||lllll // llll$lL @@@@@@@@@@@@@@@@$@@@$@@@@@@@@@@@@@@$@@@@@@@@@@@@@@g|||||||||llll // llll$lL ,@@@@@@@@@@@@@@@@@@@@K$@@@@@@@@@@@@@@$@@@@@@@@@@@@@@@@g||||||lllll // llll$lL @@@$@@$@@@@@$@@@@@@@M|@@]@@@@@@@@@@@@$@@@@@@@@@@@@@@@@%@||||||llll // llll$lL @@@@@@@@@@@@@@@@@@@@Ml`@@'%@@@@@@@@@@@$@@|@@@@@@@@@@@@@@$@@g|||llll // llll$lL ,g@@@@@@$@@@@@@@@@@@@MT $[ $@@@@@@@@@@@@@ ]@@@@@@@@@@@%@@g|M@@||lll // lllll@@@@@@@@@@@@@@@@@@@@@@@@*^"`][ "@@@@@@@@@@@@@ $@@@@@@@@@@@@@@W|||||||l // ll|@@@@@@$@@@@$@@@@@@@@@@@@@` F ]@@@@@@@@@U@F $@@@@@@@@@@@@@@|||||lll // |@@@@@@@@@@@@@@@@@@@@@@@@@@ -~$ ]@@@@@@@K @` ]@@$@@@@@@@@@@@W||||lll // ,@@@@@@@@O@@@@@@@@@@@@@@@@@C ,gg@@@p ' ]@@@@@@ @-= @@]@@@@@@@@@@@M||||lll // g@@@@@@@@C $@@@@@@@@@@@@@@@@@@P,^"@@@$, "@@@@ .g@@NB@ -]@@@@@@@@@@@||||llll // @@@@@@@@@L ]@@@@@@@@@@@@@@@$P'$@g@@@@L ]@@ @$-]@@-$ ]@@@@@@@@@@K|||||lll // @@@@@@@N|L ]@@@@@@@@@@@@@@$% $@@@@%@P K '-@@@@@@j $@@@@@@@$@@||||||lll // $@@@@@|$lL ]@@]@@@@@@@@@@*C *B@@wC "@$@'@"" $@@@@@@@@@@|||||||ll // @@@@M|lllL '% @@@@@@@@@@ -`" ]@@@@@@@$@@@W|||||lll // $@@|lllllL ,L$@@@@@@@@@ .+'| -"$@@@@@@@@@@@||||||ll // @Mlll&l$l@@&Wggg$w]@@@@@@@@@P ` ''' j@@@@P$@@@@@@w|||||ll // l$$llll$$$$$$l$$$ll@@@@@@@@@P ]@@@@P]@@@@@@@|||||ll // *M&Llll$l@@@@wwllll$@@@@@@@@P -~.=~=~.- @@@@@F"@@@$@@@|||||ll // 'llll$lL @@@@@@@@L g@@@@@L|%@@@$@@@||||ll // llllllL ]@@@@@@@@W ,@@@@@@@@||]@@@$@@@||||ll // llllllL $@@@@@@@ ,WM, ,<||@@@@@@@@@|||]@@@@@@||||ll // llllllL $@@@@@@||L|||lTw, -^|| ||@@@@@@@@L|||"@@@@@@@|||ll // ll|lllL $@@@@@@|l||||||||llMww^| l@@@@@@@@|||||]@@@@@@|||ll // llLlllL ,,g@@@@@@@@||||l|||||||||||%,| |@@@@@@@ ||||||$@@@@@W||ll // llllllL ,gg@@@@@@@@@@@@@@|||||||||l|l]|||%@w, $@@@]@` |||||"@@@@@@|||l // llll$lggg@@@@@@@@@@@@@@@@@@%L|||||||||||$A|||@@@@@@@@@@g@Wggggggg,|]@@@@@@||l // llL|@@@@@@@@@@@@@@@@@@@@@@@K *l|||l/|M$@@@@|W]@@@@@@@@ ` ``'''}@L|]@@@@@@|l // lly@@@@@@@@@@@@@@@@@@@@@@@@@P, '*||ll$@@@@@@/ $@@@@@@@@@@@gggggggl$@@$@@@@@@@ // l#@@@@@@@@@@@@@@@@@@@@@@@@@@@p\ "$@@@@@F]@p]@@@@@@@@@@@@@@@2|%&%$$$@@@@@@@ // ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,$@]@$$$ ]$$@@@@@@@@@@@@@@@@@@@@@@@$@@@@@@ // // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include<bits/stdc++.h> #include<unistd.h> #pragma GCC optimize("O3","Ofast","unroll-loops") //#pragma GCC optimize("O3", "fast-math") #define ll long long #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() using namespace std; const ll mod = (ll)1e9 + 7, mod3 = 998244353, inf = (ll)1e15, P = 997; ll binpow (ll a, ll b){ if (b == 0) return 1; if (b & 1) return ((binpow(a, b - 1)) * a); else return (binpow(a, b / 2) * binpow(a, b / 2)); } ll gcd(ll a, ll b){ return (b ? gcd(b, a % b) : a); } ll nums(ll g){ ll cur = 0; while(g){ cur++, g /= 10; } return cur; } vector <ll> fact(ll n){ ll i = 2; vector <ll> ans; ll save = n; while(i * i <= save){ while(n % i == 0){ ans.pb(i); n /= i; } i++; } if (n > 1) ans.pb(n); return ans; } ll get1(ll q, ll g){ ll cur = 1; for (ll i = q; i > g; i--){ cur *= i; } return cur; } struct T{ ll mn, mx; }; ll n, k, m, a, b, hp[200005]; void query(){ cin >> n >> a >> b >> k; for (ll i = 1; i <= n; i++){ cin >> hp[i]; hp[i] %= (a + b); if (!hp[i]) hp[i] += a + b; if (hp[i] % a){ hp[i] = hp[i] / a; } else hp[i] = hp[i] / a - 1; } ll ans = 0; sort (hp + 1, hp + n + 1); for (ll i = 1; i <= n; i++){ if (hp[i] > k) break; ans++; k -= hp[i]; } cout << ans; } int main(){ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); //freopen("lca_rmq.in", "r", stdin); //freopen("lca_rmq.out", "w", stdout); ll TT = 1; //cin >> TT; while(TT--){ //cout << "Case " << cur << ":\n"; query(); //cur++; } return 0; } /** 1 1 2 3 5 8 13 */
cpp
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
[ "implementation", "strings" ]
#include<bits/stdc++.h> using namespace std; int main() { long long int t; cin>>t; while(t--){ long long int n,i,a=0; string str,str1,str2; cin>>str>>str1>>str2; n=str.size(); for(i=0;i<n;i++){ if(str[i]==str2[i] || str1[i]==str2[i]){ a++; } } if(a==n){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } return 0; }
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
#include<bits/stdc++.h> using namespace std; #define ll long long const int N = 1e6 + 7; ll lcm(ll a, ll b) { return (a * b) / __gcd(a, b); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll n; cin >> n; ll a = 1, b = n; for(ll i = 2; i * i <= n; i++) { if(n % i == 0) { ll d = n / i; if(d != i && d <= b && lcm(i, d) == n) { a = i; b = d; } } } cout << a << " " << b << "\n"; }
cpp
1286
C1
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard 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 (n+1)2(n+1)2.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 (n+1)2(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", "interactive", "math" ]
// LUOGU_RID: 102517476 #include<bits/stdc++.h> using namespace std; #define ll long long #define N 101 #define bas (133) #define yu (998244353) ll n; inline void ask(ll x,ll y){ cout<<"? "<<x<<' '<<y<<'\n'; cout.flush(); return ; } string s1[N*N/2],s2[N*N/2]; char ans[N]; ll hs1[N*N/2],hs2[N*N/2]; bool vis[N*N/2]; ll p[N],len[N*N/2],cn=0; inline bool cmp(ll x,ll y){return len[x]<len[y];} int main() { // freopen("test1.in","r",stdin); //freopen(".in","r",stdin); //freopen("test1.out","w",stdout); ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin>>n;if(n==1){ ask(1,1); cin>>s1[0]; cout<<"! "<<s1[0]<<'\n'; return 0; } ask(1,n); ll cnt[N]; for(int i=1;i<=n*(n+1)/2;i++){ cin>>s1[i];memset(cnt,0,sizeof(cnt)); for(int j=0;j<s1[i].size();j++)cnt[s1[i][j]-'a']++; for(int j=0;j<26;j++)hs1[i]=(hs1[i]*bas+cnt[j])%yu; }ask(1,n-1); for(int i=1;i<=(n-1)*n/2;i++){ cin>>s2[i];memset(cnt,0,sizeof(cnt)); for(int j=0;j<s2[i].size();j++)cnt[s2[i][j]-'a']++; for(int j=0;j<26;j++)hs2[i]=(hs2[i]*bas+cnt[j])%yu; } for(int i=1;i<=(n-1)*n/2;i++){ for(int j=1;j<=n*(n+1)/2;j++){ if(vis[j])continue; if(hs2[i]==hs1[j]){ vis[j]=1;break; } } }for(int i=1;i<=n*(n+1)/2;i++){ if(vis[i])continue;p[++cn]=i;len[i]=s1[i].length(); }sort(p+1,p+cn+1,cmp); for(int j=1;j<=cn;j++){ memset(cnt,0,sizeof(cnt)); ll o=p[j];for(int g=0;g<s1[o].length();g++)cnt[s1[p[j]][g]-'a']++; if(j>1)for(int g=0;g<s1[p[j-1]].length();g++)cnt[s1[p[j-1]][g]-'a']--; for(int g=0;g<26;g++)if(cnt[g])ans[cn-j+1]=g+'a'; }cout<<"! ";for(int i=1;i<=n;i++)cout<<ans[i]; 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<cstdio> #include<algorithm> using namespace std; long long H; int N; int d[2<<17]; long long M[2<<17]; main() { scanf("%lld%d",&H,&N); long long cd=0; for(int i=0;i<N;i++) { scanf("%d",&d[i]); cd-=d[i]; M[i+1]=max(M[i],cd); } long long ans=0; if(H>M[N]) { if(cd<=0) { puts("-1"); return 0; } long long T=H-M[N]; ans=(T+cd-1)/cd; H-=ans*cd; ans*=N; } ans+=lower_bound(M,M+N+1,H)-M; printf("%lld\n",ans); }
cpp
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
#include <bits/stdc++.h> using namespace std; char buf[1<<23],*p1=buf,*p2=buf; #define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) template <typename T> inline void read(T &f) { f=0;T fu=1;char c=getchar(); while(c<'0'||c>'9') {if(c=='-'){fu=-1;}c=getchar();} while(c>='0'&&c<='9') {f=(f<<3)+(f<<1)+(c&15);c=getchar();} f*=fu; } template <typename T> void print(T x,char c=0) { if(x<0) putchar('-'),x=-x; if(x<10) putchar(x+48); else print(x/10),putchar(x%10+48); if(c) putchar(c); } inline void reads(string &f) { string str="";char ch=getchar(); while(ch<'!'||ch>'~') ch=getchar(); while((ch>='!')&&(ch<= '~')) str+=ch,ch=getchar(); f=str; } void prints(string s) { for(int i=0;s[i];++i) putchar(s[i]); } typedef long long ll; const int multicase=0,debug=0,maxn=1e6+50; struct node { double x; int l,r; }; stack<node> sta; int n,a[maxn]; double ans[maxn]; void solve() { read(n); for(int i=1;i<=n;++i) read(a[i]); sta.push({1.0*a[1],1,1}); for(int i=2;i<=n;++i) { node now={1.0*a[i],i,i}; while(!sta.empty()) { double sum=now.x*(now.r-now.l+1)+sta.top().x*(sta.top().r-sta.top().l+1); int len=now.r-now.l+1+sta.top().r-sta.top().l+1; double nx=sum/len; int nl=sta.top().l,nr=now.r; if(nx<=sta.top().x) { sta.pop(); now.x=nx,now.l=nl,now.r=nr; } else { break; } } sta.push(now); } while(!sta.empty()) { node t=sta.top(); sta.pop(); for(int i=t.l;i<=t.r;++i) ans[i]=t.x; } for(int i=1;i<=n;++i) printf("%.9lf\n",ans[i]); } int main() { #ifdef AC freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif clock_t program_start_clock=clock(); int _=1; if(multicase) read(_); while(_--) solve(); fprintf(stderr,"\nTotal Time: %lf ms",double(clock()-program_start_clock)/1000); return 0; }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
#include <iostream> #include <vector> #include <map> #include <unordered_map> #include <cmath> #include <iomanip> #include <set> #include <unordered_set> #include <algorithm> #include <cctype> #include <string> #include <queue> #include <cstring> #include <bitset> using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; typedef vector<long long> vll; typedef map<string, int> msi; typedef map<string, string> mss; typedef map<int, int> mii; #define endl "\n" #define ENDL "\n" #define endla(n) " \n"[i == n - 1] #define ENDLA(n) " \n"[i == n - 1] #define Ber0Silk int main (void) #define cin(v) for(auto& i : v) cin >> i; #define cout(v) for(auto& i : v) cout << i << " "; cout << ENDL; #define pb push_back #define FAST ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #define rv(x) return void(cout << x << endl) #define all(v) v.begin(),v.end() #define next continue; #define NEXT continue; #define F first #define S second #define on(n) [i == n - 1] const int INF = int(1e9) + 7; const long long N = 1e6 + 10; const double PI = acos(-1); const int MOD = 1e9 + 7; template<typename T> bool CompareVe(vector<T> v1, vector<T> v2) { bool f = v1.size() == v2.size(); if (!f) return false; for (int i = 0; i < v1.size(); i++) if (v1[i] != v2[i]) return false; return true; } template<typename T> bool sorted(vector<T> v) { for (int i = 0; i < v.size() - 1; i++) if (v[i] > v[i + 1]) return false; return true; } /* prime factorization */ // const int lim = 1000001; // set<ll> v; // void calc(){ // static bool arr[lim]; // for(int i = 2;i*i < lim;i++){ // if(!arr[i]){ // for(int j = i*i;j < lim;j+=i){ // arr[j] = true; // } // } // } // for(ll i = 2;i < lim;i++){ // if(!arr[i]){ // v.insert(((ll)i*i)); // } // } // } // Solution here void solve() { string s; cin >> s; vector<ll> v; //ll n = s.length(); ll c = 0; for(int i = 0;i < s.length();i++){ if(s[i] == '1'){ v.push_back(i); } } if(v.size() != 0) for(int i = 0;i < v.size() - 1;i++){ if((v[i + 1] - v[i]) > 1) c += v[i + 1] - v[i] - 1; } rv(c); } Ber0Silk{ FAST //calc(); ll t = 1; cin >> t; while (t--) { solve(); } return 0; } /* CODING. . . */
cpp
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
#include <bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(NULL); #define test fast int t;cin>>t;while(t--) #define test2 int t;scanf("%d",&t);while(t--) #define pb push_back #define fs first #define sc second #define mp make_pair #define loop(i,n) for(int i=0;i<n;i++) #define lt(i) ((i<<1)+1) #define rt(i) ((i<<1)+2) #define par(i) ((i-1)>>1) #define f(k,n) k*(2*n-k-1) #define all(v) v.begin(), v.end() #define sz(v) v.size() #define vc vector using ll = long long int; using ull = unsigned ll; using vi = vc<int>; using vb = vc<bool>; using vl = vc<ll>; using pii = pair<int,int>; ll mod = 1e9+7; ll inf = 1e18; const ll constant = 1e6+1; // input/output template <typename T> ostream& operator<<(ostream&os,const vector<T>&v){ loop(i,v.size()){ os<<v[i]<<" "; } os<<"\n"; return os; } template <typename T> istream& operator>>(istream&is,vector<T>&v){ loop(i,v.size())is>>v[i]; return is; } template <typename T, typename S> ostream& operator<<(ostream&os,const pair<T,S>&p){ os<<"("<<p.fs<<", "<<p.sc<<")"; return os; } template <typename T> ostream& operator<<(ostream&os,const set<T>&s){ os<<"{"; for(auto it:s){ os<<it<<","; } os<<"}"; return os; } template <typename T, typename S> ostream& operator<<(ostream&os, const map<T,S>&h){ os<<"{"; for(auto i:h){ os<<i.fs<<":"<<i.sc; if(i!=*h.end())os<<","; } os<<"}"; return os; } template <typename T> ostream& operator<<(ostream&os,const deque<T>&d){ os<<"{"; for(auto i:d){ os<<i<<","; } os<<'}'; return os; } void print(){cout<<"\n";} template <typename T, typename... types>void print(T var,types... vars){ cout<<var<<" "; print(vars...); } // debug vector<string> vcsplit(string s){ s += ","; string temp = ""; vc<string> v; loop(i,sz(s)){ if(s[i]==','){ v.pb(temp); temp=""; } else temp+=s[i]; } return v; } void debug_out( vc<string> __attribute__ ((unused)) args, int __attribute__ ((unused)) idx, int __attribute__ ((unused)) LINE) { cerr<<endl; } template<typename H,typename... T> void debug_out(vc<string>args,int idx,int LINE,H h,T... t){ cerr<<((idx)?", ":"Line("+to_string(LINE)+") "); stringstream ss; ss<<h; cerr<<args[idx]<<" = "<<ss.str(); debug_out(args,idx+1,LINE,t...); } #ifdef XOX #define debug(...) debug_out(vcsplit(#__VA_ARGS__),0,__LINE__,__VA_ARGS__); #else #define debug(...) 42; #endif // template classes //code pii check(vc<vi>&a,int x,int m){ map<int,int> s; vi v; loop(i,sz(a)){ int temp = 0; loop(j,m){ if(a[i][j]>=x)temp|=(1<<j); } if(!s.count(temp))s[temp]=i; } for(auto i:s) v.pb(i.fs); int v1 = (1<<m)-1; loop(i,sz(v)){ for(int j=i;j<sz(v);j++){ if((v[i]|v[j]) == v1){ return mp(s[v[i]],s[v[j]]); } } } return mp(-1,-1); } void solve(){ int n, m; cin>>n>>m; vc<vi> a(n,vi(m)); cin>>a; int l = 0, h = 1e9, mid; pii ans = {-1,-1}; while(l<=h){ mid = (l+h)>>1; pii temp = check(a,mid,m); if(temp.fs!=-1){ l=mid+1; ans = temp; } else h = mid-1; } cout<<(ans.fs+1)<<" "<<(ans.sc+1)<<"\n"; } int main(){ fast solve(); }
cpp
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
//shinzo_wo_sasageyo!! #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; //typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key #define int long long #define endl "\n" #define mod 1000000007 #define setbits(x) __builtin_popcountll(x) typedef long long ll; ll expo(ll a, ll b, ll m) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % m; a = (a * a) % m; b = b >> 1;} return res;} ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} 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;} //use INT_MAX as LLONG_MAX /*------------------------------------------------------------------------- //FOR DP OR ELSE //vector<vector<int>>(n+1,vector<int>(m+1,-1)) dp;memset(dp,-1,sizeof(dp)); ------------------------------------------------------------------------- //FOR FLAG->(YES/NO) if(){ cout<<"yes"<<endl; } else{ cout<<"no"<<endl; } -------------------------------------------------------------------------- */ /* void checkprime(bool isprime[],int n){ isprime[0]=false; isprime[1]=false; for(int i=2;i*i<=n;i++){//logic of iterating till sqaure root of n and not n if(isprime[i]==true){//if a number is prime it's multiples will not be prime for(int j=i*i;j<=n;j=j+i){//observation step isprime[j]=false; } } } } bool isprime[100001];*/ signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); /* for(int i=0;i<=100001;i++){ isprime[i]=true; } checkprime(isprime,100001); */ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; vector<int> pos; for(int i=0;i<n;i++){ cin>>a[i]; } for (int i = 0; i < n; ++i) { if(a[i]>=0){ // pos.push_back(a[i]); if(((i-1)>=0 and a[i-1]==-1) or ((i+1)<n and a[i+1]==-1)){ pos.push_back(a[i]); } } } // int sum=0; // for (int i = 0; i < pos.size(); ++i) // { // sum+=pos[i]; // } if(pos.size()==0){ cout<<0<<" "<<0<<endl; continue; } sort(pos.begin(),pos.end()); int avg=(pos[0]+pos[pos.size()-1])/2; //cout<<pos.size()<<endl; for (int i = 0; i < n; ++i) { if(a[i]==-1){ a[i]=avg; } } int mx=0; for (int i = 0; i < n-1; ++i) { mx=max(mx,abs(a[i]-a[i+1])); } cout<<mx<<" "<<avg<<endl; } 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" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int #define ss string #define loop1(i,n) for(ll i=0;i<n;++i) #define loop2(i,n) for(ll i=n-1;i>=0;--i) #define loop3(i,a,b) for(ll i=a;i<b;i++) #define loop4(i,a,b) for(ll i=a;i>=b;i--) #define NO cout<<"NO"<<endl; #define YES cout<<"YES"<<endl; #define No cout<<"No"<<endl; #define Yes cout<<"Yes"<<endl; #define out(x) cout<<x<<endl; vector<vector<ll>>dp(2001,vector<ll>(2001,0)); int main() { ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0); ll n,m;cin>>n>>m; for(ll i=0;i<=2000;i++) { dp[i][0]=1;dp[i][i]=1; } for(ll i=1;i<=2000;i++) { for(ll j=1;j<i;j++) { dp[i][j]=(dp[i-1][j-1]%1000000007+dp[i-1][j]%1000000007)%1000000007; } } cout<<dp[2*m+n-1][n-1]; }
cpp
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
[ "data structures", "dsu" ]
#include<bits/stdc++.h> #define ll long long #define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) #define all(a) (a).begin() , (a).end() #define pb push_back #define mp make_pair #define pii pair<int,int> #define pll pair<ll,ll> #define piii pair<pii,int> #define plll pair<pll,ll> #define R return #define B break #define C continue #define SET(n , i) memset(n , i , sizeof(n)) #define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define rep(i , n) for(int i = 0 ; i < n ; i++) #define repn(i , j , n) for(int i = j ; i < n ; i++) #define repr(i,n,j) for(int i=n;i>=j;i--) #define positive(x) ((x%mod+mod)%mod) #define YES(f)cout<<((f)?"YES":"NO")<<endl #define F first #define S second #define endl '\n' #define vi vector<int> //#define int ll using namespace std; void readFromFile(string input = "input.txt",string output="output.txt") { #ifndef ONLINE_JUDGE freopen(input.c_str(),"r",stdin); freopen(output.c_str(),"w",stdout); #endif } mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll rnd(ll x, ll y) { return uniform_int_distribution<ll>(x, y)(rng); } template <typename T> void Max(T& x,T y){x=max(x,y);} template <typename T> void Min(T& x,T y){x=min(x,y);} const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const long double EPS = 1e-3; const long double pi = acos(-1.0); const int mod = 1e9+9; const int N =1e5+2; ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;} ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;} int n,m,sq=320,a[N]; pii dp[N]; void calc(int b) { int st = max(1,b*sq),en = min(n,st+sq); repr(i,en,st) { if(a[i]+i > en) dp[i] = {1,i}; else dp[i] = {dp[a[i]+i].F+1,dp[a[i]+i].S}; } } void solve() { cin >> n >> m; rep(i,n) cin >> a[i+1]; rep(i,sq)calc(i); while(m--) { int ty;cin>>ty; if(ty == 1) { int x;cin>>x; int ans=0,fin=x; while(x <= n) { ans += dp[x].F; fin=dp[x].S; x = dp[x].S+a[dp[x].S]; } cout << fin << ' ' << ans << endl; }else { int x,y;cin>>x>>y; a[x]=y; calc(x/sq); } } } int32_t main() { readFromFile(); SD; int t = 1; // cin >> t; // scanf("%d",&t); rep(i,t) { solve(); } }
cpp
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
#include "bits/stdc++.h" using namespace std; #define ll long long int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; vector<int> a; int cc = 1; for (char c : s) { if (c == '<') cc++; else { a.push_back(cc); cc = 1; } } a.push_back(cc); { int sf = n; for (int x : a) { sf -= (x - 1); for (int i = 0; i < x; i++) { cout << (sf++) << " "; } sf -= (x + 1); } cout << "\n"; } { int tot = n - a.size(); int st = n - tot + 1; int fv = n - tot; for (int x : a) { cout << (fv--) << " "; for (int i = 1; i < x; i++) { cout << (st++) << " "; } } cout << "\n"; } } }
cpp
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2 3 3 2 1 6 3 1 4 1 5 9 OutputCopy3 5 NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
[ "greedy", "implementation" ]
#include<iostream> #include<algorithm> #include<cmath> #include<math.h> #include<numeric> #include<set> #include<list> #include<sstream> #include<functional> #include<unordered_set> #include<queue> #include<vector> #include<string> #include<map> #include<iomanip> #include<ios> #include<iterator> #include<unordered_map> #define print(v) copy(v.begin(), v.end(), ostream_iterator<ll>(cout, " ")); #define neymar ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define ll long long #define el endl #define ell cout<<endl #define forn(i, n) for (int i = 0; i < n; i++) #define for1(i, n) for (int i = 1; i <= n; i++) #define forb(i, n) for (int i = n-1; i >= 0; i--) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() using namespace std; ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a % b); } int main() { neymar ll tc; cin >> tc; while (tc--) { ll n, x; cin >> n; set<ll>s; forn(i, n) { cin >> x; s.insert(x); } cout << s.size() << el; } 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" ]
// github.com/jamesgrimard/codeforces #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(); int n; cin >> n; int sum = 0; for (int i=2;i<n;i++) { int N = n; while(N>0) { sum += (N%i); N /= i; } } int k = gcd(sum,n-2); cout << sum/k << "/" << (n-2)/k; 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" ]
// RADHASOAMI , WITH THE GRACE OF HUZUR I PROMISE TO FIGHT TILL THE LAST SECOND OF EVERY CONTEST AND CODE TO MY FULL POTENTIAL ...... #include <iostream> #include <vector> #include <unordered_map> #include <cmath> #include <cstring> #include <algorithm> #include <set> #include <map> #include <queue> #define ll long long int #define mod 1000000007 using namespace std; // ==================== FUNCTIONS FOR INPUT AND OUTPUT OF VECTORS ======================================================= void input(vector < ll > &arr) { for(int i = 0;i < arr.size();i++) cin >> arr[i]; } void output(vector < ll > &arr) { for(int i = 0;i < arr.size();i++) cout << arr[i] << " "; cout << "\n"; } // ============================== FOR MATHEMATICAL FUNCTIONS ============================================================= ll gcd(ll a,ll b) { if(b==0) return a; return gcd(b,a%b); } ll power(ll a,ll b) { if(b==0) return 1; if(b==1) return a; ll smallans=power(a,b/2); ll myans=(smallans*smallans)%mod; if((b&1)) myans=(myans*a)%mod; return myans; } ll multiply(ll a,ll b) { ll ans=((a%mod)*(b%mod))%mod; return ans; } ll divide(ll a,ll b) { return multiply(a,power(b,mod-2)); } // ============================ SEGMENT TREE FOR DEFAULT MINIMUM QUERY ================================================== void manageLazy(vector <ll> &tree,vector <ll> &lazy,ll idx) { tree[2*idx + 1] += lazy[idx]; lazy[2*idx + 1] += lazy[idx]; tree[2*idx + 2] += lazy[idx]; lazy[2*idx + 2] += lazy[idx]; lazy[idx] = 0; } void build(vector <ll> &tree,vector <ll> &arr,ll left,ll right,ll idx) { if(left == right) { tree[idx] = arr[left]; return; } ll mid = (left + right) / 2; build(tree , arr , left , mid , 2*idx + 1); build(tree , arr , mid + 1 , right , 2*idx + 2); tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]); } void update(vector <ll> &tree,vector <ll> &lazy,ll tl,ll tr,ll l,ll r,ll idx,ll val) { if(l > r) return; if(l == tl && tr == r) { tree[idx] += val; lazy[idx] += val; return; } manageLazy(tree,lazy,idx); ll mid = (tl + tr) / 2; update(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1,val); update(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2,val); tree[idx] = min(tree[2*idx + 1],tree[2*idx + 2]); } ll query(vector <ll> &tree,vector<ll> & lazy,ll tl,ll tr,ll l,ll r,ll idx) { if(l > r) return 1e18; if(l <= tl && tr <= r) return tree[idx]; manageLazy(tree,lazy,idx); ll mid = (tl + tr) / 2; ll a = query(tree,lazy,tl,mid,l,min(r,mid),2*idx + 1); ll b = query(tree,lazy,mid + 1,tr,max(l,mid + 1),r,2*idx + 2); return min(a,b); } // ================================== SPARSE TABLE FOR DEFAULT MINIMUM QUERY ================================================== void precompute_min(vector < vector < ll > > &sparsetable , vector < ll > &a) { int n = sparsetable.size(); int p = sparsetable[0].size(); for(int i = 0;i < n;i++) sparsetable[i][0] = a[i]; for(int j = 1;j < p;j++) { for(int i = 0;i + (1 << j) <= n;i++) sparsetable[i][j] = min(sparsetable[i][j - 1] , sparsetable[i + (1 << (j - 1))][j - 1]); } } ll minquery(vector < vector < ll > > &sparsetable , vector < ll > &log , ll l , ll r) { ll range = r - l + 1; if(range == 0) return sparsetable[l][0]; ll j = log[range]; return min(sparsetable[l][j] , sparsetable[r - (1 << j) + 1][j]); } //========================== BINARY INDEX TREE ========================================================================= void update(vector<ll> &tree,ll index,ll val) { index++; while(index < tree.size()) { tree[index]=(tree[index] + val) %mod; index+=index&(-index); } } ll calculate(vector<ll> &tree,ll index) { ll sum=0; index++; while(index > 0) { sum=(sum + tree[index])%mod; index-=index&(-index); } return sum; } //=========================== FOR DISJOINT SET UNION ==================================================================== ll findpar(ll p,vector<ll> &parent) { if(parent[p]==p) return p; parent[p]=findpar(parent[p],parent); return parent[p]; } void merge(ll a, ll b,vector<ll> &parent,vector<ll> &size_) { a = findpar(a,parent); b = findpar(b,parent); if (a != b) { if (size_[a] < size_[b]) swap(a, b); parent[b] = a; size_[a] += size_[b]; } } // ====================================== FOR STORING AND COUNTING THE PRIMES USING SIEVE ============================ void sieve(vector<bool> &primes,vector<ll> &count) { for(int i=2;i<primes.size();i++) { if(primes[i]) { count.push_back(i); for(int j=i*i;j<primes.size();j+=i) primes[j]=false; } } } // ===================================================================================================================== void solve() { ll n, m, p; cin >> n >> m >> p; vector < ll > a(n, 0); input(a); vector < ll > b(m, 0); input(b); int lidx = 0, ridx = 0; for(int i = 0;i < n;i++) { if(a[i] % p) { lidx = i; break; } } for(int i = 0;i < m;i++) { if(b[i] % p) { ridx = i; break; } } cout << (lidx + ridx) << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input2.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t = 1; // cin >> t; while(t--) { solve(); } return 0; }
cpp
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; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; cin >> n; string s; cin >> s; int prefix = 0, toChange = 0, index = 0, answer = 0; for(int i = 0; i < n; i++) { prefix += (s[i] == '('); prefix -= (s[i] == ')'); if(prefix < 0) toChange = 1; if(prefix == 0) { if(toChange) answer += (i - index + 1); index = i + 1; toChange = 0; } } cout << (index == n ? answer : -1); }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include <iostream> using namespace std; typedef long long ll; ll cnt[5010] = {},pr[5010][5010],p[5010],mx = 5000; bool f[5010]; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int i,j,n; cin >> n; for(i=0;i<n;i++){ int k; cin >> k; cnt[k]++; f[k] = true; } for(i=2;i<=mx;i++){ if(p[i]) continue; for(j=i;j<=mx;j+=i) p[j] = i; } for(i=2;i<=mx;i++){ for(j=1;j<=mx;j++) pr[i][j] = pr[i - 1][j]; int x = i; while(x>1){ pr[i][p[x]]++; x /= p[x]; } } ll ans = 0; for(i=1;i<=mx;i++){ ll sum = 0; for(j=1;j<=mx;j++) sum += pr[i][j]; ans += sum*cnt[i]; } for(j=mx;j>=1;){ int num = 0; for(i=1;i<=mx;i++){ if(!f[i]) continue; if(pr[i][j]) num += cnt[i]; } if(2*num<=n){ for(i=1;i<=mx;i++){ if(pr[i][j]) f[i] = false; } j--; }else{ ans += (n - 2*num); for(i=1;i<=mx;i++){ if(pr[i][j]==0) f[i] = false; else pr[i][j]--; } } } cout << ans << endl; }
cpp
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
#include<bits/stdc++.h> #define ll long long #define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) #define all(a) (a).begin() , (a).end() #define pb push_back #define mp make_pair #define pii pair<int,int> #define pll pair<ll,ll> #define piii pair<pii,int> #define plll pair<pll,ll> #define R return #define B break #define C continue #define SET(n , i) memset(n , i , sizeof(n)) #define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define rep(i , n) for(int i = 0 ; i < n ; i++) #define repn(i , j , n) for(int i = j ; i < n ; i++) #define repr(i,n,j) for(int i=n;i>=j;i--) #define posi(x) ((x%mod+mod)%mod) #define YES(f)cout<<((f)?"YES":"NO")<<endl #define F first #define S second #define endl '\n' #define vi vector<int> //#define int ll using namespace std; void readFromFile(string input = "input.txt",string output="output.txt") { #ifndef ONLINE_JUDGE freopen(input.c_str(),"r",stdin); freopen(output.c_str(),"w",stdout); #endif } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); ll rnd(ll x, ll y) { return uniform_int_distribution<ll>(x, y)(rng); } template <typename T> void Max(T& x,T y){x=max(x,y);} template <typename T> void Min(T& x,T y){x=min(x,y);} const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const long double EPS = 1e-3; const long double pi = acos(-1.0); const int mod = 998244353; const int N =2e5+3; ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;} ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;} int n,m,p; pii a[N],b[N]; piii dr[N]; struct ST { ll tree[1<<21],lazy[1<<21]; void build(int st=1,int en=1e6,int idx=0) { lazy[idx]=0; if(st==en) { auto z = lower_bound(b,b+m,mp(st,-1))-b; if(z != m)tree[idx] = -b[z].S; else tree[idx] = -INFLL; }else { int mid=st+(en-st)/2, lf=2*idx+1,rt=2*idx+2; build(st,mid,lf); build(mid+1,en,rt); tree[idx] = max(tree[lf],tree[rt]); } } void laz(int st,int en,int idx) { if(lazy[idx]==0) return; tree[idx] += lazy[idx]; if(st != en) { int lf=2*idx+1,rt=2*idx+2; lazy[lf] += lazy[idx]; lazy[rt] += lazy[idx]; } lazy[idx]=0; } void update(int qs,int qe,int val,int st=1,int en=1e6,int idx=0) { laz(st,en,idx); if(st > qe || en < qs) R ; if(st >= qs && en <= qe) { lazy[idx] += val; laz(st,en,idx); return; } int mid=st+(en-st)/2, lf=2*idx+1,rt=2*idx+2; update(qs,qe,val,st,mid,lf); update(qs,qe,val,mid+1,en,rt); tree[idx] = max(tree[lf],tree[rt]); } ll query(int qs,int qe,int st=0,int en=n-1,int idx=0) { laz(st,en,idx); R tree[idx]; } }sg; void solve() { cin >> n >> m >> p; rep(i,n)cin >> a[i].F >> a[i].S; rep(i,m)cin >> b[i].F >> b[i].S; rep(i,p) cin >> dr[i].F.F >> dr[i].F.S >> dr[i].S; sort(a,a+n); sort(b,b+m); sort(dr,dr+p); repr(i,n-2,0) { Min(a[i].S,a[i+1].S); } repr(i,m-2,0) { Min(b[i].S,b[i+1].S); } sg.build(); ll ans=-a[0].S-b[0].S; int l=0; rep(i,p) { sg.update(dr[i].F.S+1,1e6,dr[i].S); while(l < n && a[l].F <= dr[i].F.F)l++; if(l == n)B; Max(ans,-a[l].S+sg.query(1,1e6)); } cout << ans << endl; } int32_t main() { readFromFile(); SD; int t = 1; // cin >> t; // scanf("%d",&t); rep(i,t) { solve(); } }
cpp
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
#include <bits/stdc++.h> using namespace std; #define dg(x) cout<<#x<<"="<<x<<endl using ll = long long; const int N = 1e5+5; int n,sa[N],sb[N],ea[N],eb[N]; pair<pair<int,int>,int> t[N<<1]; bool chk(){ for (int i=0; i<(n<<1); i+=2){ t[i]={{sa[i/2],0},i/2}; t[i+1]={{ea[i/2],1},i/2}; } sort(t,t+(n<<1)); multiset<int> s,e; for (int i=0; i<(n<<1); i++){ int I=t[i].second; if (t[i].first.second==0){ // s s.insert(sb[I]),e.insert(eb[I]); if ((*s.rbegin())>(*e.begin())){ return 0; } } else{ // e s.erase(s.find(sb[I])),e.erase(e.find(eb[I])); } } return 1; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n; for (int i=0; i<n; i++){ cin>>sa[i]>>ea[i]>>sb[i]>>eb[i]; } if (!chk()){ cout<<"NO"<<endl; return 0; } swap(sa,sb),swap(ea,eb); if (!chk()){ cout<<"NO"<<endl; return 0; } else{ cout<<"YES"<<endl; } return 0; }
cpp
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<bits/stdc++.h> using namespace std; #define ll long long int #define loop1(i,n) for(ll i=0;i<n;++i) #define loop2(i,n) for(ll i=n-1;i>=0;--i) #define NO cout<<"NO"<<endl; #define YES cout<<"YES"<<endl; #define out(x) cout<<x<<endl; int main() { ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0); ll t;cin>>t; while(t--) { ll n,m,k;cin>>n>>m>>k; ll arr[n]; loop1(i,n) { cin>>arr[i]; } k=min(k,m-1); ll ans=0; for(ll i=0;i<=k;i++) { ll p=i,q=i+n-k-1,ansx=1e18,z=m-k-1,w=q-p+1-z; for(ll j=p;j<=p+z;j++) { ansx=min(ansx,max(arr[j],arr[j+w-1])); } ans=max(ans,ansx); } cout<<ans<<endl; } }
cpp
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
#include <iostream> #include <ranges> #include <algorithm> #include <numeric> #include <vector> #include <array> #include <set> #include <map> #include <bit> #include <sstream> #include <list> #include <stack> #include <queue> #include <cmath> typedef long long integerType; typedef integerType z; typedef std::vector<integerType> v; typedef std::vector<v> V; typedef std::set<integerType> s; typedef std::multiset<integerType> S; typedef std::string r; typedef std::vector<r> R; typedef std::vector<bool> b; struct RHEXAOCrocks { RHEXAOCrocks() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); } template<class T> operator T() const { T n; std::cin >> n; return n; } std::string operator()() { std::string s; std::cin >> s; return s; } v operator()(integerType n) { v vec(n); for (auto& n : vec) std::cin >> n; return vec; } R operator()(integerType n, char del) { R vec(n); char ch; std::cin >> ch; vec[0].push_back(ch); int c; for (integerType i{}; i < n;++i) while ((c = std::cin.get()) != del) vec[i].push_back(c); return vec; } V operator()(integerType r, integerType c) { V tab(r, v(c)); for (auto& e : tab) for (auto& n : e) std::cin >> n; return tab; } template<class T> RHEXAOCrocks& operator[](const T& t) { std::cout << t; return *this; } RHEXAOCrocks& operator[](const R& a) { for (auto& e : a) std::cout << e << '\n'; return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const C<Ty>& c) { for (auto Cc{ c.begin() }; Cc != c.end(); std::cout << *Cc << " \n"[++Cc == c.end()]); return *this; } template<class Ty, template<typename T, typename A = std::allocator<T>> class C> RHEXAOCrocks& operator[](const std::vector<C<Ty>>& c) { for (auto& e : c) for (auto E{ e.begin() }; E != e.end(); )std::cout << *E << " \n"[++E == e.end()]; return *this; } }o; #define i(b,e, ...) for(integerType i : std::views::iota(b,e) __VA_ARGS__) #define _i(b,e, ...) for(integerType i : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define j(b,e, ...) for(integerType j : std::views::iota(b,e) __VA_ARGS__) #define _j(b,e, ...) for(integerType j : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define k(b,e, ...) for(integerType k : std::views::iota(b,e) __VA_ARGS__) #define _k(b,e, ...) for(integerType k : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define l(b,e, ...) for(integerType l : std::views::iota(b,e) __VA_ARGS__) #define _l(b,e, ...) for(integerType l : std::views::iota(b,e) | std::views::reverse __VA_ARGS__) #define Aa for(auto A{ a.begin() }, a_end{ a.end() }; A != a_end; ++A) #define Bb for(auto B{ b.begin() }, b_end{ b.end() }; B != b_end; ++B) #define Cc for(auto C{ c.begin() }, c_end{ c.end() }; C != c_end; ++C) #define Dd for(auto D{ d.begin() }, d_end{ d.end() }; D != d_end; ++D) #define z(a) (integerType)((a).size()) #define ff(...) auto f = [&](__VA_ARGS__, const auto& f) #define f(...) f(__VA_ARGS__, f) #define gg(...) auto g = [&](__VA_ARGS__, const auto& g) #define g(...) g(__VA_ARGS__, g) #define hh(...) auto h = [&](__VA_ARGS__, const auto& h) #define h(...) h(__VA_ARGS__, h) using namespace std; namespace ra = ranges; inline void nwmn(integerType nw, integerType& mn) { mn -= ((nw) < mn) * (mn - (nw)); } inline void nwmx(integerType nw, integerType& mx) { mx += ((nw) > mx) * ((nw)-mx); } z power(z a, z b, z M) { z r{ 1 }; do { if (b & 1) (r *= a) %= M; (a *= a) %= M; } while (b >>= 1); return r; } #define w(...) if(__VA_ARGS__) #define _ else #define W(...) while(__VA_ARGS__) #define A(...) for(auto __VA_ARGS__) #define O while(true) void solve_test_case() { z n{ o }, x{}, y{}, mn{ n + 1 }, mnI, mnP; map<pair<z, z>, z> mp; mp[{0, 0}] = -1; i(0, n) { switch ((char)o) { case'L':--x;break; case'R':++x;break; case'U':++y;break; case'D':--y; } w(auto p{ mp.find({x, y}) }; p != mp.end()) { z nw{ i - p->second }; if (nw < mn) { mn = nw; mnP = p->second; mnI = i; } } mp[{x, y}] = i; } w(mn <= n) o[mnP + 1 + 1][' '][mnI + 1]['\n']; _ o["-1\n"]; } int main() { z t{ o }; while (t--) solve_test_case(); }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
// LUOGU_RID: 98169232 //A tree without skin will surely die. //A man without face is invincible. #include<bits/stdc++.h> using namespace std; int const N=5e2+10; char s[N][N];int f[N][N],qz[N][N][255],g[N][N][5]; inline int search(int x,int y,int xx,int yy,int k){return qz[xx][yy][k]-qz[x-1][yy][k]-qz[xx][y-1][k]+qz[x-1][y-1][k];} inline int Search(int x,int y,int xx,int yy,int k){return g[xx][yy][k]-g[x-1][yy][k]-g[xx][y-1][k]+g[x-1][y-1][k];} signed main(){ ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int n,m,q;cin>>n>>m>>q; for (int i=1;i<=n;++i) for (int j=1;j<=m;++j){ cin>>s[i][j]; for (int k=0;k<4;++k) g[i][j][k]=g[i-1][j][k]+g[i][j-1][k]-g[i-1][j-1][k]; if (s[i][j]=='R') ++g[i][j][0]; if (s[i][j]=='G') ++g[i][j][1]; if (s[i][j]=='B') ++g[i][j][2]; if (s[i][j]=='Y') ++g[i][j][3]; } for (int i=1;i<=n;++i) for (int j=1;j<=m;++j){ if (s[i][j]=='R' && s[i+1][j]=='Y' && s[i][j+1]=='G' && s[i+1][j+1]=='B');else continue; f[i][j]=1; for (int k=2;k<=min(n,m)/2;++k){ int x=i-k+1,y=j-k+1,xx=i,yy=j; if (x<1 || y<1 || xx>n || yy>m || y>m || x>n || xx<1 || yy<1) break; if (Search(x,y,xx,yy,0)!=k*k) break; x=i-k+1,y=j+1,xx=i,yy=j+k; if (x<1 || y<1 || xx>n || yy>m || y>m || x>n || xx<1 || yy<1) break; if (Search(x,y,xx,yy,1)!=k*k) break; x=i+1,y=j+1,xx=i+k,yy=j+k; if (x<1 || y<1 || xx>n || yy>m || y>m || x>n || xx<1 || yy<1) break; if (Search(x,y,xx,yy,2)!=k*k) break; x=i+1,y=j-k+1,xx=i+k,yy=j; if (x<1 || y<1 || xx>n || yy>m || y>m || x>n || xx<1 || yy<1) break; if (Search(x,y,xx,yy,3)!=k*k) break; f[i-k+1][j-k+1]=k; } } for (int i=1;i<n;++i) for (int j=1;j<m;++j) if (f[i][j]) qz[i][j][f[i][j]]=1; for (int i=1;i<=n;++i) for (int j=1;j<=m;++j) for (int k=1;k<=min(n,m)/2;++k) qz[i][j][k]+=qz[i-1][j][k]+qz[i][j-1][k]-qz[i-1][j-1][k]; while (q--){ int x,y,xx,yy;cin>>x>>y>>xx>>yy; int k=min(xx-x+1,yy-y+1)/2; while (k && !search(x,y,xx-2*k+1,yy-2*k+1,k)) --k; cout<<4*k*k<<'\n'; } return 0; }
cpp
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1 4 2 1 2 1 2 0 1OutputCopy ? C ? CH ? CCHO ! CCHH InputCopy2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1OutputCopy ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
[ "constructive algorithms", "greedy", "interactive", "math" ]
#include<iostream> #include<cstdio> #include<cassert> #define N 50 using namespace std; int read() { char c=0; int sum=0; while (c<'0'||c>'9') c=getchar(); while ('0'<=c&&c<='9') sum=sum*10+c-'0',c=getchar(); return sum; } int t,n,k,p[N+1]; string s1,s2,s3,s4,s5,s6,s7,divs,zero; bool guess(string s) { cout<<'?'<<' '<<s<<endl,fflush(stdout); k=read(); if (k==-1) exit(0); for (int i=1;i<=k;++i) p[i]=read(); return k; } bool s_guess(string s,int x) { cout<<'?'<<' '<<s<<endl,fflush(stdout); k=read(); if (k==-1) exit(0); for (int i=1;i<=k;++i) p[i]=read(); for (int i=1;i<=k;++i) if (p[i]==x) return 1; return 0; } void bfs(string s) { int ft=p[1]; for (int i=ft-1;i>=1;--i) { if (s_guess('H'+s,i)) s='H'+s; else if (s_guess('O'+s,i)) s='O'+s; else s='C'+s; } for (int i=ft+2;i<=n;++i) { if (s_guess(s+'H',1)) s=s+'H'; else if (s_guess(s+'O',1)) s=s+'O'; else s=s+'C'; } cout<<'!'<<' '<<s<<endl,fflush(stdout); return; } void exbfs(string s) { int ft=p[k]; for (int i=ft-1;i>=1;--i) { if (s_guess('H'+s,i)) s='H'+s; else s='O'+s; } bool op=0; for (int i=ft+2;i<=n;++i) { if (!op) { if (s_guess(s+'H',1)) s=s+'H'; else if (s_guess(s+'O',1)) s=s+'O',op=1; else s=s+'C',op=1; } else { if (s_guess(s+'O',1)) s=s+'O'; else s=s+'C'; } } cout<<'!'<<' '<<s<<endl,fflush(stdout); return; } void exbfs2(string s) { int ft=p[1]; for (int i=ft-1;i>=1;--i) s='H'+s; for (int i=ft+3;i<=n;++i) { if (s_guess(s+'O',1)) s=s+'O'; else s=s+'C'; } cout<<'!'<<' '<<s<<endl,fflush(stdout); return; } void exbfs3(string s) { int ft=p[1]; for (int i=ft+3;i<=n;++i) s=s+'C'; for (int i=ft-1;i>=1;--i) { if (s_guess('H'+s,i)) s='H'+s; else s='O'+s; } cout<<'!'<<' '<<s<<endl,fflush(stdout); return; } void work(string s) { cout<<'!'<<' '; for (int i=1;i<=p[1]-1;++i) cout<<'H'; cout<<s; for (int i=p[1]+3;i<=n;++i) cout<<'C'; cout<<endl; fflush(stdout); return; } int main() { t=read(); while (t--) { n=read(),s1=s2=s3=s4=s5=s6=s7=divs=zero; for (int i=1;i<=n;++i) { s1=s1+'H',s2=s2+'O',s3=s3+'C'; if (i==1) s4=s4+'H',s5=s5+'H',s6=s6+'O',s7=s7+'H'; else { s4=s4+'O',s5=s5+'C',s6=s6+'C',divs=divs+'C'; if (i==2) s7=s7+'O'; else s7=s7+'C'; } } if (guess("CO")) bfs("CO"); else if (guess("CH")) bfs("CH"); else if (guess("OH")) exbfs("OH"); else if (guess("HHO")) exbfs2("HHO"); else if (guess("OOC")) exbfs3("OOC"); else if (guess("HHC")) work("HHC"); else if (guess(divs)) { if (guess(s3)) cout<<'!'<<' '<<s3<<endl,fflush(stdout); else if (guess(s5)) cout<<'!'<<' '<<s5<<endl,fflush(stdout); else cout<<'!'<<' '<<s6<<endl,fflush(stdout); } else { if (guess(s1)) cout<<'!'<<' '<<s1<<endl,fflush(stdout); else if (guess(s2)) cout<<'!'<<' '<<s2<<endl,fflush(stdout); else if (guess(s4)) cout<<'!'<<' '<<s4<<endl,fflush(stdout); else cout<<'!'<<' '<<s7<<endl,fflush(stdout); } int st=read(); if (st==0) break; } return 0; }
cpp
1303
G
G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s1,s2,…,sk][s1,s2,…,sk] as s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk)s1+(s1+s2)+(s1+s2+s3)+⋯+(s1+s2+⋯+sk).You are given a tree consisting of nn vertices. Each vertex ii has an integer aiai written on it. We define the value of the simple path from vertex uu to vertex vv as follows: consider all vertices appearing on the path from uu to vv, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer nn (2≤n≤1500002≤n≤150000) — the number of vertices in the tree.Then n−1n−1 lines follow, representing the edges of the tree. Each line contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), denoting an edge between vertices uiui and vivi. It is guaranteed that these edges form a tree.The last line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤1061≤ai≤106).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInputCopy4 4 2 3 2 4 1 1 3 3 7 OutputCopy36 NoteThe best path in the first example is from vertex 33 to vertex 11. It gives the sequence [3,3,7,1][3,3,7,1], and the sum of prefix sums is 3636.
[ "data structures", "divide and conquer", "geometry", "trees" ]
#include <bits/stdc++.h> #define task "" #define fi first #define se second #define int long long #define fori(i, L, R) for(auto i = (L); i <= (R); ++i) #define ford(i, L, R) for(auto i = (L); i >= (R); --i) using namespace std; void Freopen() { if(fopen(task".inp","r")) { freopen(task".inp","r",stdin); freopen(task".out","w",stdout); } } const int maxn = 150005; typedef long long LL; typedef pair <LL, LL> L4; struct lichao { int childL, childR; long long L, R, mid; L4 line; }; long long val(long long x, L4 line) { return line.fi * x + line.se; } int nT; lichao tree[maxn * 4]; void newnode(int r, long long k, long long l) { tree[r].childL = tree[r].childR = 0; tree[r].line = L4(0, 0); tree[r].L = k; tree[r].R = l; tree[r].mid = (k + l)/2; } void add(int r, L4 newL) { bool tL, tR, tM; tL = (val(tree[r].L, newL) <= val(tree[r].L, tree[r].line)); tR = (val(tree[r].R, newL) <= val(tree[r].R, tree[r].line)); if(tL && tR) return; tL = (val(tree[r].L, newL) >= val(tree[r].L, tree[r].line)); tR = (val(tree[r].R, newL) >= val(tree[r].R, tree[r].line)); if(tL && tR) { tree[r].line = newL; return; } tM = (val(tree[r].mid, newL) >= val(tree[r].mid, tree[r].line)); if(tM) swap(newL,tree[r].line); if(tree[r].L == tree[r].R) return; if(tL != tM) { if(!tree[r].childL) { tree[r].childL = ++nT; newnode(nT, tree[r].L, tree[r].mid); } add(tree[r].childL, newL); } else { if(!tree[r].childR) { tree[r].childR = ++nT; newnode(nT, tree[r].mid + 1, tree[r].R); } add(tree[r].childR, newL); } } LL get(int r, LL x) { LL res = val(x, tree[r].line); if(x <= tree[r].mid) { if(tree[r].childL) res = max(res, get(tree[r].childL, x)); } else { if(tree[r].childR) res = max(res, get(tree[r].childR, x)); } return res; } int n, a[maxn]; vector <int> g[maxn]; void Inp() { scanf("%lld",&n); fori(i, 2, n) { int u, v; scanf("%lld%lld",&u,&v); g[u].push_back(v); g[v].push_back(u); } fori(i, 1, n) scanf("%lld",&a[i]); } int flag, cl[maxn], s[maxn]; void dfssize(int u) { cl[u] = flag; s[u] = 1; for(int v : g[u]) if(cl[v] >= 0 && cl[v] != flag) { dfssize(v); s[u] += s[v]; } } int r, depth[maxn], q[maxn], root; long long sum[maxn], kc[maxn], d[maxn], res; void dfs(int u, int dad) { q[++r] = u; depth[u] = depth[dad] + 1; sum[u] = sum[dad] + a[u]; kc[u] = kc[dad] + sum[u]; d[u] = d[dad] + 1ll * (depth[u] + 1) * a[u]; res = max(res, kc[u] + a[root]); res = max(res, d[u] + get(0, sum[u])); for(int v : g[u]) if(cl[v] != -1 && v != dad) dfs(v, u); } void centroid(int u) { ++flag; dfssize(u); int smax = s[u]; int cen = u, vmax; while(1) { --cl[cen]; vmax = 0; for(int v : g[cen]) if(s[v] * 2 > smax && cl[v] == flag) { vmax = v; break; } if(vmax > 0) cen = vmax; else break; } root = cen; kc[cen] = 0; cl[cen] = -1; d[cen] = sum[cen] = 1ll * a[cen]; depth[cen] = 0; res = max(res, 1ll * a[cen]); newnode(0, 1, 2e16); for(int v : g[cen]) if(cl[v] != -1) { dfs(v, cen); while(r > 0) { int x = q[r]; add(0, L4(depth[x], kc[x] - depth[x] * a[root])); --r; } } reverse(g[cen].begin(),g[cen].end()); newnode(0, 1, 2e16); for(int v : g[cen]) if(cl[v] != -1) { dfs(v, cen); while(r > 0) { int x = q[r]; add(0, L4(depth[x], kc[x] - depth[x] * a[root])); --r; } } for(int v : g[cen]) if(cl[v] != -1) centroid(v); } int32_t main() { Freopen(); Inp(); res = 0; centroid(1); printf("%lld",res); }
cpp
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
#include <bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define ll long long int #define f(i,a,b) for(ll i=a;i<b;i++) #define vl vector<ll> #define asc(v) sort(v.begin(), v.end()) //vectors,pairs,tuples,string #define dsc(v) sort(v.begin(), v.end(), greater<ll>()) #define p2sort(v) sort(v.begin(), v.end(), sortbysec); //for pairs #define mod 1000000007 #define fill(a,b) memset(a, b, sizeof(a)) #define yes return (void) (cout << "YES\n"); #define no return (void) (cout << "NO\n"); //bits using namespace std; using namespace __gnu_pbds; typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key bool sortbysec(const pair<ll,ll> &a,const pair<ll,ll> &b){return (a.second < b.second);} //pairs des 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;} //less than O(sqrt(n)) string decToBin(ll n){string s="";if(n==0){s+='0';return s;}ll i = 0;while (n > 0) {s =to_string(n % 2)+s;n = n / 2;i++;}return s;} ll binToDec(string n){string num = n;ll dec_value = 0;ll base = 1;ll len = num.length();for(ll i = len - 1; i >= 0; i--){if (num[i] == '1')dec_value += base;base = base * 2;}return dec_value;} void swap(ll &x, ll &y) {ll temp = x; x = y; y = temp;} //modfun ncrmodp KMP KMPbool Manacher Rabin //primeFactors allFactors sieve extendedGCD void solve(){ int n; cin >> n; vector<pair<int, int>> p(n); for (auto &pnt : p) cin >> pnt.first; for (auto &pnt : p) cin >> pnt.second; sort(p.begin(), p.end()); pbds s; long long ans = 0; for (int i = 0; i < n; ++i) { // cnt = count of all ( elements before i having speed <= Vi ) int cnt = s.order_of_key(make_pair(p[i].second + 1, -1)); ans += cnt * 1ll * p[i].first; // + xi * cnt s.insert(make_pair(p[i].second, i)); // only elements before i are in the set } s.clear(); for (int i = n - 1; i >= 0; --i) { // cnt = count of all ( elements after i having speed > Vi ) int cnt = int(s.size()) - s.order_of_key(make_pair(p[i].second - 1, n)); // total - less speed = higher speed ans -= cnt * 1ll * p[i].first; // - xi * cnt s.insert(make_pair(p[i].second, i)); } cout << ans << endl; } int main(){ (ios_base:: sync_with_stdio(false),cin.tie(NULL)); ll TC=1; //cin>>TC; while(TC--){solve();} return 0; } //ASCII - (0-9 : 48-57) ; (A-Z : 65-90) ; (a-z : 97-122) //Upper : char(k&'_') , Lower : char(k&' ')
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> #include <string> using namespace std; typedef long long int ll; const int MAXN = 2E5 + 1; const ll MOD = 1E9 + 7; int t; ll solve() { ll n, m; cin >> n >> m; // f(s) можно интерпретировать как // f(s) = [всего подпоследовательностей в An] - [кол-во подпоследовательностей содержащих ТОЛЬКО 0] // [всего подпоследовательностей в An] = n(n + 1)/2 // [кол-во подпоследовательностей содержащих ТОЛЬКО 0] = l1(l1 + 1)/2 + l2(l2 + 1)/2 + .. + lg(lg + 1)/2 // Нам надо минимизировать вычитаемое, чтобы f(s) было максимальным // Для этого, нужно чтобы все li были как можно меньше // А это значит, что мы можем просто разбить исходный массив на m + 1 группу, состоящую из 0 (т.к m единиц разбивает последовательность на m + 1 отрезок) // и содержащие ПРИМЕРНО ОДИНАКОВОЙ количество элементов // Всего нулей z = n - m // Все m + 1 групп будут точно содержать по k = [z / g], g = m + 1 нулей // а дополнительно z % g групп еще по одному доп. нулю (что даст +(k + 1) последовательностей ) ll z = n - m; ll g = m + 1LL; ll k = z / g; ll ans = n * (n + 1LL) / 2LL - k * g * (k + 1LL) / 2LL - (k + 1LL) * (z % g); return ans; } int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> t; while (t-- > 0) { cout << solve() << '\n'; } 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> #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 = 1e9 + 7; 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) { ll res = 1; u %= mod; if (u == 0) { return 0; } while (p > 0) { if (p & 1) { res = (res * u) % mod; } p >>= 1; u = (u * u) % mod; } return res; } 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 = 1e6 + 10; ll n, k, q, m; ll a[N]; string s, s1, s2, s3; void init() { } ll get_ans() { } ll p, b[N]; void single(ll t_id = 0) { cin >> n >> m >> p; FOR(i, 0, n - 1) { cin >> a[i]; } FOR(i, 0, m - 1) { cin >> b[i]; } ll save_i = 0, save_j = 0; FOR(i, 0, n - 1) { if (a[i] % p) { save_i = i; break; } } FOR(j, 0, m - 1) { if (b[j] % p) { save_j = j; break; } } cout << save_i + save_j << "\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
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; using ll = long long; using vll = vector<ll>; void working() { // ll n; // cin >> n; // vll a(n); // for(ll i=0; i<n; i++){ // cin>>a[i]; // } // sort(a.begin(), a.end()); ll n; cin >> n; vll a(n); for(ll i=0; i<n; i++){ cin>>a[i]; } ll i=1, cnt=0, mx=0; while(i<2*n){ mx = max(mx,cnt); if(a[i%n]==1) cnt++; else cnt=0; i++; } cout<<mx; cout << endl; } int main() { #ifndef ONLINE_JUDGE freopen("Input.txt", "r", stdin); freopen("Output.txt", "w", stdout); #endif ll t = 1; // cin >> t; while (t--) { working(); } }
cpp
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
[ "implementation", "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; if(m%n!=0){ cout<<-1<<endl; return 0; } if(n==m){ cout<<0<<endl; return 0; } int ans = m/n; int count = 0; while(ans % 3 == 0){ ans /= 3; count++; } while(ans % 2 == 0){ ans /= 2; count++; } if(ans != 1){ cout<<-1<<endl; } else cout<<count<<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" ]
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << 1 << " " << n - 1 << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { solve(); } }
cpp