contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1322
D
D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4 4 3 1 2 1 1 2 1 2 1 1 2 3 4 5 6 7 8 9 OutputCopy6 InputCopy2 2 1 2 0 0 2 1 -100 -100 OutputCopy2 InputCopy5 4 4 3 2 1 1 0 2 6 7 4 12 12 12 6 -3 -5 3 10 -4 OutputCopy62 NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.
[ "bitmasks", "dp" ]
#include "bits/stdc++.h" using namespace std; #define all(x) begin(x),end(x) template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; } #define debug(a) cerr << "(" << #a << ": " << a << ")\n"; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pi; const int mxN = 1e5+1; const ll oo = 1e18; template<typename T> struct fenwick { int n; vector<T> fen; fenwick(){} fenwick(int nn) { fen.resize(nn+1,-oo); n = nn; } auto max(int i) { ++i; T ans = -oo; while(i) { ans=::max(ans,fen[i]); i&=i-1; } return ans; } void update(int i, T val) { ++i; while(i<=n) { fen[i]=::max(fen[i],val); i+= i&(-i); } } }; int main() { int n,m; cin >> n >> m; vi l(n),s(n); for(auto& i : l) cin >> i; for(auto& i : s) cin >> i; vi c(n+m); for(auto& i : c) cin >> i; c.insert(c.begin(),0); vector<vector<ll>> dp(n+m+1,vector<ll>(n+1,-oo)); fenwick<ll> fenzero(n+m+2); // fenzero // need to take some maximum across a diagonal, all such dp, such that dp[l-x][cnt+x] // and then? not so easy, as their contributions add up. So to add +(cnt+x)*c[l-x] + (cnt+x-1)*c[l-x] // add half of this contribution, then subtract rest? // also cases when the cnt gets to 0 first. Those contribution can be calculated. Do those seperately. fenzero.update(0,0); for(int i=n-1;i>=0;--i) { int x = l[i]; // fenzero ll cnt1 = fenzero.max(x); auto update = [&](int cnt, ll val) { val+=c[x]-s[i]; if(val<=-oo/2) return; // calculate zero int at = x; while(cnt>0) { dp[at][cnt] = max(dp[at][cnt],val); cnt/=2; if(cnt) val+=c[at+1]*cnt; at++; } fenzero.update(at,val); }; for(int cnt=n-1;cnt>=0;--cnt) { // pre-emptivily add. update(cnt+1,dp[x][cnt]); } update(1,cnt1); } cout << fenzero.max(n+m+1) << '\n'; }
cpp
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> #define debug(x) cerr << #x << " = " << x << '\n'; using namespace std; typedef long long ll; #define int long long const int inf = 0x3f3f3f3f; const ll mod = 1e9 + 7; const int N = 5e5 + 10; ll dp[N], dp2[N]; void solve() { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; ++i) { cin >> a[i]; } stack<int> st; for (int i = 1; i <= n; ++i) { dp[i] = a[i]; while (st.size() && a[st.top()] > a[i]) { st.pop(); } int p = (st.size() == 0 ? 0 : st.top()); dp[i] += dp[p] + 1LL * (i - p - 1) * a[i]; st.push(i); } stack<int> st2; for (int i = n; i >= 1; --i) { dp2[i] = a[i]; while (st2.size() && a[st2.top()] > a[i]) { st2.pop(); } int p = (st2.size() == 0 ? n + 1 : st2.top()); dp2[i] += dp2[p] + 1LL * (p - i - 1) * a[i]; st2.push(i); } ll mx = 0, id; for (int i = 1; i <= n; ++i) { int t = dp[i] + dp2[i] - a[i]; if (t > mx) { mx = t; id = i; } } vector<int> ans(n + 1); ans[id] = a[id]; for (int i = id - 1; i >= 1; --i) { ans[i] = min(ans[i + 1], a[i]); } for (int i = id + 1; i <= n; ++i) { ans[i] = min(ans[i - 1], a[i]); } for (int i = 1; i <= n; ++i) { cout << ans[i] << " \n"[i == n]; } } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr);cout.tie(nullptr); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }
cpp
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
#include <bits/stdc++.h> #define ll long long using namespace std; vector<ll> pos[30]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll T; string s,t; cin >> T; while (T--) { cin >> s >> t; for (ll i=0;i<26;i++) pos[i].clear(); for (ll i=0;i<s.size();i++) pos[s[i]-'a'].push_back(i); if (!pos[t[0]-'a'].size()) { cout << -1 << "\n"; continue; } ll cur=pos[t[0]-'a'][0],ans=1; for (ll i=1;i<t.size();i++) { if (!pos[t[i]-'a'].size()) { ans=-1; break; } auto it=upper_bound(pos[t[i]-'a'].begin(),pos[t[i]-'a'].end(),cur); if (it==pos[t[i]-'a'].end()) { cur=pos[t[i]-'a'][0]; ans++; } else cur=*it; } cout << ans << "\n"; } 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> //MACROS #define rep(i, n) for(int i=0; i<n; i++) #define rev_rep(i, n) for(int i=n-1; i>=0; i--) #define index_rep(i, k, n) for(int i=k; i<n; i++) using namespace std; //Grafo vector<vector<int>> derecho; vector<vector<int>> reves; vector<int> distancias_desde_final; vector<bool> visitados; void crear_grafos(int n){ derecho.assign(n+1, vector<int>{}); reves.assign(n+1, vector<int>{}); distancias_desde_final.assign(n+1, INT_MAX); visitados.assign(n+1, false); } void agregar_vecino(vector<vector<int>> &grafo, int a, int b){ grafo[a].push_back(b); } void BFS(vector<vector<int>> &grafo, int inicio, int final){ queue<int> sig_nodo; visitados[inicio] = true; distancias_desde_final[inicio] = 0; sig_nodo.push(inicio); int nodo_actual; int vecino; while(!sig_nodo.empty()){ nodo_actual = sig_nodo.front(); sig_nodo.pop(); for(auto &v : grafo[nodo_actual]){ if(visitados[v] == false){ visitados[v] = true; sig_nodo.push(v); distancias_desde_final[v] = distancias_desde_final[nodo_actual] + 1; } } } } int main(){ //Fast input ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //Input int nodos, aristas, a, b; cin >> nodos >> aristas; crear_grafos(nodos); while(aristas--){ cin >> a >> b; agregar_vecino(derecho, a, b); agregar_vecino(reves, b, a); } int k; cin >> k; vector<int> ruta(k); rep(i, k) cin >> ruta[i]; //PROCESAR //1. Hacer BFS INVERSO BFS(reves, ruta[k-1], ruta[0]); //2. Seguir ruta int distancia_actual = distancias_desde_final[ruta[0]]; int nodo_actual, nodo_anterior; int minimos = 0; int maximos = 0; int idx = 0; for(idx=1; idx<k; idx++){ nodo_actual = ruta[idx]; nodo_anterior = ruta[idx-1]; if(distancia_actual <= distancias_desde_final[nodo_actual]){ //Ruta peor minimos++; maximos++; } else{ //Revisar vecinos for(auto &v : derecho[nodo_anterior]){ if(distancias_desde_final[v] == distancias_desde_final[nodo_actual] && v != nodo_actual){ maximos++; break; } } } distancia_actual = distancias_desde_final[nodo_actual]; } //Resultado cout << minimos << " " << maximos << "\n"; return 0; }
cpp
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second #define pb push_back #define pii pair<int,int> void solve(){ int n; cin >> n; vector<int> a(n), b(n); for(int i = 0; i < n; i++ ){ cin >> a[i]; } for(int i = 0; i < n; i++ ){ cin >> b[i]; } sort(a.begin(), a.end()); sort(b.begin(), b.end()); for(int i = 0; i < n; i++ ){ cout << a[i] << " \n"[i == n - 1]; } for(int i = 0; i < n; i++ ){ cout << b[i] << " \n"[i == n - 1]; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while(T--){ solve(); } return 0; }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
#include<bits/stdc++.h> #define eps 1e-9 #define emailam ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define endl '\n' #define ll long long #define ull unsigned long long #define MAX 200010 #define pb push_back #define all(a) a.begin(),a.end() #define pf push_front #define fi first #define se second #define pii pair<int,int> const int INF = INT_MAX; using namespace std; const int N=1e6+10; #define int long long /*----------------------------------------------------------------*/ int dx[] = {+0, +0, -1, +1, +1, +1, -1, -1}; int dy[] = {-1, +1, +0, +0, +1, -1, +1, -1}; /*----------------------------------------------------------------*/ void READ(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout); #endif } const int mod=1e9+7; ll power(ll x, ll y) { ll ret = 1; while (y > 0) { if (y % 2 == 0) { x = x * x; x %= mod; y = y / 2; } else { ret = ret * x; ret %= mod; y = y - 1; } } return ret; } int fac[N], inv[N]; void precalc() { fac[0] = fac[1] = 1; for (int i = 2; i < N; ++i) { fac[i] = fac[i - 1] * i; fac[i] %= mod; } inv[0] = 1; for (int i = 1; i < N; ++i) { inv[i] = power(fac[i], mod - 2); } } int ncr(int x, int y) { if (x < y)return 0; return ((fac[x] * inv[x - y]) % mod * inv[y]) % mod; } int mul(int a, int b) { return (a * b) % mod; } int add(int a, int b) { return ((a) + (b) + 2 * mod) % mod; } void solve(){ int n,m; cin>>n>>m; precalc(); cout<<ncr(n-1+2*m,n-1)<<endl; } signed main() { emailam //READ(); int t=1; //cin>>t; while(t--){ solve(); } }
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" ]
//Author: Ankush Bhagat (https://github.com/ankushbhagat124) //RFIPITIDS #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; const int N = (int)(3e5 + 1); const int mod = (int)(1e9 + 7); template <class type1> using ordered_multiset = tree <type1, null_type, less <type1>, rb_tree_tag, tree_order_statistics_node_update>; clock_t startTime; double getCurrentTime() { return (double)(clock() - startTime) / CLOCKS_PER_SEC; } void init() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void __print(int x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif /**********************************************************************************************************************/ vector <vector <int>> adj; vector <int> p, c; vector <int> cnt, ans; ordered_multiset <int> st; bool flag = true; void dfs(int u, int p = -1) { cnt[u] = 1; for (auto v : adj[u]) { if (v != p) { dfs(v, u); cnt[u] += cnt[v]; } } } void dfs2(int u, int p = -1) { if (c[u] >= cnt[u]) { flag = false; return; } int val = *(st.find_by_order(c[u])); ans[u] = val; st.erase(st.find(val)); for (auto v : adj[u]) { if (v != p) dfs2(v, u); } } signed main() { init(); startTime = clock(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); /* */ int t = 1; // cin >> t; while (t-- && getCurrentTime() <= 5) { int n; cin >> n; p = vector <int> (n); c = vector <int> (n); cnt = vector <int> (n, 0); ans = vector <int> (n, 0); adj = vector <vector <int>> (n); int root = 0; for (int i = 0; i < n; i++) { cin >> p[i] >> c[i]; p[i]--; if (p[i] >= 0) { adj[i].push_back(p[i]); adj[p[i]].push_back(i); } else root = i; } dfs(root); debug(cnt); for (int i = 1; i <= 2 * n; i++) st.insert(i); flag = true; dfs2(root); if (!flag) cout << "NO"; else { cout << "YES" << endl; for (auto x : ans) cout << x << " "; } } double time = getCurrentTime(); debug(time); }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(),(x).end() #define rep(i,n) for(int i=0;i<(n);i++) #define rep3(i,m,n) for(int i=(m);i<(n);i++) #define foreach(x,a) for(auto& (x) : (a) ) #define endl '\n' #define dump(x) cout << #x << " = " << (x) << endl; #define YES(n) cout << ((n) ? "YES" : "NO" ) << endl #define Yes(n) cout << ((n) ? "Yes" : "No" ) << endl #define POSSIBLE(n) cout << ((n) ? "POSSIBLE" : "IMPOSSIBLE" ) << endl #define Possible(n) cout << ((n) ? "Possible" : "Impossible" ) << endl #define pb(a) push_back(a) #define sz(x) ((int)(x).size()) #define in(a,us) (us).find(a)!=(us).end() template<typename S> using Vec = vector<S>; template<typename S, typename T> using P = pair<S,T>; template<typename S, typename T, typename U> using Tpl = tuple<S,T,U>; using ll = long long; using ld = long double; using Pii = P<int, int>; using Pll = P<ll,ll>; using Tiii = Tpl<int,int,int>; using Tll = Tpl<ll,ll,ll>; using Vi = Vec<int>; using VVi = Vec<Vi>; template<typename S, typename T> using umap = unordered_map<S,T>; template<typename S> using uset = unordered_set<S>; using Graph = VVi; int main(){ cin.tie(0)->sync_with_stdio(0); ll x0,y0,ax,ay,bx,by,xs,ys,t; cin >> x0 >> y0 >> ax >> ay >> bx >> by; cin >> xs >> ys >> t; ll u = pow(10,16); Vec<Pll> data; data.push_back({x0,y0}); while(x0<=u && y0<=u){ x0 = ax*x0 + bx; y0 = ay*y0 + by; data.push_back({x0,y0}); } int n = data.size(); int ans = 0; rep(i,n) rep(j,i+1) rep3(k,i,n){ auto [x,y] = data[i]; auto [x1,y1] = data[j]; auto [x2,y2] = data[k]; ll d = abs(xs-x) + abs(ys-y); ll d1 = abs(x-x1) + abs(y-y1); ll d2 = abs(x-x2) + abs(y-y2); d = min(d+2*d1+d2, d+d1+2*d2); if(t>=d) ans = max(ans, k-j+1); } cout << ans << endl; }
cpp
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
// LUOGU_RID: 94953770 #include <bits/stdc++.h> using namespace std; constexpr int N = 1 << 18; int n, fa[N], sz[N]; long long ans; int findf(int x) { return x == fa[x] ? x : fa[x] = findf(fa[x]); } void unite(int u, int v, int w) { if (!sz[u] || !sz[v]) return; if ((u = findf(u)) == (v = findf(v))) return; ans += w * (sz[u] + sz[v] - 1ll), sz[fa[u] = v] = 1; } signed main() { cin.tie(nullptr)->sync_with_stdio(false); cin >> n, sz[0] = 1; for (int i = 1, a; i <= n; ++i) cin >> a, ans -= a, ++sz[a]; iota(fa, fa + N, 0); for (int i = N - 1; i; --i) { int j = i; do unite(j, i ^ j, i), j = (j - 1) & i; while (j != i); } return cout << ans << endl, 0; }
cpp
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
[ "implementation", "number theory" ]
#include <bits/stdc++.h> using namespace std; int main() { int t,n,odd,even; cin>>t; while(t--){ odd=0,even=0; cin>>n; int a[n]; for(int j=0;j<n;j++){ cin>>a[j]; if(a[j]%2==0){ even++; } else{ odd++; } } if(even==n||odd==n){ cout<<"YES"<<endl; } else{ cout<<"NO"<<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; #ifdef LOCAL #include "debug.h" #else #define dout(...) 0 #endif int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<set<int>> g(n); for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; --u, --v; g[u].insert(v); g[v].insert(u); } set<int> leafs; for (int i = 0; i < n; i++) { if (g[i].size() == 1) { leafs.insert(i); } } auto ask = [](int u, int v) { cout << "? " << u + 1 << ' ' << v + 1 << endl; int x; cin >> x; --x; return x; }; function<void(int, int, int)> dfsdelete = [&](int u, int p, int x) { if (leafs.find(u) != leafs.end()) { leafs.erase(u); } for (int v : g[u]) { if (v == p) { continue; } if (v == x) { g[x].erase(u); } else { dfsdelete(v, u, x); } } }; int r = -1; while (leafs.size() > 1) { dout(vector<int>(leafs.begin(), leafs.end())); auto it = leafs.begin(); int u = *it; leafs.erase(it); it = leafs.begin(); int v = *it; leafs.erase(it); int x = ask(u, v); if (x == u || x == v) { r = x; break; } dfsdelete(u, -1, x); dfsdelete(v, -1, x); if (g[x].size() <= 1) { leafs.insert(x); } } if (r == -1) { r = *leafs.begin(); } cout << "! " << r + 1 << endl; return 0; }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include<bits/stdc++.h> #define int long long int #define F first #define S second #define pb push_back using namespace std; int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b, c, n; cin >> a >> b >> c >> n; int maxt = -1; maxt = max(a, max(b, c)); int s = a + b + c + n; if (s % 3 == 0 and s / 3 >= maxt) { cout << "Yes" << endl; } else { cout << "NO" << endl; } } return 0; }
cpp
1307
G
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm; which consists of nn fields connected by mm directed roads. Each road takes some time wiwi to cross. She is currently at field 11 and will return to her home at field nn at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed xixi for the ii-th plan. Determine the maximum he can make the shortest path from 11 to nn for each of the qq independent plans.InputThe first line contains integers nn and mm (2≤n≤502≤n≤50, 1≤m≤n⋅(n−1)1≤m≤n⋅(n−1)) — the number of fields and number of roads, respectively.Each of the following mm lines contains 33 integers, uiui, vivi, and wiwi (1≤ui,vi≤n1≤ui,vi≤n, 1≤wi≤1061≤wi≤106), meaning there is an road from field uiui to field vivi that takes wiwi time to cross.It is guaranteed that there exists a way to get to field nn from field 11. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from uu to vv and a road from vv to uu.The next line contains a single integer qq (1≤q≤1051≤q≤105), the number of plans.Each of the following qq lines contains a single integer xixi, the query (0≤xi≤1050≤xi≤105).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed xixi.Your answer is considered correct if its absolute or relative error does not exceed 10−610−6.Formally, let your answer be aa, and the jury's answer be bb. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6|a−b|max(1,|b|)≤10−6.ExampleInputCopy3 3 1 2 2 2 3 2 1 3 3 5 0 1 2 3 4 OutputCopy3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000
[ "flows", "graphs", "shortest paths" ]
#include<bits/stdc++.h> #define fi first #define se second using namespace std; const int _=100,inf=1e9; int S,T,n,m,Q,head[_],ne[_*_],to[_*_],w[_*_],c[_*_],tot=1,x; int dis[_],vis[_],p[_]; vector<pair<int,int>>ans; void add(int x,int y,int z,int a){ ne[++tot]=head[x],head[x]=tot,to[tot]=y,w[tot]=z,c[tot]=a; } void ad(int x,int y,int z){ add(x,y,1,z),add(y,x,0,-z); } bool bfs(){ for(int i=1;i<=n;i++)dis[i]=inf,vis[i]=0; queue<int>q;q.push(S),vis[S]=1,dis[S]=0; while(q.size()){ int u=q.front();q.pop(),vis[u]=0; for(int i=head[u];i;i=ne[i]) if(w[i]&&dis[to[i]]>dis[u]+c[i]){ dis[to[i]]=dis[u]+c[i],p[to[i]]=i; if(!vis[to[i]])vis[to[i]]=1,q.push(to[i]); } } return dis[T]!=inf; } void EK(){ int flow=0,cost=0; while(bfs()){ int f=inf; for(int i=T;i!=S;i=to[p[i]^1])f=min(f,w[p[i]]); flow+=f,cost+=dis[T]*f; for(int i=T;i!=S;i=to[p[i]^1])w[p[i]]-=f,w[p[i]^1]+=f; ans.push_back({flow,cost}); } } int main(){ scanf("%d%d",&n,&m); for(int i=1,y,z;i<=m;i++) scanf("%d%d%d",&x,&y,&z),ad(x,y,z); S=1,T=n;EK(); scanf("%d",&Q); while(Q--){ scanf("%d",&x); long double Min=inf; for(auto v:ans)Min=min(Min,(long double)(v.se+x)/v.fi); printf("%.10Lf\n",Min); } 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" ]
#include<bits/stdc++.h> using namespace std; int i,j,k,n,a[110][27];string s,S; int main(){ cin>>n;cout<<"? 1 "<<n<<endl; for (i=1;i<=n*(n+1)/2;i++){cin>>s; for (auto ch:s) a[s.length()][ch-97]++; } if (n>1) cout<<"? 2 "<<n<<endl; for (i=1;i<=n*(n-1)/2;i++){cin>>s; for (auto ch:s) a[s.length()][ch-97]--; } for (i=1;i<=n;i++) for (j=0;j<26;j++) if (a[i][j]) for (S+=char(j+97),k=i+1;k<=n;k++) a[k][j]--; cout<<"! "<<S<<endl; return 0; }
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" ]
// LUOGU_RID: 102122836 #include <bits/stdc++.h> using namespace std; const int _ = 2e5 + 5; int n; int col[_] , dp1[_] , dp2[_]; vector< int > G[_]; void DFS1( int x , int fa ) { dp1[ x ] = col[ x ]; for( int i = 0 ; i < G[ x ].size() ; i++ ) { if( G[ x ][ i ] != fa ) { DFS1( G[ x ][ i ] , x ); dp1[ x ] += max( 0 , dp1[ G[ x ][ i ] ] ); } } } void DFS2( int x , int fa ) { if( x != 1 ) dp2[ x ] = max( dp2[ fa ] - max( 0 , dp1[ x ] ) , 0 ) + dp1[ x ]; for( int i = 0 ; i < G[ x ].size() ; i++ ) { if( G[ x ][ i ] != fa ) DFS2( G[ x ][ i ] , x ); } } int main() { cin >> n; for( int i = 1 , x ; i <= n ; i++ ) { cin >> x; col[ i ] = x * 2 - 1; } for( int i = 1 , u , v ; i < n ; i++ ) { cin >> u >> v; G[ u ].push_back( v ); G[ v ].push_back( u ); } DFS1( 1 , 0 ); dp2[ 1 ] = dp1[ 1 ]; DFS2( 1 , 0 ); for( int i = 1 ; i <= n ; i++ ) cout << dp2[ i ] << " \n"[ i == n ]; return 0; }
cpp
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
#include<iostream> #include<queue> #include <algorithm> #include "vector" using namespace std; void solve() { int x; cin >> x; cout << 1 << ' ' << x-1 << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t = 1; cin >> t; while (t--) { solve(); } return 0; }
cpp
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
#include<bits/stdc++.h> #include<math.h> #include<string.h> #include<cstring> #include<string> #include<vector> #include<stdlib.h> #include <ext/pb_ds/exception.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/type_utils.hpp> #include <ext/pb_ds/detail/hash_fn/mask_based_range_hashing.hpp> #include <ext/pb_ds/detail/hash_fn/mod_based_range_hashing.hpp> #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update #define MOD 1000000007 #define INF 1e18 #define ff first #define ss second #define PI 3.141592653589793238462 #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define small 0 const int N = 2000005; #define MAXN 100001 #define endl "\n" using namespace std; using namespace __gnu_pbds; #define debug(x) cerr << #x << " " << x << endl; #define debug1(x) cerr << #x << " " << x << " "; typedef long long int ll; typedef long double lld; #define timeset ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); /*#define debug(x); printf(x);*/ void init() { #ifndef ONLINE_JUDGE freopen("input.txt" , "r" ,stdin); freopen("output.txt" , "w" ,stdout); #endif } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> pbds_pair; ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} int modpow(int b, int e){int ans = 1;b %= MOD;while(e){if(e & 1) ans = (ans * b) % MOD;e >>= 1;b = (b * b) % MOD;}return ans;} int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);} int max(int a, int b) {if (a > b) return a; else return b;} int min(int a, int b) {if (a < b) return a; else return b;} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} void debug_vector(vector<int> v){for(auto i:v){cerr << i << " ";}cerr << endl;} void debug_map(map<ll,ll> mp){for(auto i:mp){cerr << i.ff << " " << i.ss << endl;}} void debug_set(set<ll> v){for(auto i:v){cerr << i << " ";}} vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;} ll Testcase_generator(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);} void testcase_generator(ll n,ll l,ll r){for(int i=0;i<n;i++){cerr << Testcase_generator(l,r) << endl;}} void precision(lld a) { cout << setprecision(a) << fixed; } // { // reference // cerr << "0th element: " << *A.find_by_order(0) << endl; // cerr << "No. of elements smaller than 6: " << A.order_of_key(6) << endl; // 2 // cerr << "Lower Bound of 6: " << *A.lower_bound(6) << endl; // cerr << "Upper Bound of 6: " << *A.upper_bound(6) << endl; // } //** pritishcf307 **// //**------------------------------------------------------------------------------------------------------**// //** code starts here **// void solve(){ ll n,k; cin >> n >> k; ll a = n; ll b = k; ll c = 0; ll d = 0; c = a / (b+1); d = a - c; c = b * c * (c+1)/2; d = d * (d+1)/2; ll x = c + d; cout << x << endl; } int main(){ init(); IOS; ll t=1; cin >> t; while(t--){ solve(); } }
cpp
1303
F
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10 2 1 1 1 2 1 2 2 1 1 1 2 3 1 2 1 2 2 2 2 2 2 1 2 3 2 4 2 1 5 OutputCopy2 4 3 3 4 4 4 2 2 4
[ "dsu", "implementation" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef vector<int> vi; typedef pair<int, int> pii; #define IOS ios::sync_with_stdio(0) #define For(i,a,b) for (int i=(a),_b=(b);i<=_b;i++) #define FOr For #define Iter(i,a,b) for (int i=(a),_b=(b);i<_b;i++) #define Downto(i,a,b) for (int i=(a),_b=(b);i>=_b;i--) #define set0(a) memset(a,0,sizeof(a)) #define set0n(a,n) memset(a,0,sizeof((a)[0])*(n+1)) #define pb push_back #define mkp make_pair #define all(a) (a).begin(),(a).end() template <class T1, class T2> inline void getmin(T1& x, const T2& y) {if (y < x) x = y;} template <class T1, class T2> inline void getmax(T1& x, const T2& y) {if (x < y) x = y;} //char NY[2][10]={"NO\n","YES\n"};//capital? #ifdef DEBUG #define SHOW(x) (cerr<<#x"="<<(x)<<endl,(x)) #define MSG(s) (cerr<<"MESSAGE: "<<(s)<<endl,0) #else #define SHOW(x) (x) #define MSG(s) 0 #endif const int N = 303, NN = N * N, Q = 2e6 + 10; const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; int n, m, q; int first[Q], last[Q]; int dt[Q]; struct Query { int x, y, c; } a[Q]; vi cover[Q]; int cc[N][N];//current color int fa[NN]; int find(int x) {return fa[x] == x ? x : (fa[x] = find(fa[x]));} inline void merge(int x, int y) {fa[find(y)] = find(x);} #define pt(x,y) ((x)*m+(y)) inline bool in(int x, int y) {return 1 <= x && x <= n && 1 <= y && y <= m;} inline int add(int x, int y, int c) { if (!x && !y) { return 0; } int cnt = 0, x2, y2; cc[x][y] = c; For(d, 0, 3) if (in(x2 = x + dx[d], y2 = y + dy[d]) && cc[x2][y2] == c && find(pt(x, y)) != find(pt(x2, y2))) { cnt++, merge(pt(x, y), pt(x2, y2)); } return 1 - cnt; } signed main() { IOS; cin >> n >> m >> q; For(i, 1, q) { int x, y, c; cin >> x >> y >> c; if (cc[x][y] == c) {x = y = 0;} else { cover[cc[x][y]].pb(i); } a[i] = (Query) {x, y, c}; last[cc[x][y] = c] = i; if (c != a[i - 1].c) { first[c] = i; } } dt[0] = 1, last[0] = -1; For(c, 0, a[q].c) { if (!last[c]) { continue; } if (c) { iota(fa, fa + 1 + (n + 1)*m, 0); For(i, 1, n) set0n(cc[i], m); For(i, first[c], last[c]) { dt[i] += add(a[i].x, a[i].y, c); } } iota(fa, fa + 1 + (n + 1)*m, 0); reverse(all(cover[c])); for (auto i : cover[c]) { cc[a[i].x][a[i].y] = -1; } if (c) { For(i, first[c], last[c]) if (cc[a[i].x][a[i].y] != -1) add(a[i].x, a[i].y, c); } //only merging else { For(x, 1, n) For(y, 1, m) if (cc[x][y] != -1) add(x, y, 0); } //beware braces!!! for (auto i : cover[c]) { dt[i] -= add(a[i].x, a[i].y, c); } } For(i, 1, q) dt[i] += dt[i - 1], cout << dt[i] << '\n'; return cout << flush, 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
#include<bits/stdc++.h> using namespace std; #define ll long long int main() { ll n; cin>>n; ll a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } ll b[n]; for(int i=0;i<n;i++) { cin>>b[i]; } ll count1=0; ll count2=0; for(int i=0;i<n;i++) { if(a[i]==1 && b[i]==0) count1++; else if(a[i]==0 && b[i]==1) count2++; } if(count1!=0 && count2!=0) cout<<count2/count1+1<<endl; else if(count1==0 && count2==0) cout<<"-1"<<endl; else if(count1==0 && count2!=0) cout<<"-1"<<endl; else cout<<"1"<<endl; }
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; char ch[510][510]; int n,m,q,f[510][510],g[510][510][5],h[510][510][275]; int main() { scanf("%d%d%d",&n,&m,&q); for (int i=1;i<=n;i++) scanf("%s",ch[i]+1); for (int i=1;i<=n;i++) for (int j=1;j<=m;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(ch[i][j]=='R') g[i][j][0]++; if(ch[i][j]=='G') g[i][j][1]++; if(ch[i][j]=='B') g[i][j][2]++; if(ch[i][j]=='Y') g[i][j][3]++; } for (int i=1;i<n;i++) for (int j=1;j<m;j++) if(ch[i][j]=='R'&&ch[i+1][j]=='Y'&&ch[i][j+1]=='G'&&ch[i+1][j+1]=='B') { f[i][j]=1; for (int k=2;k<=min(n,m)/2;k++) { int x=i-k+1,y=j-k+1; int a=i,b=j; if(x<1||y<1) break; if(g[a][b][0]-g[a][y-1][0]-g[x-1][b][0]+g[x-1][y-1][0]!=k*k) break; x=i-k+1,y=j+1; a=i,b=j+k; if(x<1||y<1||a>n||b>m) break; if(g[a][b][1]-g[a][y-1][1]-g[x-1][b][1]+g[x-1][y-1][1]!=k*k) break; x=i+1,y=j+1; a=i+k,b=j+k; if(x<1||y<1||a>n||b>m) break; if(g[a][b][2]-g[a][y-1][2]-g[x-1][b][2]+g[x-1][y-1][2]!=k*k) break; x=i+1,y=j-k+1; a=i+k,b=j; if(x<1||y<1||a>n||b>m) break; if(g[a][b][3]-g[a][y-1][3]-g[x-1][b][3]+g[x-1][y-1][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]) h[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++) h[i][j][k]+=h[i-1][j][k]+h[i][j-1][k]-h[i-1][j-1][k]; while (q--) { int x,y,xx,yy; scanf("%d%d%d%d",&x,&y,&xx,&yy); int mx=min(xx-x+1,yy-y+1)/2; bool bo=0; for (int k=mx;k>=1;k--) { int sx=xx-2*k+1; int sy=yy-2*k+1; if (h[sx][sy][k]-h[sx][y-1][k]-h[x-1][sy][k]+h[x-1][y-1][k]) { printf("%d\n",k*k*4); bo=1; break; } } if (bo) continue; puts("0"); } return 0; }
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
// LUOGU_RID: 101076779 #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 2e5 + 5; const int M = 1e6 + 5; int n, prime[M], tot; ll a[N]; mt19937 rnd(19260817); bool vis[M]; inline void Euler() { for (int i = 2; i <= M - 5; i++) { if (!vis[i]) prime[++tot] = i; for (int j = 1; j <= tot && 1ll * i * prime[j] <= M - 5; j++) { vis[i * prime[j]] = true; if (!(i % prime[j])) break; } } } set<ll> s; inline void solve(ll x) { for (int i = 1; i <= tot && x > 1; i++) if (!(x % prime[i])) { s.insert(prime[i]); while (!(x % prime[i])) x /= prime[i]; } if (x > 1) s.insert(x); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); Euler(); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= 50; i++) { int x = rnd() % n + 1; if (a[x] > 2) solve(a[x] - 1); solve(a[x]), solve(a[x] + 1); } ll ans = n; for (ll x : s) { ll cur = 0; for (int i = 1; i <= n; i++) cur += a[i] < x ? x - a[i] : min(a[i] % x, x - a[i] % x); ans = min(ans, cur); } cout << ans; return 0; }
cpp
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
/** * author: Pratham_Shah10 * date: 10.02.2023 **/ #include<bits/stdc++.h> using namespace std; #define fastio() ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define endl "\n" #define pb push_back #define ff first #define ss second #define sz(x) ((ll)(x).size()) #define all(x) x.begin(),x.end() #define set_bits __builtin_popcountll typedef long long ll; typedef unsigned long long ull; typedef long double lld; #ifndef ONLINE_JUDGE #define debug(x) cerr << #x <<": "; _print(x); cerr << endl; #else #define debug(x) #endif void _print(ll t) {cerr << t;} void _print(int t) {cerr << t;} void _print(string t) {cerr << t;} void _print(char t) {cerr << t;} void _print(lld t) {cerr << t;} void _print(double t) {cerr << t;} void _print(ull t) {cerr << t;} template <class T, class V> void _print(pair <T, V> p); template <class T> void _print(vector <T> v); template <class T> void _print(set <T> v); template <class T, class V> void _print(map <T, V> v); template <class T> void _print(multiset <T> v); template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.first); cerr << ","; _print(p.second); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} /* ------------------------------------------------------------------------------------------------------------------------------------------------ */ void google(int t) {cout << "Case #" << t << ": ";} ll binexpo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} ll min(ll a, ll b) {if (a > b) return b; return a;} ll max(ll a, ll b) {if (a > b) return a; return b;} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);} ll lcm(ll a, ll b) {return ((a * b) / (gcd(a, b)));} /* ------------------------------------------------------------------------------------------------------------------------------------------------ */ void solve() { int n; cin >> n; string s; cin >> s; int cnt = 0; while (1) { n = s.length(); set<pair<char, int>>st; for (int i = 0; i < n; i++) { int t1 = (i + 1 < n) ? s[i] - s[i + 1] : 0; int t2 = (i - 1 >= 0) ? s[i] - s[i - 1] : 0; if (t1 == 1 || t2 == 1) { st.insert({s[i], i}); } } if (st.empty()) break; pair<char, int>pr = *st.rbegin(); string s1 = s.substr(0, pr.ss); string s2 = ""; if (pr.ss + 1 < n) { s2 = s.substr(pr.ss + 1); } s = s1 + s2;//.substr(pr.ss + 1, n - 1 - pr.ss - 1 + 1); cnt++; } cout << cnt << endl; } int main() { #ifndef ONLINE_JUDGE freopen("Error.txt", "w", stderr); #endif fastio(); solve(); }
cpp
1312
G
G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10 0 i 1 q 2 g 0 k 1 e 5 r 4 m 5 h 3 p 3 e 5 8 9 1 10 6 OutputCopy2 4 1 3 3 InputCopy8 0 a 1 b 2 a 2 b 4 a 4 b 5 c 6 d 5 2 3 4 7 8 OutputCopy1 2 2 4 4 NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.
[ "data structures", "dfs and similar", "dp" ]
#include <bits/stdc++.h> using namespace std; // clang-format off namespace { enum operand_type_enum : uint32_t { RAW = 0, COMPOSED = 1 << 1, REQUIRE_PARAM = 1 << 2, }; template <class T> concept has_operand_type = requires() { { T::operand_type } -> convertible_to<uint32_t>; }; template <class T> class operand_type { public: inline static constexpr uint32_t value() { if constexpr (has_operand_type<T>) return T::operand_type; else return operand_type_enum::RAW; } }; template <class T> constexpr uint32_t operand_type_v = operand_type<decay_t<T>>::value(); template <class T> concept is_raw = ((operand_type_v<T> & RAW) == RAW); template <class T> concept is_composed = ((operand_type_v<T> & COMPOSED) == COMPOSED); template <class T> concept require_param = ((operand_type_v<T> & REQUIRE_PARAM) == REQUIRE_PARAM); template <class T> concept require_no_param = !require_param<T>; template <class left_t, class right_t> class composed_operation_t { public: inline static constexpr uint32_t operand_type = COMPOSED | operand_type_v<right_t> | operand_type_v<left_t>; left_t left; right_t right; }; template <class left_t, class right_t> requires(is_composed<left_t> && (!is_composed<right_t>)) auto operator|(left_t&& left, right_t&& right) { return left.left | (left.right | right); } template <class left_t, class right_t> requires(is_raw<left_t>&& require_param<right_t>) auto operator|(left_t&& left, right_t&& right) { return composed_operation_t<left_t, right_t>(left, right); } namespace array_binding_details { template <typename T> class array_binding_t_full { public: inline static constexpr uint32_t operand_type = RAW; T* array; int l, r; T* begin() { return array + l; } T* end() { return array + r + 1; } void resize(const size_t sz) { r = l + sz - 1; } }; class array_binding_t_l_r { public: inline static constexpr uint32_t operand_type = RAW; template <typename T> friend array_binding_t_full<T> operator|(T* array, const array_binding_t_l_r& binding) { return array_binding_t_full<T>{array, binding.l, binding.r}; } int l, r; }; class array_binding_t_l { public: inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l_r operator|(const int r) const { return array_binding_t_l_r{l, r}; } int l; }; class array_binding_t_empty { public: inline static constexpr uint32_t operand_type = REQUIRE_PARAM; array_binding_t_l operator|(const int l) const { return array_binding_t_l{l}; } }; static_assert(has_operand_type<array_binding_t_empty>); static_assert(require_param<array_binding_t_empty>); } enum general_operation_t { REVERSE, }; enum comparable_operation_t { SORT, UNIQUE, PREFIX_MIN, PREFIX_MAX, }; enum integer_operation_t { PREFIX_AND, PREFIX_OR, PREFIX_XOR, }; enum number_operation_t { PREFIX_SUM, PREFIX_PROD, }; enum single_input_operation_t { NEXT_INPUT, }; enum array_input_operation_t { ARRAY_INPUT, INDEX_1, }; enum array_output_operation_t { OUTPUT_1LINE, OUTPUT_1_PER_LINE, }; template <typename container_t> auto operator|(container_t&& a, const general_operation_t& op) { switch (op) { case REVERSE: reverse(a.begin(), a.end()); break; default: assert(false); }; return a; } template <typename container_t> auto operator|(container_t&& a, const comparable_operation_t& op) { switch (op) { case SORT: { sort(a.begin(), a.end()); break; }; case UNIQUE: { sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); break; } case PREFIX_MIN: { auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = min(*begin, *(begin - 1)); begin++; } break; } case PREFIX_MAX: { auto begin = a.begin(); ++begin; while (begin < a.end()) { (*begin) = max(*begin, *(begin - 1)); begin++; } break; } default: assert(false); } return a; } template <typename container_t> auto operator|(container_t&& a, const number_operation_t& op) { switch (op) { case PREFIX_SUM: { for (size_t i = 1; i < a.size(); i++) a[i] += a[i - 1]; break; } case PREFIX_PROD: { for (size_t i = 1; i < a.size(); i++) a[i] *= a[i - 1]; break; } default: assert(false); } return a; } template <typename container_t> auto operator|(container_t&& a, const integer_operation_t& op) { switch (op) { case PREFIX_AND: { for (size_t i = 1; i < a.size(); i++) a[i] &= a[i - 1]; break; } case PREFIX_OR: { for (size_t i = 1; i < a.size(); i++) a[i] |= a[i - 1]; break; } case PREFIX_XOR: { for (size_t i = 1; i < a.size(); i++) a[i] ^= a[i - 1]; break; } default: break; } return a; } template <typename container_t> auto operator|(container_t&& a, const array_input_operation_t& op) { switch (op) { case ARRAY_INPUT: { for (auto&& x : a) cin >> x; break; } default: assert(0); } return a; } template <typename container_t> auto operator|(container_t&& a, const array_output_operation_t& op) { switch (op) { case OUTPUT_1LINE: { for (auto&& x : a) cout << x << ' '; cout << '\n'; break; } case OUTPUT_1_PER_LINE: { for (auto&& x : a) cout << x << '\n'; cout << '\n'; break; } default: assert(0); } return a; } constexpr array_binding_details::array_binding_t_empty ARRAY; } // clang-format on // #define MULTI_TEST // #define SKIP_ASSERT #ifdef SKIP_ASSERT #define assert(x) (x) #endif vector<pair<char, int>> g[1000001]; int f[1000001]; int a[1000001]; bool in_set[1000001]; class segment_tree_t { public: segment_tree_t *left, *right; int l, r, m; int min_val; int lazy; segment_tree_t(int l, int r) : l(l), r(r), m((l + r) / 2), min_val(0), lazy(0) { if (l != r) { left = new segment_tree_t(l, m); right = new segment_tree_t(m + 1, r); } } void down() { if (lazy == 0) return; left->min_val += lazy; left->lazy += lazy; right->min_val += lazy; right->lazy += lazy; lazy = 0; } void update(const int& u, const int& v, const int& x) { if (l > v || r < u) return; if (u <= l && v >= r) { min_val += x; lazy += x; } else { down(); left->update(u, v, x); right->update(u, v, x); min_val = min(left->min_val, right->min_val); } } int get(const int& u, const int& v) { if (l > v || r < u) return 1e9; if (u <= l && v >= r) return min_val; down(); return min(left->get(u, v), right->get(u, v)); } void set(const int& u, const int& x) { if (l == r) { min_val = x; } else { down(); if (m >= u) left->set(u, x); else right->set(u, x); min_val = min(left->min_val, right->min_val); } } }; segment_tree_t* tree; void dfs(int u, int h = 0) { if (u == 0) { f[u] = 0; } else { if (in_set[u]) { tree->update(0, h - 1, 1); f[u] = min(f[u], tree->get(0, h - 1)); } } tree->set(h, f[u] + in_set[u]); for (auto&& [c, v] : g[u]) { f[v] = f[u] + 1; dfs(v, h + 1); } } void solve() { int n; cin >> n; tree = new segment_tree_t(0, n); for (int i = 1; i <= n; i++) { int p; char c; cin >> p >> c; g[p].emplace_back(c, i); } for (int i = 0; i <= n; i++) g[i] | SORT; int k; cin >> k; for (int i = 1; i <= k; i++) { cin >> a[i]; in_set[a[i]] = 1; } dfs(0); for (int i = 1; i <= k; i++) cout << f[a[i]] << " \n"[i == k]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t = 1; #ifdef MULTI_TEST cin >> t; #endif while (t--) solve(); }
cpp
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
#include<stdio.h> #include<iostream> #include<vector> #include<map> #include<set> #include<queue> #include<algorithm> #include<string.h> using namespace std; const int N = 2e5 + 5; int b[N]; void solve() { string a; cin>>a; int len = a.size(); b[1] = 0; int idx = 1; for(int i = 0; i < len; i++) { if(a[i] == 'R') b[++idx] = i + 1; } b[++idx] = len + 1; int g = 0; for(int i = 2; i <= idx; i++) { g = max(g, b[i] - b[i - 1]); } cout<<g; cout<<'\n'; } int main() { std::ios::sync_with_stdio(false); int t; cin>>t; while(t--) { solve(); } // solve(); }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include <iostream> #include <vector> using namespace std; #define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL); typedef long long int64; struct Point{ double x, y; Point(){ } Point(double x, double y){ this->x = x; this->y = y; } }; Point sub(Point &A, Point &B){ return Point(A.x - B.x, A.y - B.y); } int main(){ fastIO int n; cin >> n; vector<Point> polygon(n); for (int i = 0; i < n; i++){ Point p; cin >> p.x >> p.y; polygon[i] = p; } if (n % 2 != 0){ cout << "No"; } else{ Point center(0, 0); for (Point p : polygon){ center.x += p.x; center.y += p.y; } center.x /= n; center.y /= n; bool aerodynamic = true; for (int i = 0; i < n / 2; i++){ Point A = polygon[i]; Point B = polygon[n / 2 + i]; Point OA = sub(A, center); Point OB = sub(B, center); if (OA.x != -OB.x || OA.y != -OB.y){ aerodynamic = false; break; } } if (aerodynamic) cout << "Yes"; else cout << "No"; } return 0; }
cpp
13
D
D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7
[ "dp", "geometry" ]
#include <iostream> #include <algorithm> using namespace std; typedef long long ll; static const int MAXN=500+10; int cnt[MAXN][MAXN]; struct Point{ int x,y; Point(){} Point(int _x,int _y):x(_x),y(_y){} void input() { scanf("%d%d",&x,&y); } bool operator<(const Point &b)const{ return y<b.y; } ll operator^(const Point &b)const{ return 1ll*x*b.y-1ll*y*b.x; } }red[MAXN],blue[MAXN]; bool check(Point a,Point b,Point c) { return c.y>=a.y && c.y<b.y && (a^b)+(b^c)+(c^a)>0; } int n,m; int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) red[i].input(); for(int i=1;i<=m;i++) blue[i].input(); sort(red+1,red+n+1); for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) for(int k=1;k<=m;k++) if(check(red[i],red[j],blue[k])) cnt[i][j]++; int res=0; for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) for(int k=j+1;k<=n;k++) if(cnt[i][j]+cnt[j][k]==cnt[i][k]) res++; printf("%d\n",res); return 0; }
cpp
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> #include <ext/rope> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/hash_policy.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_cxx; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>; using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>; // template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>; template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>; #define ll long long #define i128 ll #define ld long double #define ui unsigned int #define ull unsigned long long #define pii pair<int, int> #define pll pair<ll, ll> #define pdd pair<ld, ld> #define vi vector<int> #define vvi vector<vector<int>> #define vll vector<ll> #define vvll vector<vector<ll>> #define vpii vector<pii> #define vpll vector<pll> #define lb lower_bound #define ub upper_bound #define pb push_back #define pf push_front #define eb emplace_back #define fi first #define se second #define rep(i, a, b) for(int i = a; i < b; ++i) #define per(i, a, b) for(int i = a; i > b; --i) #define each(x, v) for(auto& x: v) #define len(x) (int)x.size() #define elif else if #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define mst(x, a) memset(x, a, sizeof(x)) #define lowbit(x) (x & (-x)) #define bitcnt(x) (__builtin_popcountll(x)) #define endl "\n" mt19937 rng( chrono::steady_clock::now().time_since_epoch().count() ); #define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a) struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } size_t operator()(pair<uint64_t,uint64_t> x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1); } }; const i128 ONE = 1; istream &operator>>(istream &in, i128 &x) { string s; in >> s; bool minus = false; if (s[0] == '-') { minus = true; s.erase(s.begin()); } x = 0; for (auto i : s) { x *= 10; x += i - '0'; } if (minus) x = -x; return in; } ostream &operator<<(ostream &out, i128 x) { string s; bool minus = false; if (x < 0) { minus = true; x = -x; } while (x) { s.push_back(x % 10 + '0'); x /= 10; } if (s.empty()) s = "0"; if (minus) out << '-'; reverse(s.begin(), s.end()); out << s; return out; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const set<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) { os << p.first << " " << p.second; return os; } ll gcd(ll x,ll y) { if(!x) return y; if(!y) return x; int t = __builtin_ctzll(x | y); x >>= __builtin_ctzll(x); do { y >>= __builtin_ctzll(y); if(x > y) swap(x, y); y -= x; } while(y); return x<<t; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) return x = 1, y = 0, a; ll d = exgcd(b, a % b, x, y); ll t = x; x = y; y = t - a / b * x; return d; } ll max(ll x, ll y) { return x > y ? x : y; } ll min(ll x, ll y) { return x < y ? x : y; } ll Mod(ll x, int mod) { return (x % mod + mod) % mod; } ll pow(ll x, ll y, ll mod){ ll res = 1, cur = x; while (y) { if (y & 1) res = res * cur % mod; cur = ONE * cur * cur % mod; y >>= 1; } return res % mod; } ll probabilityMod(ll x, ll y, ll mod) { return x * pow(y, mod-2, mod) % mod; } vvi getGraph(int n, int m, bool directed = false) { vvi res(n); rep(_, 0, m) { int u, v; cin >> u >> v; u--, v--; res[u].emplace_back(v); if(!directed) res[v].emplace_back(u); } return res; } vector<vpii> getWeightedGraph(int n, int m, bool directed = false) { vector<vpii> res(n); rep(_, 0, m) { int u, v, w; cin >> u >> v >> w; u--, v--; res[u].emplace_back(v, w); if(!directed) res[v].emplace_back(u, w); } return res; } const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const int N = 1e5 + 10; void solve() { int n; cin >> n; vector<array<int, 3>> a(2 * n); vector<array<int, 3>> b(2 * n); vector<ull> val(n); rep(i, 0, n) { val[i] = (ull) rng() << 31 | rng(); cin >> a[i][0] >> a[i+n][0]; a[i][2] = a[i+n][2] = i; a[i+n][1] = 1; cin >> b[i][0] >> b[i+n][0]; b[i][2] = b[i+n][2] = i; b[i+n][1] = 1; } sort(all(a)), sort(all(b)); ull x = 0; vector<ull> S(2 * n); rep(i, 0, 2 * n) { if (a[i][1]) x ^= val[a[i][2]]; else S[a[i][2]] ^= x; } x = 0; per(i, 2 * n - 1, -1) { if (!a[i][1]) x ^= val[a[i][2]]; else S[a[i][2]] ^= x; } x = 0; rep(i, 0, 2 * n) { if (b[i][1]) x ^= val[b[i][2]]; else S[b[i][2]] ^= x; } x = 0; per(i, 2 * n - 1, -1) { if (!b[i][1]) x ^= val[b[i][2]]; else S[b[i][2]] ^= x; } rep(i, 0, 2 * n) if (S[i]) { cout << "NO" << endl; return; } cout << "YES" << endl; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }
cpp
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
#include <bits/stdc++.h> using namespace std; #define read(type) readInt<type>() // Fast read #define ll long long #define nL "\n" #define pb push_back #define mk make_pair #define pii pair<int, int> #define vi vector<int> #define all(x) (x).begin(), (x).end() #define umap unordered_map #define uset unordered_set #define MOD 1000000007 ll maxk(ll value, ll k) { ll cnt = 0; while (value) { value = value / k; cnt++; } cnt--; return cnt; } ll power(ll value, ll k) { ll ans = 1; while (k--) { /* code */ ans = ans * value; } return ans; } void solve() { int n, k; cin >> n >> k; ll arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } map<ll, ll> m; for (int i = 0; i < n; i++) { while (arr[i] != 0) { /* code */ ll maxik = maxk(arr[i], k); // cout<<arr[i]<<" "<<maxik<<" "<<m[maxik]<<nL; if (m[maxik] > 0) { cout << "NO" << nL; return; } m[maxik]++; arr[i] = arr[i] - power(k, maxik); } } // cout << m[0]; cout << "YES" << nL; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int ttt; cin >> ttt; for (int i = 1; i <= ttt; i++) { solve(); } return 0; }
cpp
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define el "\n" #define matrix vector<vector<int>> #define pt complex<ld> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; const ll N = 1500, LOG = 20; const ld pi = acos(-1); const ll mod = 1e9 + 7; int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; ll n, m, k, x, y; int a[N]; int solve(vector<pair<int, int>> &v) { int cnt = 1; int idx; sort(v.begin(), v.end()); pair<int, int> p = {v[0].second, 1e9}; for (auto j: v) { if (p.second > j.second) { p = j; } } p = {p.second + 1, 0}; idx = upper_bound(v.begin(), v.end(), p) - v.begin(); while (idx < v.size()) { p = v[idx]; p = {p.second + 1, 0}; idx = upper_bound(v.begin(), v.end(), p) - v.begin(); cnt++; } return cnt; } void dowork() { map<int, vector<pair<int, int>>> mp; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } int sum; vector<pair<int, int>> ans; for (int i = 1; i <= n; i++) { sum = 0; for (int j = i; j > 0; j--) { sum += a[j]; if (mp[sum].size() == 0 || mp[sum].back().second < j) { mp[sum].push_back({j, i}); } if (mp[sum].size() > ans.size()) { ans = mp[sum]; } } } cout << ans.size() << el; for (auto j: ans) { cout << j.first << " " << j.second << el; } } int main() { fast //freopen("cowland.in", "r", stdin); //freopen("cowland.out", "w", stdout); int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { dowork(); } }
cpp
1322
D
D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4 4 3 1 2 1 1 2 1 2 1 1 2 3 4 5 6 7 8 9 OutputCopy6 InputCopy2 2 1 2 0 0 2 1 -100 -100 OutputCopy2 InputCopy5 4 4 3 2 1 1 0 2 6 7 4 12 12 12 6 -3 -5 3 10 -4 OutputCopy62 NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.
[ "bitmasks", "dp" ]
#include<bits/stdc++.h> using namespace std; typedef long long LL; template <typename T> inline void read(T &F) { int R = 1; F = 0; char CH = getchar(); for(; !isdigit(CH); CH = getchar()) if(CH == '-') R = -1; for(; isdigit(CH); CH = getchar()) F = F * 10 + CH - 48; F *= R; } inline void file(string str) { freopen((str + ".in").c_str(), "r", stdin); freopen((str + ".out").c_str(), "w", stdout); } const int N = 2e3 + 10; int f[N << 1][N], n, m, num[N], s[N], c[N << 1]; int main() { //file(""); read(n), read(m); for(int i = 1; i <= n; i++) read(num[i]); for(int i = 1; i <= n; i++) read(s[i]); for(int i = 1; i <= n + m; i++) read(c[i]); for(int i = 1; i <= n + m; i++) { f[i][0] = 0; for(int j = 1; j <= n; j++) f[i][j] = INT_MIN / 2; } for(int i = n; i >= 1; i--) { for(int j = n; j >= 1; j--) f[num[i]][j] = max(f[num[i]][j], f[num[i]][j - 1] - s[i] + c[num[i]]); int len = n; for(int j = num[i]; j < n + m; j++, len >>= 1) for(int k = 0; k <= len; k++) f[j + 1][k / 2] = max(f[j + 1][k / 2], f[j][k] + c[j + 1] * (k / 2)); } cout << f[n + m][0] << endl; #ifdef _MagicDuck fprintf(stderr, "# Time: %.3lf s", (double)clock() / CLOCKS_PER_SEC); #endif return 0; }
cpp
1303
F
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n×mn×m, initially filled with zeroes. We define ai,jai,j as the element in the ii-th row and the jj-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s1s1, s2s2, ..., sksk such that s1s1 is the first cell, sksk is the second cell, and for every i∈[1,k−1]i∈[1,k−1], sisi and si+1si+1 are connected.You are given qq queries of the form xixi yiyi cici (i∈[1,q]i∈[1,q]). For every such query, you have to do the following: replace the element ax,yax,y with cc; count the number of connected components in the matrix. There is one additional constraint: for every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.InputThe first line contains three integers nn, mm and qq (1≤n,m≤3001≤n,m≤300, 1≤q≤2⋅1061≤q≤2⋅106) — the number of rows, the number of columns and the number of queries, respectively.Then qq lines follow, each representing a query. The ii-th line contains three integers xixi, yiyi and cici (1≤xi≤n1≤xi≤n, 1≤yi≤m1≤yi≤m, 1≤ci≤max(1000,⌈2⋅106nm⌉)1≤ci≤max(1000,⌈2⋅106nm⌉)). For every i∈[1,q−1]i∈[1,q−1], ci≤ci+1ci≤ci+1.OutputPrint qq integers, the ii-th of them should be equal to the number of components in the matrix after the first ii queries are performed.ExampleInputCopy3 2 10 2 1 1 1 2 1 2 2 1 1 1 2 3 1 2 1 2 2 2 2 2 2 1 2 3 2 4 2 1 5 OutputCopy2 4 3 3 4 4 4 2 2 4
[ "dsu", "implementation" ]
#include<bits/stdc++.h> using namespace std; int n,m,q,fa[4000005],ma[305][305],id[305][305],idx,ans[2000005],cur; int get(int x){return x==fa[x]?x:fa[x]=get(fa[x]);} struct P{ int x,y,f,t; }p[2000005]; void merge(int x,int y){ x=get(x); y=get(y); if(x==y)return; fa[x]=y; cur--; } void solve(int x,int y){ if(ma[x][y]==ma[x-1][y])merge(id[x][y],id[x-1][y]); if(ma[x][y]==ma[x+1][y])merge(id[x][y],id[x+1][y]); if(ma[x][y]==ma[x][y-1])merge(id[x][y],id[x][y-1]); if(ma[x][y]==ma[x][y+1])merge(id[x][y],id[x][y+1]); } int main(){ int i,j; scanf("%d%d%d",&n,&m,&q); for(i=0;i<=m+1;i++)ma[0][i]=ma[n+1][i]=-1; for(i=1;i<=n;i++)ma[i][0]=ma[i][m+1]=-1; for(i=1;i<=q;i++){ scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].t); p[i].f=ma[p[i].x][p[i].y]; if(p[i].f!=p[i].t){ ma[p[i].x][p[i].y]=p[i].t; cur=1; id[p[i].x][p[i].y]=++idx; fa[idx]=idx; solve(p[i].x,p[i].y); ans[i]+=cur; } } idx=0; for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ id[i][j]=++idx; fa[idx]=idx; } } for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ solve(i,j); } } for(i=q;i>=1;i--){ if(p[i].f!=p[i].t){ ma[p[i].x][p[i].y]=p[i].f; cur=1; id[p[i].x][p[i].y]=++idx; fa[idx]=idx; solve(p[i].x,p[i].y); ans[i]-=cur; } } ans[0]=1; for(i=1;i<=q;i++){ ans[i]=ans[i-1]+ans[i]; printf("%d\n",ans[i]); } 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" ]
//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 void solve() { ll n, i, j, a[200005], m, l, k, r, fans=0, p, x, y, ans=1e10; int nbElem, pos, nbControl; cin >> nbElem >> pos >> nbControl; int before = pos-1, behind = nbElem-pos; nbControl = min(nbControl, before); for(i=1;i<=nbElem;i++) { cin>>a[i]; } for(i=0;i<=nbControl;i++) { ll ans = 1e10; for(j=0;j<=before - nbControl;j++) { ans = min(ans, max(a[i+j+1], a[i+j+behind+1])); // cout<<ans<<endl; } fans = max(ans, fans); } cout<<fans<<endl; } int main(){ ios_base::sync_with_stdio(0); cin.tie(nullptr); int t; cin>>t; while(t--) solve(); } //Iterate through maps: /*for(auto it: m) { ll x=it.first; ll y=it.second; }*/ // lower_bound() --> first element greater than or equal to... // upper_bound() --> first element strictly greater than... // UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s // UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s// UT for BS...s // Source: https://usaco.guide/general/io
cpp
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
[ "dfs and similar", "dp", "graphs", "trees" ]
#include <bits/stdc++.h> #define ll long long #define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); using namespace std; const int N = 2e5 + 10; const int inf = 0x3f3f3f3f; int head[N], nex[N << 1], to[N << 1], cnt=1; int dp[N],dp1[N],sum[N], a[N],d[N], n; //cnt:start from 1,no need to memset (-1) void add(int x, int y) { to[cnt] = y; nex[cnt] = head[x]; head[x] = cnt++; } void dfs1(int rt, int fa) { if(a[rt] == 0) { dp[rt] = -1;//设置dp数组的初值 sum[rt]=-1; } else { dp[rt] = 1; sum[rt]=1; } for(int i = head[rt]; i; i = nex[i]) { if(to[i] == fa) continue; dfs1(to[i], rt); dp[rt] = max(dp[rt], dp[rt] + dp[to[i]]);//两种选择,与其子树连接或者不连接。 sum[rt]=max(sum[rt],sum[rt]+sum[to[i]]); } } void dfs2(int rt, int fa) { for(int i = head[rt]; i; i = nex[i]) { if(to[i] == fa) continue; dp[to[i]] = max(dp[to[i]], dp[to[i]] + dp[rt] - max(dp[to[i]], 0)); int v=to[i]; if(d[v]==1){ //leaf point if(sum[v]==-1) dp1[v]=max(sum[v],sum[v]+dp1[rt]); else dp1[v]=max(sum[v],dp1[rt]); } else { dp1[v]=sum[v]+max(dp1[rt]-max(sum[v],0),0); //if(v==6){ // cout<<"!"<<dp1[rt]-max(sum[v],0); // cout<<"!"<<sum[v]+dp1[rt]-max(sum[v],0); //} } //这个的de[rt] - max(dp[to[i]], 0),表示的意思是:如果这个节点在上一躺的dfs中选择了这个儿子节点那么这个点一定是正数,如果这个点是负数,那么他在上一躺就没有被选择到,所以我们不需要减去这个点的值。 dfs2(to[i], rt); } } int main() { cin>>n; int x,y; for(int i = 1; i <= n; i++) cin>>a[i]; for(int i = 1; i < n; i++) { cin>>x>>y; add(x, y); add(y, x); d[y]++; d[x]++; } dfs1(1, -1); dp1[1]=sum[1]; dfs2(1, -1); //cout<<"dp: sum dp1[]"<<endl; for(int i = 1; i <= n; i++){ //cout<<i<<":"<<dp[i]<<" "<<sum[i]<<" "<<dp1[i]<<endl; cout<<dp1[i]<<" "; } return 0; }
cpp
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
#include <bits/stdc++.h> using namespace std; #define all(c) c.begin(),c.end() #define sz(x) int(x.size()) #define ar array typedef long long ll; typedef vector<int> vi; const ll mod=1000000007; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll exp(ll x,ll y){ x%=mod; ll res=1; while(y){ if(y&1) res=res*x%mod; x=x*x%mod, y>>=1; } return res; } ll fact(ll n){ ll res=1; for(ll i=2;i<=n;++i) (res*=i)%=mod; return res; } bool isprime(ll n){ if(n<=1) return 0; for(ll i=2;i*i<=n;++i) if(n%i==0) return 0; return 1; } int main(){ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ios::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ int n; cin>>n; vector<ar<int,2>> v(n); vector<int> b; for(int i=0;i<n;++i){ for(int j=0;j<2;++j){ cin>>v[i][j]; b.push_back(v[i][j]); v[i][j]*=2; b.push_back(v[i][j]); b.push_back(v[i][j]+j); } } sort(all(b)); b.resize(unique(all(b))-b.begin()); for(auto &i:v) for(int j=0;j<2;++j) i[j]=lower_bound(all(b),i[j])-b.begin(); vector<int> pre(5*n),p(5*n); for(auto i:v){ ++pre[i[0]]; if(i[1]+1<5*n) --pre[i[1]+1]; } for(int i=1;i<5*n;++i) pre[i]+=pre[i-1]; int a=0,mx=0; for(int i=1;i<5*n;++i) a+=!pre[i]&&pre[i-1]; for(int i=1;i<5*n;++i) p[i]=p[i-1]+(pre[i]==1&&pre[i-1]>1); for(auto i:v){ int c=i[1]+1<5*n?!pre[i[1]+1]&&pre[i[1]]==1:0; mx=max(mx,a+p[i[1]]-(i[0]?p[i[0]-1]:0)-c); } cout<<mx<<'\n'; } return 0; }
cpp
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
/* _/ _/ _/_/_/ _/ _/ _/ _/_/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/_/ _/ _/_/_/_/_/ _/_/_/_/_/ */ #include <bits/stdc++.h> #define ll long long #define lc(x) ((x) << 1) #define rc(x) ((x) << 1 | 1) #define ru(i, l, r) for (int i = (l); i <= (r); i++) #define rd(i, r, l) for (int i = (r); i >= (l); i--) #define mid ((l + r) >> 1) #define pii pair<int, int> #define mp make_pair #define fi first #define se second #define sz(s) (int)s.size() #define maxn 100005 using namespace std; inline int read() { int x = 0, w = 0; char ch = getchar(); while(!isdigit(ch)) {w |= ch == '-'; ch = getchar();} while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();} return w ? -x : x; } int n, a[maxn], pre[maxn], suf[maxn]; int main() { n = read(); ru(i, 1, n) a[i] = read(); ru(i, 1, n) pre[i] = pre[i - 1] | a[i]; rd(i, n, 1) suf[i] = suf[i + 1] | a[i]; int ans = -1, mx = 0; ru(i, 1, n) { int t = pre[n] - (pre[i - 1] | suf[i + 1]); if(ans < t) { ans = t; mx = i; } } printf("%d ", a[mx]); ru(i, 1, n) if(mx != i) printf("%d ", a[i]); 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> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> // #include <atcoder/all> // using namespace atcoder; using namespace __gnu_pbds; using namespace std; using uns = unsigned; using ll = long long; using ld = long double; using vb = std::vector<bool>; using vvb = std::vector<vb>; using vc = std::vector<char>; using vvc = std::vector<vc>; using vi = std::vector<int>; using vvi = std::vector<vi>; using vvvi = std::vector<vvi>; using vll = std::vector<ll>; using vvll = std::vector<vll>; using vvvll = std::vector<vvll>; using vld = std::vector<ld>; using vvld = std::vector<vld>; using vvvld = std::vector<vvld>; using pll = std::pair<ll, ll>; using vpll = std::vector<pll>; using pii = std::pair<int, int>; using vpii = std::vector<pii>; using vu = std::vector<uns>; using vs = std::vector<std::string>; using ordered_set = tree<pll, null_type, std::less<pll>, rb_tree_tag, tree_order_statistics_node_update>; #define siz(x) (ll) x.size() #define all(v) (v).begin(), (v).end() #ifdef DEBUG #include "dbg.hpp" #else #define err(...) #define deb(...) #endif const ll mod = 1e9+7; //using mint = modint998244353; const ll maxN = 1e5+5; void run_brute(){ //cout<<"\n................\n"; } template<class T> inline T POW(T a,ll n){ T r=1; for (; n>0; n>>=1,a*=a){ if (n&1)r*=a; } return r; } inline ll POW(int a,ll n){ return POW((ll)a,n); } template<class T> vector<T> powers(T m,ll n){ vector<T> ret(n+1,1); for (ll i=1;i<=n;++i) ret[i]=ret[i-1]*m; return ret; } struct modint { int n; modint() :n(0) { ; } modint(ll m) { if (m < 0 || mod <= m) { m %= mod; if (m < 0)m += mod; } n = m; } operator int() { return n; } }; bool operator==(modint a, modint b) { return a.n == b.n; } bool operator<(modint a, modint b) { return a.n < b.n; } modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= (int)mod; return a; } modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += (int)mod; return a; } modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; } modint operator+(modint a, modint b) { return a += b; } modint operator-(modint a, modint b) { return a -= b; } modint operator*(modint a, modint b) { return a *= b; } modint operator^(modint a, ll n) { if (n == 0)return modint(1); modint res = (a * a) ^ (n / 2); if (n % 2)res = res * a; return res; } ll inv(ll a, ll p) { return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p); } modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); } modint operator/=(modint& a, modint b) { a = a / b; return a; } const int max_n = 1 << 20; modint fact[max_n], factinv[max_n]; void init_f() { fact[0] = modint(1); for (int i = 0; i < max_n - 1; i++) { fact[i + 1] = fact[i] * modint(i + 1); } factinv[max_n - 1] = modint(1) / fact[max_n - 1]; for (int i = max_n - 2; i >= 0; i--) { factinv[i] = factinv[i + 1] * modint(i + 1); } } modint ncr(int a, int b) { if (a < 0 || b < 0 || a < b)return 0; return fact[a] * factinv[b] * factinv[a - b]; } modint npr(int a, int b) { if (a < 0 || b < 0 || a < b)return 0; return fact[a] * factinv[a - b]; } void solve() { ll n,m; cin>>n>>m; // cnt1+cnt2+..cntn = 2*m // 2*m stars, n-1bars // ncr(n+2*m-1,n-1) or ncr(n+2*m-1,2m) cout<<ncr(n+2*m-1,2*m)<<"\n"; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif std::ios_base::sync_with_stdio(false), std::cin.tie(nullptr); int t = 1; //cout << fixed << setprecision(20); //cin >> t; init_f(); for (int i = 1; i <= t; i++) { // cout << "Case #" << i << ": "; solve(); // run_brute(); } return 0; }
cpp
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; #define int long long int a[N], s[N]; void solve() { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; s[i] = s[i - 1] + a[i]; } int ans = -1e18, minm = 0; for (int i = 1; i <= n; i++) { if (i == n) { ans = max(ans, a[i]); for (int j = 1; j < n; j++) ans = max(ans, s[i] - s[j]); } else ans = max(ans, s[i] - minm); minm = min(minm, s[i]); } // cout << ans << endl; if (ans >= s[n]) cout << "NO" << endl; else cout << "YES" << endl; } signed main() { int t; cin >> t; while (t--) solve(); }
cpp
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vl; typedef pair<int, int>pi; typedef pair<ll, ll>pl; typedef vector<pi>vpi; typedef vector<pl>vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef vector<string> vs; typedef vector<bool> vb; const long double PI = acos(-1); const int oo = 1e9 + 7; const int MOD = 1e9 + 7; const int N = 2e5 + 7; #define endl '\n' #define all(v) (v).begin(),(v).end() #define rall(v) (v).rbegin(),(v).rend() #define read(v) for (auto& it : v) scanf("%d", &it); #define readL(v) for (auto& it : v) scanf("%lld", &it); #define print(v) for (auto it : v) printf("%d ", it); puts(""); #define printL(v) for (auto it : v) printf("%lld ", it); puts(""); void solve() { int q, x, mex = 0; scanf("%d %d", &q, &x); vi v(x); for (int i = 0; i < x; i++) v[i] = i; map<int, bool>vis; while (q--) { int n; scanf("%d", &n); int mo = n % x; vis[v[mo]] = true, v[mo] += x; while (vis[mex]) mex++; printf("%d\n", mex); } } int t = 1; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif //scanf("%d", &t); while (t--) solve(); }
cpp
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
#include <bits/stdc++.h> #define itn long long #define int long long #define double long double //#define endl '\n' #define p_b push_back #define fi first #define se second #define pii std::pair<int, int> #define oo LLONG_MAX #define big INT_MAX #define elif else if using namespace std; int input() { int x; cin>>x; return x; } void solve() { int n; cin>>n; string s; cin>>s; cout<<n+1; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); // freopen("network.in", "r", stdin); // freopen("magic.txt", "w", stdout); int t=1; // cin>>t; while(t--) { solve(); cout<<endl<<endl; } }
cpp
1284
G
G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1). For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1) For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4 2 2 OO OO 3 3 OOO XOO OOO 4 4 OOOX XOOX OOXO OOOO 5 6 OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OutputCopyYES OOO O OOO NO YES OOOOO X O O X O O X O OOO X O O O O O OOOOO YES OOOOOOOOOOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO
[ "graphs" ]
#include<iostream> #include<cstdio> #include<algorithm> #include<set> #include<vector> #include<ctime> #include<cstring> #include<map> #include<cmath> #include<queue> #define mp make_pair #define PII pair<int,int> #define fi first #define se second #define pb push_back using namespace std; inline int read(){ int x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-')f=-1;c=getchar();} while(isdigit(c)){x=(x<<3)+(x<<1)+(c^48);c=getchar();} return f==-1?~x+1:x; } int T; int n,m; char str[21][21]; int tot; int head[610],nxt[200010],to[200010],w[200010]; int depth[610],gap[610]; int stk[610],top; vector<int>vec[610],st[610]; int dfn[610],low[610],idx; bool vis[610]; int fa[610]; int ccnt; int belong[610]; int siz[610]; void tarjan(int x){ dfn[x]=++idx,low[x]=idx;stk[++top]=x;vis[x]=1; for(int v:vec[x]){ if(!dfn[v]){ tarjan(v); low[x]=min(low[x],low[v]); } else if(vis[x]) low[x]=min(low[x],dfn[v]); } if(dfn[x]==low[x]){ ++ccnt;siz[ccnt]=0;vector<int>().swap(st[ccnt]); while(stk[top]!=x){ vis[stk[top]]=0; st[ccnt].pb(stk[top]); belong[stk[top]]=ccnt;--top;++siz[ccnt]; }siz[ccnt]++;st[ccnt].pb(x); --top;belong[x]=ccnt;vis[x]=0; } } int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; int s,t; bool gt[610]; void add(int x,int y,int z){ // printf("x:%d,y:%d,z:%d\n",x,y,z); nxt[++tot]=head[x],head[x]=tot,to[tot]=y,w[tot]=z; nxt[++tot]=head[y],head[y]=tot,to[tot]=x,w[tot]=0; } int getid(int x,int y){ if(x==1&&y==0) return n*m+1; if(x==0&&y==1) return n*m+2; if(x<1||x>n||y<1||y>m) return 0; return (x-1)*m+y; } PII getpos(int x){ if(x>n*m) return (x==n*m+1?(mp(1,0)):(mp(0,1))); else return mp((x-1)/m+1,(x-1)%m+1); } int id[21][21][4]; int tmp[610]; bool Bfs(int s,int t){ memset(depth,0,sizeof(depth)); memset(gap,0,sizeof(gap)); queue<int>q; while(!q.empty()) q.pop(); q.push(t); depth[t]=1; gap[1]++; while(!q.empty()){ int u=q.front(); q.pop(); for(int i=head[u];i;i=nxt[i]){ int v=to[i]; if(depth[v]==0){ depth[v]=depth[u]+1; gap[depth[v]]++; q.push(v); } } } if(depth[s]==0) return 0; return 1; } int dfs(int x,int maxf){ if(x==t) return maxf; int sum=0; for(int &i=tmp[x];i;i=nxt[i]){ int v=to[i]; if(depth[v]+1==depth[x]){ int di=dfs(v,min(maxf,w[i])); w[i]-=di; w[i^1]+=di; maxf-=di; sum+=di; if(maxf==0) return sum; } } if(--gap[depth[x]]==0) depth[s]=t+2; ++gap[++depth[x]];tmp[x]=head[x]; return sum; } inline int ISAP(int s,int t){ int maxflow=0; if(Bfs(s,t)==0) return 0; for(int i=0;i<=t;++i) tmp[i]=head[i]; while(depth[s]<=t+1) { maxflow+=dfs(s,0x3f3f3f3f); } return maxflow; } char ans[51][51]; void resetans(){ memset(ans,0,sizeof(ans)); for(int i=1;i<=n;++i){ for(int j=1;j<=m;++j){ ans[i<<1|1][j<<1|1]=str[i][j]; } } } int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]); } void mer(int x,int y){ // printf("x:%d,y:%d\n",x,y); fa[find(x)]=find(y); PII poa=getpos(x),pob=getpos(y); // printf("%d %d,%d %d\n",poa.fi,poa.se,pob.fi,pob.se); ans[(poa.fi<<1|1)+(pob.fi<<1|1)>>1][(poa.se<<1|1)+(pob.se<<1|1)>>1]='O'; } vector<int>rev[610]; void bfs(int x){ queue<int>Q; Q.push(x);memset(vis,0,sizeof(vis));vis[x]=1; while(!Q.empty()){ int u=Q.front();Q.pop(); for(int v:rev[u]){ if(find(u)!=find(v)) mer(u,v); if(!vis[v]) Q.push(v),vis[v]=1; } } } int main(){ T=read(); while(T--){ n=read(),m=read(); memset(head,0,sizeof(head));tot=1; for(int i=1;i<=n*m+5;++i)vector<int>().swap(vec[i]),vector<int>().swap(rev[i]); for(int i=1;i<=n;++i) scanf("%s",str[i]+1); str[0][1]=str[1][0]='O'; memset(id,0,sizeof(id)); for(int i=1;i<=n;++i){ for(int j=1;j<=m;++j) if(str[i][j]=='O'&& !((i+j)&1)){ for(int k=0;k<4;++k){ int vx=i+dx[k],vy=j+dy[k]; if(vx<0||vx>n||vy<0||vy>m) continue ; if(str[vx][vy]=='O') id[i][j][k]=tot+1,add(getid(i,j),getid(vx,vy),1); } } } int cnt=0; s=0,t=n*m+5; for(int i=0;i<=n;++i){ for(int j=0;j<=m;++j) if(str[i][j]=='O'){ if((i+j)&1) add(getid(i,j),t,1); else add(s,getid(i,j),1),++cnt; } } int f=ISAP(s,t); // printf("f:%d\n",f); if(f!=cnt){ puts("NO");continue ; } for(int i=0;i<=n*m+2;++i) fa[i]=i; resetans(); for(int i=0;i<=n;++i){ for(int j=0;j<=m;++j) if(str[i][j]=='O'&&!((i+j)&1)){ for(int k=0;k<4;++k){ if(id[i][j][k]){ int vx=i+dx[k],vy=j+dy[k]; if(!w[id[i][j][k]]) vec[getid(vx,vy)].pb(getid(i,j)),rev[getid(i,j)].pb(getid(vx,vy)),mer(getid(vx,vy),getid(i,j)); vec[getid(i,j)].pb(getid(vx,vy)); rev[getid(vx,vy)].pb(getid(i,j)); } } } } bool fl=0; memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));top=0; memset(vis,0,sizeof(vis));ccnt=0; for(int i=0;i<=n;++i){ for(int j=0;j<=m;++j) if(str[i][j]=='O'){ if(!dfn[getid(i,j)]){ // printf("tarjan:%d\n",getid(i,j)); tarjan(getid(i,j)); } } } for(int i=1;i<=ccnt;++i){ gt[i]=(siz[i]==1); for(int j:st[i]){ for(int v:vec[j]) gt[i]|=gt[belong[v]]; } if(!gt[i]) fl=1; } if(fl){ puts("NO");continue ; } printf("YES\n"); for(int i=1;i<=ccnt;++i){ if(siz[i]==1){ // printf("bfs:%d\n",st[i][0]); bfs(st[i][0]); } } for(int i=3;i<=(n<<1|1);++i){ for(int j=3;j<=(m<<1|1);++j){ if(ans[i][j]) printf("%c",ans[i][j]);else printf(" "); } printf("\n"); } } }
cpp
1284
E
E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5 -1 0 1 0 -10 -1 10 -1 0 3 OutputCopy2InputCopy8 0 1 1 2 2 2 1 3 0 -1 -1 -2 -2 -2 -1 -3 OutputCopy40InputCopy10 588634631 265299215 -257682751 342279997 527377039 82412729 145077145 702473706 276067232 912883502 822614418 -514698233 280281434 -41461635 65985059 -827653144 188538640 592896147 -857422304 -529223472 OutputCopy213
[ "combinatorics", "geometry", "math", "sortings" ]
// LUOGU_RID: 94202220 #include<cstdio> #include<cstring> #include<vector> #include<cmath> #include<algorithm> #define int long long #define F(i,l,r) for(int i=(l),i##end=(r);i<=i##end;++i) using namespace std; const int N=2505;const long double pi=acos(-1.0L); int n,ans,dp[N],s[N];long double x[N],y[N]; template<typename T>inline void readmain(T &n){T sum=0,x=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-')x=-1;ch=getchar();}while (ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}n=sum*x;} template<typename T>inline T& read(T &x){readmain(x);return x;} template<typename T,typename ...Tr>inline void read(T &x,Tr&... r){readmain(x);read(r...);} template<typename T>inline void write(T x){if (x<0){putchar('-');x=-x;}if (x>9)write(x/10);putchar(x%10+'0');return;} template<typename T>inline void writesc(T x){write(x);putchar(' ');} template<typename T>inline void writeln(T x){write(x);putchar('\n');} main() { F(i,0,read(n)-1)read(x[i],y[i]); F(i,0,n-1) { vector<long double>v; F(j,0,n-1)if (j!=i)v.push_back(atan2(y[j]-y[i],x[j]-x[i])); int k=0; sort(v.begin(),v.end());F(j,0,n-1) { while (k<n-1&&v[k]<v[j]+pi)++k; dp[j]=k;s[j]=(j?s[j-1]:0)+dp[j]; } F(j,0,n-1)ans+=(s[dp[j]-1]-s[j])-(dp[j])*(dp[j]-j-1); } write(ans*(n-4)/2); 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" ]
#include "bits/stdc++.h" using namespace std; #define ll long long string query(int l, int r) { cout << "? " << l << " " << r << "\n"; cout.flush(); int n = r - l + 1; vector<vector<int>> a(n + 1, vector<int>(26)); for (int i = 0; i < (n * (n + 1)) / 2; i++) { string curr; cin >> curr; for (char c : curr) { a[curr.size()][c - 'a']++; } } string cv(n, '?'); if (n == 2) { int ind = 0; for (int i = 0; i < a[n].size(); i++) { while (a[n][i]) { cv[ind++] = 'a' + i; a[n][i]--; } } return cv; } vector<pair<char,int>> sf; for (int i = 0; i < n - i - 1; i++) { int cc = i + 2; for (auto [c, x] : sf) { a[cc][c - 'a'] += (cc - x - 1); } for (int j = 0; j < a[cc].size(); j++) { if (a[cc][j] < a[n][j] * cc) { if (cv[i] == '?') cv[i] = 'a' + j; else cv[n - i - 1] = 'a' + j; sf.push_back({'a' + j, i}); a[cc][j]++; j--; } } } if (n % 2) { for (auto [c, x] : sf) { a[n][c - 'a']--; } for (int i = 0; i < a[n].size(); i++) { if (a[n][i]) { cv[n / 2] = 'a' + i; break; } } assert(cv[n / 2] != '?'); } return cv; } char diff(string a, string b) { vector<int> fr(26); for (char c : a) fr[c - 'a']++; for (char c : b) fr[c - 'a']--; for (int i = 0; i < fr.size(); i++) { if (fr[i] != 0) { return 'a' + i; } } return 0; } char other(char x, char y, char z) { if (y == x) return z; return y; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; if (n <= 3) { string ans = ""; for (int i = 1; i <= n; i++) { ans += query(i, i); } cout << "! " << ans << "\n"; cout.flush(); return 0; } int fs = (n + 1) / 2; string fp = query(1, fs); string sp = query(2, fs); string av = query(1, n); string ans(n, '?'); ans[0] = diff(fp, sp); int l = 1, r = fs - 1; while (l <= r) { ans[r] = other(ans[l - 1], fp[r], fp[fs - r - 1]); int ind = r - 1; ans[l] = other(ans[r], sp[ind], sp[fs - ind - 2]); l++; r--; } for (int i = 0; i < n; i++) { int oi = (n - i - 1); if (i >= oi) break; ans[oi] = other(ans[i], av[i], av[oi]); } cout << "! " << ans << "\n"; } // ~ BucketPotato
cpp
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define mod 1000000007 #define ll long long int #define endl '\n' #define mem(a,x) memset(a,x,sizeof(a)) #define EPS 1e-12 #define double long double using namespace std; using namespace __gnu_pbds; typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds; //cout << "0th element: " << *A.find_by_order(0) << endl; //cout << "No. of elems smaller than 6: " << A.order_of_key(6) << endl; //priority_queue <int, vector<int>, greater<int>> ll pow1(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod;}else{b--;ans=(ans*a)%mod;}}return ans;} ll mod1=1e9+9; ll pow2(ll a,ll b){ll ans=1; while(b>0){if(b%2==0){b=b/2;a=(a*a)%mod1;}else{b--;ans=(ans*a)%mod1;}}return ans;} ll lcm(ll a,ll b) { return (a*b)/__gcd(a,b); } const int N=5e5+5; int sp1[N][22],sp2[N][22],val1[N],val2[N],ar[N],br[N],cr[N],dr[N]; void sparse1(int n) { int i,j; for(i=0;i<n;i++) { sp1[i][0]=val1[i+1]; } for(j=1;(1<<j)<=n;j++) { for(i=0;i<=n-(1<<j);i++) { sp1[i][j]=max(sp1[i][j-1],sp1[i+(1<<(j-1))][j-1]); } } } void sparse2(int n) { int i,j; for(i=0;i<n;i++) { sp2[i][0]=val2[i+1]; } for(j=1;(1<<j)<=n;j++) { for(i=0;i<=n-(1<<j);i++) { sp2[i][j]=max(sp2[i][j-1],sp2[i+(1<<(j-1))][j-1]); } } } ll check1(ll a,ll b) { ll c=(b-a)+1; c=(int)log2(c); return max(sp1[a][c],sp1[b-(1<<c)+1][c]); } ll check2(ll a,ll b) { ll c=(b-a)+1; c=(int)log2(c); return max(sp2[a][c],sp2[b-(1<<c)+1][c]); } void solve() { int n,i,a,b,c,d,e,j; cin>>n; map<int,int>mp; for(i=1;i<=n;i++) { cin>>ar[i]>>br[i]>>cr[i]>>dr[i]; mp[ar[i]]=1; mp[br[i]]=1; mp[cr[i]]=1; mp[dr[i]]=1; } a=1; for(auto it=mp.begin();it!=mp.end();it++) { (*it).second=a++; } for(i=1;i<=n;i++) { ar[i]=mp[ar[i]]; br[i]=mp[br[i]]; cr[i]=mp[cr[i]]; dr[i]=mp[dr[i]]; val1[ar[i]]=max(val1[ar[i]],cr[i]); val1[br[i]]=max(val1[br[i]],cr[i]); val2[cr[i]]=max(val2[cr[i]],ar[i]); val2[dr[i]]=max(val2[dr[i]],ar[i]); } sparse1(a); sparse2(a); for(i=1;i<=n;i++) { a=ar[i],b=br[i]; if(check1(a-1,b-1)>dr[i]) { cout<<"NO"<<endl; return; } a=cr[i],b=dr[i]; if(check2(a-1,b-1)>br[i]) { cout<<"NO"<<endl; return; } } cout<<"YES"<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; t=1; int cs=1; //cin>>t; while (t--) { //cout<<"Case "<<cs<<": "; solve(); cs++; } }
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
#include <bits/stdc++.h> // v.erase( unique(all(v)) , v.end() ) -----> removes duplicates and resizes the vector as so using namespace std; #define ll long long #define lld long double const lld pi = 3.14159265358979323846; #define pb push_back #define pf push_front #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());} constexpr int mod = (int)(1e9+7); #define log(x) (31^__builtin_clz(x)) // Easily calculate log2 on GNU G++ compilers #define left p<<1 , l , (l+r)>>1 #define right p<<1|1 , ((l+r)>>1)+1 , r const int N=4e4+7; const int M=53; int seg[M][4*N],lazy[M][4*N]; void push(int t,int p){ if(!lazy[t][p]) return; seg[t][p<<1] += lazy[t][p]; seg[t][p<<1|1] += lazy[t][p]; lazy[t][p<<1] += lazy[t][p]; lazy[t][p<<1|1] +=lazy[t][p]; lazy[t][p] = 0; } void upd(int t,int i , int j , int inc , int p , int l , int r){ if(j<l || r<i) return; if(i<=l && r<=j){ lazy[t][p] += inc; seg[t][p] += inc; return; } push(t,p); upd(t,i,j,inc,left); upd(t,i,j,inc,right); seg[t][p]=max(seg[t][p<<1],seg[t][p<<1|1]); } int a[M][N]; int main() {ios_base::sync_with_stdio(0),cin.tie(0); int n,m;cin>>n>>m;int k;cin>>k; for(int i=0;i<n;i++){ for(int j=1;j<=m;j++){ cin>>a[i][j];a[i][j]+=a[i][j-1]; } } if(n==1){ int ans=0; for(int i=k;i<=m;i++)ans=max(ans,a[0][i]-a[0][i-k]); cout<<ans<<'\n';return 0; } for(int i=1;i<=m;i++){ int sum=a[1][i]-a[1][max(i-k,0)]+a[0][i]-a[0][max(i-k,0)]; upd(1,i,i,sum,1,1,2*m); } for(int c=2;c<=n;c++){ for(int i=1;i<=m;i++){ int sum=a[c][i]-a[c][max(i-k,0)]+a[c-1][i]-a[c-1][max(i-k,0)]; int minus=a[c-1][i]-a[c-1][i-1]; upd(c-1,i,i+k-1,-minus,1,1,2*m); upd(c,i,i,sum+seg[c-1][1],1,1,2*m); if(i>=k)upd(c-1,i-k+1,i,(a[c-1][i-k+1]-a[c-1][i-k]),1,1,2*m); } } cout<<seg[n][1]<<'\n'; return 0; } /* */
cpp
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
#include<bits/stdc++.h> #define ll long long #define endl "\n" #define fast ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); using namespace std; ll q,n,x,d,y,z,r; int main() { fast cin>>q; while(q--) { cin>>n>>d; if(n>=d) { cout<<"YES"<<endl; } else { ll mi=1e13; x=ceil(sqrt(d)); while(x>0) { ll ans=x+ceil(((double )d)/(x+1)); mi=min(mi,ans); x--; } if(mi<=n) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } } return 0; }
cpp
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = tuple<ll, ll>; using vi =vector<ll>; using vii = vector<ii>; using vvi = vector<vi>; using qi = queue<int>; int n; vi x; vvi y; void f() { y.push_back(vi(n)); for (int i=0; i < n; i++) y[0][i] = x[i]; for (int i=1, k=2; k <= n; i++, k *= 2) { y.push_back(vi(n - k + 1)); for (int j = 0; j <= n - k; j++) y[i][j] = max(y[i-1][j], y[i-1][j + k/2]); } } int mx(int a, int b) { if (a>b) return -1; int d=b-a+1; int i=0, k=1; for (; k*2 <= d; i++, k *= 2); return max(y[i][a], y[i][b-k+1]); } int main() { cin.tie(0), ios::sync_with_stdio(0); ll m, k, u, v; cin >> n >> m >> k; vi c(k); for (int i = 0; i < k; i++) cin >> u, u--, c[i] = u; vvi g(n); for (int i = 0; i < m; i++) { cin >> u >> v; u--, v--; g[u].push_back(v); g[v].push_back(u); } vi a(n), s(n); a[0]=0, s[0]=1; qi q; q.push(0); while (!q.empty()) { u = q.front(); q.pop(); for (int v : g[u]) { if (s[v]) continue; s[v] = 1; a[v] = a[u]+1; q.push(v); } } vi b(n); s=vi(n); b[n-1] = 0, s[n-1] = 1; q.push(n-1); while (!q.empty()) { u = q.front(); q.pop(); for (int v : g[u]) { if (s[v]) continue; s[v] = 1; b[v] = b[u]+1; q.push(v); } } x = vi(n, -1); for (int i=0; i<k; i++) x[a[c[i]]] = max(x[a[c[i]]], b[c[i]]); f(); vi d(k); for (int i = 0; i < k; i++) d[i] = a[c[i]]; sort(d.begin(), d.end()); for (int i = 0; i < k-1; i++) if (d[i] == d[i+1]) { cout << a[n-1] << '\n'; return 0; } ll M = 0; for (int i = 0; i < k; i++) { ll x = mx(d[i]+1,n-1); if (x >= 0) M = max(M, d[i]+x+1); } cout << min(M, a[n-1]) << '\n'; }
cpp
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
#include<iostream> #include<cstring> #include<vector> #include<map> #include<queue> #include<unordered_map> #include<cmath> #include<cstdio> #include<algorithm> #include<set> #include<cstdlib> #include<stack> #include<ctime> #define forin(i,a,n) for(int i=a;i<=n;i++) #define forni(i,n,a) for(int i=n;i>=a;i--) #define fi first #define se second using namespace std; typedef long long ll; typedef double db; typedef pair<int,int> PII; const double eps=1e-7; const int N=2e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[N]; int ans; void solve() { n=read(); int a=read(),b=read(); if(a>=b) printf("%d\n",n); else { ll ans=0; int c=n/(2*a); ans+=(ll)c*(a+b); int p=n%(2*a); ll x=(ll)(b-a)*c; if(p==0) ans-=min((ll)b,x); else { int q=p/2; ans+=p; ans-=min(x,(ll)q); } printf("%lld\n",ans); } } int main() { // init(); // stin(); scanf("%d",&T); // T=1; while(T--) solve(); return 0; }
cpp
1295
A
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2 3 4 OutputCopy7 11
[ "greedy" ]
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int, int> pi; #define ll long long #define pb push_back #define lb(s,x) lower_bound(s.begin(),s.end(),x) #define ub(s,x) upper_bound(s.begin(),s.end(),x) #define asort(p) sort(p.begin(),p.end()) #define dsort(p) sort(p.begin(),p.end(),greater<int>()) #define count(s,x) count(s.begin(),s.end(),x) //ceil function returns least greater or equal value //floor fucntion returns smaller or equal value to the number //upper case aplhabet-(65-90) //lower case aplhabet-(97-122) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@___**___@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void killer() { ll int n; cin>>n; if(n%2==0) { for(ll int i=0;i<n/2;i++) cout<<"1"; } else {cout<<"7"; for(ll int i=0;i<(n/2)-1;i++) { cout<<"1"; } } cout<<endl; } int main() { ll int t; cin>>t; while(t--) { killer(); } }
cpp
1305
H
H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor; Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of nn questions, and mm students have taken the exam. Each question was worth 11 point. Question ii was solved by at least lili and at most riri students. Additionally, you know that the total score of all students is tt.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 11 to mm, where rank 11 has the highest score and rank mm has the lowest score. Ties were broken arbitrarily.You know that the student at rank pipi had a score of sisi for 1≤i≤q1≤i≤q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students.InputThe first line of input contains two integers (1≤n,m≤1051≤n,m≤105), denoting the number of questions of the exam and the number of students respectively.The next nn lines contain two integers each, with the ii-th line containing lili and riri (0≤li≤ri≤m0≤li≤ri≤m).The next line contains a single integer qq (0≤q≤m0≤q≤m). The next qq lines contain two integers each, denoting pipi and sisi (1≤pi≤m1≤pi≤m, 0≤si≤n0≤si≤n). It is guaranteed that all pipi are distinct and if pi≤pjpi≤pj, then si≥sjsi≥sj.The last line contains a single integer tt (0≤t≤nm0≤t≤nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 11, and the maximum possible score for rank 11 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output −1−1 −1−1.ExamplesInputCopy5 4 2 4 2 3 1 1 0 1 0 0 1 4 1 7 OutputCopy3 2 InputCopy5 6 0 6 0 6 2 5 6 6 4 6 1 3 3 30 OutputCopy-1 -1 NoteFor the first sample; here is one possible arrangement that fits the data:Students 11 and 22 both solved problems 11 and 22.Student 33 solved problems 22 and 33.Student 44 solved problem 44.The total score of all students is T=7T=7. Note that the scores of the students are 22, 22, 22 and 11 respectively, which satisfies the condition that the student at rank 44 gets exactly 11 point. Finally, 33 students tied for first with a maximum score of 22, and it can be proven that we cannot do better with any other arrangement.
[ "binary search", "greedy" ]
#include<bits/stdc++.h> using namespace std; using ll = long long; template <typename T> void setmin(T& a, const T& b) { if (b < a) a = b; } template <typename T> void setmax(T& a, const T& b) { if (b > a) a = b; } optional<vector<int>> getOptimal(vector<pair<int, int>> ranges, int M, ll T) { int N = int(ranges.size()); //sort(ranges.begin(), ranges.end()); vector<int> ans; ans.reserve(N); ll curT = T; for (auto it : ranges) curT -= it.first; if (curT < 0) return nullopt; int idx = 0; priority_queue<int, vector<int>, greater<int>> upperBounds; int curVal = 0; while (int(ans.size()) < N) { assert(curT >= 0); int nxtVal = M+1; if (!upperBounds.empty()) { setmin(nxtVal, upperBounds.top()); } if (idx < N) { setmin(nxtVal, ranges[idx].first); } assert(nxtVal <= M); assert(nxtVal >= curVal); if (int(upperBounds.size()) * ll(nxtVal - curVal) > curT) { // can't make it there nxtVal = int(curVal + curT / (int(upperBounds.size()))); } curT -= int(upperBounds.size()) * ll(nxtVal - curVal); curVal = nxtVal; if (idx < N && ranges[idx].first == curVal) { upperBounds.push(ranges[idx].second); idx++; } else { assert(!upperBounds.empty()); // make progress by removing this guy ans.push_back(curVal); upperBounds.pop(); } } //for (auto v : ans) { cerr << v << ' '; } cerr << '\n'; if (curT > 0) return nullopt; return ans; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int NQ, NS; cin >> NQ >> NS; vector<pair<int, int>> questionSolveRanges(NQ); for (auto& it : questionSolveRanges) { cin >> it.first >> it.second; } int numRankScore; cin >> numRankScore; vector<pair<int, int>> rankScore(numRankScore); for (auto& it : rankScore) { cin >> it.first >> it.second; it.first--; } ll T; cin >> T; vector<int> questionSolves; { sort(questionSolveRanges.begin(), questionSolveRanges.end()); auto v = getOptimal(questionSolveRanges, NS, T); if (!v) { cout << -1 << ' ' << -1 << '\n'; exit(0); } questionSolves = std::move(*v); } vector<ll> minScorePref(NS+1); { for (int v : questionSolves) minScorePref[NS-v]++; for (ll curV = 0, curDiff = 0, i = 0; i <= NS; i++) { curDiff += minScorePref[i]; minScorePref[i] = curV; curV += curDiff; } } auto isGoodScore = [&](const vector<int>& scores) -> bool { ll pref = 0; for (int i = 0; i < NS; i++) { pref += scores[i]; if (pref < minScorePref[i+1]) return false; } return true; }; vector<pair<int, int>> scoreRanges(NS, {0, NQ}); for (auto it : rankScore) { scoreRanges[NS-1-it.first] = {it.second, it.second}; } for (int i = 1; i < NS; i++) { setmax(scoreRanges[i].first, scoreRanges[i-1].first); } for (int i = NS-1; i > 0; i--) { setmin(scoreRanges[i-1].second, scoreRanges[i].second); } vector<int> optimalScores; { auto v = getOptimal(scoreRanges, NQ, T); if (!v) { cout << -1 << ' ' << -1 << '\n'; exit(0); } optimalScores = std::move(*v); } if (!isGoodScore(optimalScores)) { cout << -1 << ' ' << -1 << '\n'; exit(0); } auto canTie = [&](int numTie, int winningScore) -> bool { assert(winningScore >= optimalScores.back()); vector<pair<int, int>> curRanges = scoreRanges; for (int i = 0; i < numTie; i++) { if (curRanges[NS-1-i].second < winningScore) { return false; } curRanges[NS-1-i].first = winningScore; } auto optimal = getOptimal(curRanges, NQ, T); if (!optimal) return false; return isGoodScore(*optimal); }; auto getNumTie = [&]() -> int { int mi = 0, ma = NS+1; while (ma - mi > 1) { int md = (mi + ma) / 2; if (canTie(md, optimalScores.back())) mi = md; else ma = md; } assert(mi >= 1); return mi; }; int numTie = getNumTie(); auto getMaxScore = [&]() -> int { int mi = optimalScores.back() - 1, ma = NQ+1; while (ma - mi > 1) { int md = (mi + ma) / 2; if (canTie(numTie, md)) mi = md; else ma = md; } assert(mi >= optimalScores.back()); return mi; }; int maxScore = getMaxScore(); cout << numTie << ' ' << maxScore << '\n'; return 0; }
cpp
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
///Moba8ta gya mn el 2alb #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx,avx2,fma") #include "bits/stdc++.h" using namespace std; #define pb push_back #define F first #define S second #define f(i, a, b) for (int i = a; i < b; i++) #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define sz(x) (int)(x).size() #define mp(x, y) make_pair(x, y) #define popCnt(x) (__builtin_popcountll(x)) #define int ll using ll = long long; using ull = unsigned long long; using uint = uint32_t; using ii = pair<int, int>; const int N = 1e5 + 5, A = 12, LG = 18, MOD = 1e9 + 7; const long double PI = acos(-1); const long double EPS = 1e-9; const int INF = 1e18; string DIC = "UDRLX"; const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, 1, -1}; int n; int dX[1005][1005], dY[1005][1005]; int ans[1005][1005]; void dfs(int x, int y) { for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if (dX[nx][ny] == dX[x][y] && dY[nx][ny] == dY[x][y]) { if (ans[nx][ny] == -1) { ans[nx][ny] = k ^ 1; dfs(nx, ny); } } } } void doWork() { cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> dX[i][j] >> dY[i][j]; ans[i][j] = -1; } } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (dX[i][j] == -1) { for (int k = 0; k < 4; k++) { int nx = i + dx[k]; int ny = j + dy[k]; if (dX[nx][ny] == -1) { ans[i][j] = k; break; } } } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (i == dX[i][j] && j == dY[i][j]) { ans[i][j] = 4; dfs(i, j); } f(i, 1, n + 1) f(j, 1, n + 1) if (ans[i][j] == -1) { cout << "INVALID\n"; return; } cout << "VALID\n"; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cout << DIC[ans[i][j]]; cout << '\n'; } } int32_t main() { #ifdef ONLINE_JUDGE ios_base::sync_with_stdio(0); cin.tie(0); #endif // ONLINE_JUDGE int t = 1; // cin >> t; while (t--) { doWork(); } return 0; }
cpp
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 OutputCopy56 6 442 1 45 80 NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
[ "implementation" ]
#include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while(tt--) { int A, B, X, Y; cin >> A >> B >> X >> Y; cout << max({X * B, (A - 1 - X) * B, A * Y, A * (B - 1 - Y)}) << '\n'; } }
cpp
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4 3 5 1 4 OutputCopy1 3 2 5 1 4 1 5 1 5 InputCopy4 3 1 2 4 OutputCopy1 3 1 2 3 4 1 4 NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
[ "data structures" ]
#include <bits/stdc++.h> using namespace std; typedef long long int ll; # define mod 1000000007 int sum[300000*2+10],minn[300000+10],maxx[300000+10],pos[300000+10],n,m; int lowbit(int x) { return x&-x; } void change(int x,int val) { while(x<=n+m) { sum[x]+=val; x+=lowbit(x); } } int getsum(int x) { int ans=0; while(x) { ans+=sum[x]; x-=lowbit(x); } return ans; } int main() { cin>>n>>m; for(int i=1;i<=n;i++) { minn[i]=maxx[i]=i; change(i+m,1); pos[i]=i+m; } int now=m; for(int i=1;i<=m;i++) { int x; cin>>x; minn[x]=1; int pre=getsum(pos[x]); maxx[x]=max(maxx[x],pre); change(pos[x],-1); pos[x]=now; now--; change(pos[x],1); } for(int i=1;i<=n;i++) { maxx[i]=max(maxx[i],getsum(pos[i])); cout<<minn[i]<<" "<<maxx[i]<<endl; } return 0; }
cpp
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
#include <bits/stdc++.h> using namespace std; #define E 1e-9 #define PI 3.141592653589793238462 #define F first #define S second #define PB push_back #define EB emplace_back #define MP make_pair #define INF 1e18 #define MOD 1000000007 #define SZ(a) int((a).size()) #define setbits(a) (__builtin_popcountll(a)) #define right(a) (__builtin_ctzll(a)) #define left(a) (__builtin_clzll(a)) #define parity(a) (__builtin_parityll(a)) #define msb(a) (__lg(a)) #define lsb(a) ((ll)(log2(a & -a))) typedef std::numeric_limits<double> dbl; typedef long long ll; #define REP(i, a, b) for (ll i = a; i < b; i++) typedef vector<ll> vi; typedef pair<ll, ll> pi; typedef pair<ll, pi> pii; ll power(ll a, ll n) { ll ans = 1ll; while (n > 0) { int last_bit = (n & 1ll); if (last_bit) { ans = ans * a; } a = a * a; n = n >> 1ll; } return ans; } //*********************DSU*********************** #define MAXV 110 vector<ll> Parent(MAXV), Rank(MAXV); void Init(int n) { REP(i, 1, n + 1) { Parent[i] = i; Rank[i] = 1; } } int Root(int x) { if (Parent[x] != x) Parent[x] = Root(Parent[x]); return Parent[x]; } void Union(int x, int y) { int rx = Root(x), ry = Root(y); if (rx == ry) return; if (Rank[rx] > Rank[ry]) { Parent[ry] = rx; Rank[rx] += Rank[ry]; } else { Parent[rx] = ry; Rank[ry] += Rank[rx]; } } //**********************END************************* void PrimeFactors(ll m, map<ll, ll> &mp) { for (ll j = 2; j * j <= m; j++) { while ((m % j) == 0) { mp[j] += 1; m /= j; } } if (m > 1) mp[m] += 1; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll t; cin >> t; while (t--) { ll a, m; cin >> a >> m; ll g = __gcd(a, m); map<ll, ll> gmp; map<ll, ll> mmp; PrimeFactors(m, mmp); PrimeFactors(g, gmp); for (auto it = gmp.begin(); it != gmp.end(); it++) { mmp[it->F] -= it->S; } vi res; for (auto it = mmp.begin(); it != mmp.end(); it++) { if (it->S > 0) { res.PB(it->F); } } ll ans = ((a + m - 1) / g) - ((a - 1) / g); for (ll i = 1; i < (1ll << SZ(res)); i++) { ll prod = g; ll cnt = 0ll; for (ll j = msb(i); j >= 0; j--) { if (i & (1ll << j)) { prod *= res[j]; cnt++; } } ll tmp = ((a + m - 1) / prod) - ((a - 1) / prod); if (cnt & 1ll) ans -= tmp; else ans += tmp; } cout << ans << '\n'; } 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<iostream> #include<cstring> #include<vector> #include<map> #include<queue> #include<unordered_map> #include<cmath> #include<cstdio> #include<algorithm> #include<set> #include<cstdlib> #include<stack> #include<ctime> #define forin(i,a,n) for(int i=a;i<=n;i++) #define forni(i,n,a) for(int i=n;i>=a;i--) #define fi first #define se second using namespace std; typedef long long ll; typedef double db; typedef pair<int,int> PII; const double eps=1e-7; const int N=1e5+7 ,M=2*N , INF=0x3f3f3f3f,mod=1e9+7; inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;} void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);} template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);} template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);} int T; int n,m,k; int w[3][N]; void solve() { n=read(),m=read(); int last=0; while(m--) { int x=read(),y=read(); if(w[x][y]==1) { if(w[3-x][y]==1) last--; if(y+1<=n&&w[3-x][y+1]==1) last--; if(y-1>=1&&w[3-x][y-1]==1) last--; w[x][y]^=1; }else { if(w[3-x][y]==1) last++; if(y+1<=n&&w[3-x][y+1]==1) last++; if(y-1>=1&&w[3-x][y-1]==1) last++; w[x][y]^=1; } if(last==0) printf("Yes\n"); else printf("No\n"); } } int main() { // init(); // stin(); // scanf("%d",&T); T=1; while(T--) solve(); return 0; }
cpp
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
#include<bits/stdc++.h> using namespace std; #define int long long int #define mod 1000000007 #define pb push_back #define ff first #define ss second #define vi vector<int> #define pf push_front #define popb pop_back #define popf pop_front #define all(a) a.begin(), a.end() #define mp make_pair const char nl = '\n'; int max(int a,int b){if(a>b)return a;return b;} int min(int a,int b){ if(a<b)return a;return b;} int gcd(int a, int b) { return b?gcd(b,a%b):a;} int lcm(int a, int b) { return a/gcd(a,b)*b;} int computeXOR(int n) {if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0;} main() { int t; cin>>t; while(t--) { int n; cin>>n; int v1[n]; map<int,int>mp1; map<int,int>mp2; bool flag = false; for(int i=0;i<n;i++) { cin>>v1[i]; } for(int i = 0;i<n-2;i++) { for(int j = i+2;j<n;j++) { if(v1[i] == v1[j]) { flag = true; break; } } if(flag == true)break; } if(flag) {cout<<"YES"<<nl;} else{ cout<<"NO"<<nl; } } 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" ]
// Problem: E. Cow and Treats // Contest: Codeforces - Codeforces Round #621 (Div. 1 + Div. 2) // URL: https://codeforces.com/contest/1307/problem/E // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) //回家?我没有家可以回,我没有退路。 #include<bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") using namespace std; inline int read(){ int s=0,w=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();} while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); return s*w; } const int p=1e9+7; vector<int> v[5003],a[5003]; int n=read(),m=read(); int col[5003]; pair<int,int> solve(int x) { int res=0,ans=1; for(int i=1; i<=n; ++i) if(col[x]==i) { int X=0,Y=0,pos=0,s=(int)a[i].size(); for(int j:v[i]) if(j<=s&&a[i][j-1]==x) X=1,pos=j; if(!X) return make_pair(0,0); for(int j:v[i]) if(j<=s&&a[i][j-1]!=x&&j+pos<=s) ++Y; if(Y) res+=2,ans=1ll*ans*Y%p; else ++res; } else { int s=a[i].size(); int A=0,B=0,C=0; for(int j:v[i]) if(j<=s) { if(a[i][j-1]<x) ++A; if(a[i][s-j]>x) ++B; if(a[i][j-1]<x&&a[i][s-j]>x) ++C; } long long sum=1ll*A*B-C; if(sum) res+=2,ans=1ll*ans*(sum%p)%p; else if(A+B) res+=1,ans=1ll*ans*(A+B)%p; } return make_pair(res,ans); } pair<int,int> merge(pair<int,int> A,pair<int,int> B) { if(A.first>B.first) return A; if(A.first<B.first) return B; return make_pair(A.first,(A.second+B.second)%p); } signed main() { for(int i=1; i<=n; ++i) a[col[i]=read()].push_back(i); for(int i=1,x; i<=m; ++i) x=read(),v[x].push_back(read()); pair<int,int> ans=make_pair(0,0); for(int i=0; i<=n; ++i) ans=merge(ans,solve(i)); printf("%d %d\n",ans.first,ans.second); return 0; }
cpp
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4 ababcd abcba a b defi fed xyz x OutputCopyYES NO NO YES
[ "dp", "strings" ]
#include <bits/stdc++.h> using namespace std; const int N=405; int n,m,dp[N][N]; char s[N],t[N]; bool check(int d) { for (int i=0; i<=n; i++) for (int j=0; j<=d; j++) dp[i][j]=-1; dp[0][0]=0; for (int i=1; i<=n; i++) for (int j=0; j<=d; j++) { if (dp[i-1][j]!=-1) dp[i][j]=max(dp[i][j],dp[i-1][j]+(dp[i-1][j]<m-d && t[d+dp[i-1][j]+1]==s[i])); if (j>0 && dp[i-1][j-1]!=-1 && t[j]==s[i]) dp[i][j]=max(dp[i][j],dp[i-1][j-1]); } return (dp[n][d]==m-d); } int main() { // freopen("sa1.in","r",stdin); int T; scanf("%d",&T); while (T--) { scanf("%s%s",s+1,t+1); n=strlen(s+1),m=strlen(t+1); int flag=0; for (int d=0; d<=m; d++) if (check(d)) { flag=1; break; } puts(flag?"YES":"NO"); } return 0; }
cpp
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
/**https://userpic.codeforces.org/2328346/title/fbb135ec547634e3.jpg https://userpic.codeforces.org/2328346/title/fbb135ec547634e3.jpg https://userpic.codeforces.org/2328346/title/fbb135ec547634e3.jpg**/ //////////////////////////////////////////////////////// /// // /// CODE BY // /// RAHAPAHA // /// // //////////////////////////////////////////////////////// #include <bits/stdc++.h> #define pb push_back #define pob pop_back #define exit return 0; #define out break; #define Ferarri ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); typedef long long ll; typedef long double ld; using namespace std; vector<int> g[101]; queue<int>q; vector<int>us(101); vector<int> p(101); /*void bfs(int v){ q.push(v); us[v] = 1; while(!q.empty()){ v = q.front(); q.pop(); for (int i: g[v]) { if (!us[i]) { q.push(i); p[i] = v; us[i] = 1; } } } } */ void solve(){ } int main() { Ferarri //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int t = 1; cin >> t; while(t--) { int n; cin>>n; int a[n]; map<int,int>mp; map<int,bool>mp2; for(int i=0;i<n;i++){ cin>>a[i]; if(a[i-1]==a[i] && !mp2[a[i]] && i>0){ mp[a[i]]--; mp2[a[i]]=1; } mp[a[i]]++; } bool k=0; for(int i=0;i<n;i++){ if(mp[i+1]>=2){ cout<<"YES"; k=1; break; } } if(!k){ cout<<"NO"; } cout<<"\n"; } }
cpp
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
#include "bits/stdc++.h" using namespace std; // #define MULTI_TESTS // #define FLOAT_PRECISION 13 void solve() { int n; cin >> n; vector<int> x(n), y(n); for (int i = 0; i < n; ++i) cin >> x[i] >> y[i]; if (n % 2 == 1) { cout << "NO\n"; return; } for (int i = 0; i < n; ++i) { int x1 = x[i] - x[(i + 1) % n]; int y1 = y[i] - y[(i + 1) % n]; int x2 = x[(i + n / 2) % n] - x[(i + n / 2 + 1) % n]; int y2 = y[(i + n / 2) % n] - y[(i + n / 2 + 1) % n]; if (x1 != -x2 or y1 != -y2) { cout << "NO\n"; return; } } cout << "YES\n"; }; void init() { } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin.exceptions(cin.failbit); #ifdef FLOAT_PRECISION cout << fixed; cout.precision(FLOAT_PRECISION); #endif init(); int numTests = 1; #ifdef MULTI_TESTS cin >> numTests; #endif for (int testNo = 1; testNo <= numTests; testNo++) { solve(); } return 0; }
cpp
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define nl "\n" #define forn(i, n) for(int i = 0; i < n; i++) void solve(){ int a, b; cin >> a >> b; ll thing = (ll)(log10(b+1)); cout << (a * thing); cout << nl; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) solve(); cout.flush(); return 0; }
cpp
1284
F
F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4 1 2 2 3 4 3 1 3 2 4 1 4 OutputCopy3 3 2 4 2 2 1 1 3 4 3 1 4 InputCopy5 1 2 2 4 3 4 4 5 1 2 1 3 1 4 1 5 OutputCopy4 2 1 1 2 3 4 1 3 4 2 1 4 5 4 1 5 InputCopy9 7 9 2 8 2 1 7 5 4 7 2 4 9 6 3 9 1 8 4 8 2 9 9 5 7 6 1 3 4 6 5 3 OutputCopy8 4 2 9 2 9 7 6 7 5 7 5 9 6 9 4 6 8 2 8 4 3 9 3 5 2 1 1 8 7 4 1 3
[ "data structures", "graph matchings", "graphs", "math", "trees" ]
// LUOGU_RID: 102410942 #include<bits/stdc++.h> using namespace std; #define ll long long #define N 250100 ll n; ll du[N]; queue<ll>q; ll v[N<<1],fir[N],nxt[N<<1],cnt=0; inline void add(ll x,ll y){ v[++cnt]=y;nxt[cnt]=fir[x];fir[x]=cnt; return ; } bool vis[N]; ll fa[N]; inline ll getf(ll x){ if(fa[x]==x)return x; return fa[x]=getf(fa[x]); } ll faa[19][N],dep[N]; inline void dfs(ll x,ll ff){ faa[0][x]=ff;dep[x]=dep[ff]+1; for(int i=1;i<=18;i++)faa[i][x]=faa[i-1][faa[i-1][x]]; for(int i=fir[x];i;i=nxt[i]){ ll vi=v[i];if(vi==ff)continue; dfs(vi,x); }return ; } inline ll lca(ll x,ll y){ if(dep[x]<dep[y])swap(x,y); for(int i=18;i>=0;i--)if(dep[faa[i][x]]>=dep[y])x=faa[i][x]; if(x==y)return x; for(int i=18;i>=0;i--)if(faa[i][x]!=faa[i][y])x=faa[i][x],y=faa[i][y]; return faa[0][x]; } inline ll gt(ll x,ll y){ ll nw=x; for(int i=0;i<=18;i++){ if(y&(1<<i))nw=faa[i][nw]; }return nw; } inline void del(ll x,ll y){ ll o=lca(x,y); if(getf(o)==x){ ll p=dep[y]-dep[o]; ll l=0,r=p,mid,an; while(l<=r){ mid=(l+r)>>1; if(getf(gt(y,mid))==x)an=mid,r=mid-1; else l=mid+1; }ll g=gt(y,an),u=gt(y,an-1); cout<<g<<' '<<u;fa[x]=u; }else{ ll nw=x; for(int i=18;i>=0;i--){ if(getf(faa[i][nw])==x)nw=faa[i][nw]; }cout<<nw<<' '<<faa[0][nw]; ll g=getf(faa[0][nw]); fa[x]=g; } cout<<' '<<x<<' '<<y<<'\n' ; return ; } vector<ll>e[N]; 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;for(int i=1;i<=n;i++)fa[i]=i;cout<<n-1<<'\n'; for(int i=1;i<n;i++){ ll u,v;cin>>u>>v;add(u,v);add(v,u); }for(int i=1;i<n;i++){ ll u,v;cin>>u>>v;du[u]++;du[v]++;e[u].push_back(v);e[v].push_back(u); }for(int i=1;i<=n;i++)if(du[i]==1)q.push(i); dfs(1,0); while(!q.empty()){ ll o=q.front();q.pop();vis[o]=1; for(auto vi:e[o]){ if(vis[vi])continue; del(o,vi); du[vi]--;if(du[vi]==1)q.push(vi); } } return 0; }
cpp
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; using vi = vector<int>; int main() { cin.tie(0), ios::sync_with_stdio(0); int t, n, d; cin >> t; while (t--) { cin >> n >> d; vi a(n); for (int i = 0; i < n; i++) cin >> a[i]; int sum = a[0]; for (int i = 1; i < n; i++) { if (i*a[i] <= d) { sum += a[i]; d -= i*a[i]; continue; } sum += d/i; break; } cout << sum << '\n'; } }
cpp
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.
[ "brute force", "greedy", "implementation" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define PI 3.1415926535897932384626 #define MOD 1000000007 #define vi vector<int> #define vll vector<long long> #define vb vector<bool> #define vs vector<string> #define vvi vector<vector<int> > #define pii pair<int,int> #define pll pair<ll,ll> #define vpii vector<pair<int, int> > #define vpll vector<pair<ll,ll> > #define pb push_back #define mp make_pair #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL)); int main() { fastread() ll t; cin>>t; while(t--) { ll a[3]; for(int i=0;i<3;i++) cin>>a[i]; ll ans=0; for(int i=0;i<3;i++) { if(a[i]>0) { ans++; a[i]--; } } sort(a,a+3,greater<int>()); if(a[0]>0 and a[1]>0) { ans++; a[0]--; a[1]--; } if(a[0]>0 and a[2]>0) { ans++; a[0]--; a[2]--; } if(a[1]>0 and a[2]>0) { ans++; a[1]--; a[2]--; } if(a[0]>0 and a[1]>0 and a[2]>0) ans++; cout<<ans<<endl; } return 0; }
cpp
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
// LUOGU_RID: 101625748 #pragma GCC optimize("Ofast") #include<bits/stdc++.h> using namespace std; #define int long long int read() { int s=0; char c=getchar(); while(c<'0' || c>'9') c=getchar(); while(c>='0' && c<='9') s=s*10+c-'0',c=getchar(); return s; } int n,m,k; int a[55][20010],b[55][20010]; int sum[55][20010]; int dp[55][20010]; struct Tree { int ax1,ax2,ax3,ax4; } tree[80010]; Tree merge(Tree x,Tree y) { return {max(x.ax1,y.ax1),max(x.ax2,y.ax2),max(x.ax3,y.ax3),max(x.ax4,y.ax4)}; } void build(int now,int qx,int l,int r) { if(l==r) { tree[now]={dp[qx][l]+sum[qx][l+k-1]-sum[qx][l-1],dp[qx][l]-sum[qx][l-1], dp[qx][l]+sum[qx][l+k-1],dp[qx][l]+sum[qx][l+k-1]-sum[qx][l-1]}; return; } int mid=(l+r)>>1; build(now<<1,qx,l,mid),build(now<<1|1,qx,mid+1,r); tree[now]=merge(tree[now<<1],tree[now<<1|1]); } int query(int now,int ql,int qr,int l,int r,int op) { ql=max(ql,1ll),qr=min(qr,m-k+1); if(ql>qr) return -1e9; if(ql<=l && r<=qr) return op==1?tree[now].ax1:op==2?tree[now].ax2:op==3?tree[now].ax3:tree[now].ax4; int mid=(l+r)>>1,ans=-1e9; if(ql<=mid) ans=max(ans,query(now<<1,ql,qr,l,mid,op)); if(qr>mid) ans=max(ans,query(now<<1|1,ql,qr,mid+1,r,op)); return ans; } signed main() { n=read(),m=read(),k=read(); for(int i=1; i<=n; ++i) { for(int j=1; j<=m; ++j) { a[i][j]=read(); } } for(int i=1; i<=n; ++i) { for(int j=1; j<=m; ++j) { sum[i][j]=sum[i][j-1]+a[n-i+1][j]; } } build(1,1,1,m-k+1); for(int i=2; i<=n; ++i) { for(int j=1; j<=m-k+1; ++j) { dp[i][j]=max(dp[i][j],query(1,1,j-k,1,m-k+1,1)+sum[i-1][j+k-1]-sum[i-1][j-1]); dp[i][j]=max(dp[i][j],query(1,j-k+1,j,1,m-k+1,2)+sum[i-1][j+k-1]); dp[i][j]=max(dp[i][j],query(1,j,j+k-1,1,m-k+1,3)-sum[i-1][j-1]); dp[i][j]=max(dp[i][j],query(1,j+k,m-k+1,1,m-k+1,4)+sum[i-1][j+k-1]-sum[i-1][j-1]); } build(1,i,1,m-k+1); } int ans=0; for(int i=1; i<=m-k+1; ++i) ans=max(ans,dp[n][i]+sum[n][i+k-1]-sum[n][i-1]); cout<<ans; return 0; }
cpp
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 998244353; const int mm = 2e5 + 10; struct line{ ll l,r; }a[mm]; map<ll,int>mp; int d[mm<<2],dd[mm<<2]; void solve(){ int n; cin>>n; for(int i=1;i<=n;i++){ cin>>a[i].l>>a[i].r; mp[a[i].l]++,mp[a[i].r]++; } int ma=0; for(auto &[x,y]:mp){ y=(++ma)*2; }ma<<=1; for(int i=1;i<=n;i++){ a[i].l=mp[a[i].l],a[i].r=mp[a[i].r]; d[a[i].l]++,d[a[i].r+1]--; } for(int i=1;i<=ma+5;i++){ d[i]+=d[i-1]; } int ans0=0; for(int i=0;i<=ma+5;i++){ ans0+=(d[i]&&!d[i+1]); } for(int i=0;i<=ma+5;i++){ if(d[i]!=1&&d[i+1]==1)dd[i+1]++; } for(int i=1;i<=ma+5;i++){ if(d[i]!=1&&d[i-1]==1)dd[i-1]++; } for(int i=1;i<=ma+5;i++)dd[i]+=dd[i-1]; int ans=-10000; for(int i=1;i<=n;i++){ int k=(dd[a[i].r]-dd[a[i].l-1])/2; if(d[a[i].l]==1)k--; if(d[a[i].r]==1)k--; ans=max(k,ans); }cout<<ans+ans0<<'\n'; for(int i=0;i<=ma+10;i++){ d[i]=dd[i]=0; }mp.clear(); } int main(){ std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int t; cin>>t; while(t--){ solve(); } }
cpp
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
#include<bits/stdc++.h> using namespace std; int main() { string s;cin>>s; int n = s.length(); vector<int> a; vector<int> b; int close=0; for(int i=0;i<n;i++) { if(s[i]==')') { b.push_back(i); close++; } else a.push_back(i); } if(close==0) { cout<<0<<"\n"; return 0; } int c=0; int ma=INT_MIN; for(int i=0;i<n;i++) { if(s[i]=='(') c++; else close--; if(s[i]=='(' && close>=c) ma =max(ma,c); } if(ma==INT_MIN) { cout<<0<<"\n"; return 0; } cout<<1<<"\n"; cout<<ma*2<<"\n"; reverse(b.begin(),b.end()); vector<int> ans; for(int i=0;i<ma;i++) { ans.push_back(a[i]+1); ans.push_back(b[i]+1); } sort(ans.begin(),ans.end()); for(int i=0;i<ans.size();i++) cout<<ans[i]<<" "; cout<<"\n"; }
cpp
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
#include <cstdio> #include <iostream> const int N = 1e6+10; const int INF = 1e9; using namespace std; int arr[N]; int n, K; void Sol() { int ans = arr[1]; int rmn = K; for (int i=2; i<=n; i++) { int t = min(rmn/(i-1), arr[i]); ans += t; rmn -= t*(i-1); if(rmn <= 0) break; } printf("%d\n", ans); } int main() { int tt; scanf("%d",&tt); while (tt--) { scanf("%d %d",&n,&K); for (int i=1; i<=n; i++) scanf("%d",&arr[i]); Sol(); } return 0; }
cpp
1288
F
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 OutputCopy35 BUURRU InputCopy3 1 3 4 5 RRR B 2 1 1 1 3 1 OutputCopy-1 InputCopy3 1 3 4 5 URU B 2 1 1 1 3 1 OutputCopy14 RBB
[ "constructive algorithms", "flows" ]
#include <bits/stdc++.h> using namespace std; const int N = 505, inf = 0x3f3f3f3f; namespace flow_graph { int n, s, t, S, T, cnt, h[N], cur[N], in[N], d[N], sum; bool vis[N]; struct edge { int nxt, fl, w, to; void insert(int x, int y, int z, int ww) { nxt = h[x], to = y, w = ww, fl = z, h[x] = cnt++; } } e[N * N]; void init(int len) { n = len; s = 0; t = n + 1; S = t + 1; T = S + 1; memset(h, -1, sizeof(h)); return; } void add(int w, int up, int low, int u, int v) { in[u] -= low; in[v] += low; e[cnt].insert(u, v, up - low, w); e[cnt].insert(v, u, 0, -w); return; } void add(int w, int flow, int u, int v) { e[cnt].insert(u, v, flow, w); e[cnt].insert(v, u, 0, -w); return; } void build() { for (int i = s; i <= t; i++) { if (in[i] > 0) { sum += in[i]; add(0, in[i], 0, S, i); } else { add(0, -in[i], 0, i, T); } } } bool spfa() { memcpy(cur, h, sizeof(h)); memset(d, 63, sizeof(d)); queue<int> Q; d[S] = 0, Q.push(S); while (!Q.empty()) { int u = Q.front(); Q.pop(), vis[u] = 0; for (int i = h[u], v; ~i; i = e[i].nxt) { if (e[i].fl && d[(v = e[i].to)] > d[u] + e[i].w) { d[v] = d[u] + e[i].w; if (!vis[v]) Q.push(v), vis[v] = 1; } } } return d[T] != inf; } int dfs(int u, int sum) { if (u == T) return sum; int used = 0; vis[u] = 1; for (int &i = cur[u], v; ~i; i = e[i].nxt) { if (e[i].fl && !vis[v = e[i].to] && d[v] == d[u] + e[i].w) { int fl = dfs(v, min(sum - used, e[i].fl)); e[i].fl -= fl; e[i ^ 1].fl += fl; if ((used += fl) == sum) break; } } vis[u] = 0; return used; } int dinic() { int maxflow = 0, cost = 0; while (spfa()) { int flow = dfs(S, inf); cost += flow * d[T], maxflow += flow; } return maxflow == sum ? cost : -1; } } using namespace flow_graph; int n1, n2, m, R, B; char c1[N], c2[N]; int main() { scanf("%d%d%d%d%d%s%s", &n1, &n2, &m, &R, &B, c1 + 1, c2 + 1); init(n1 + n2); for (int i = 1; i <= m; i++) { int u, v; scanf("%d%d", &u, &v); add(R, 1, 0, u, v + n1); add(B, 1, 0, v + n1, u); } for (int i = 1; i <= n1 + n2; i++) { char c = i <= n1 ? c1[i] : c2[i - n1] == 'U' ? 'U' : 'R' + 'B' - c2[i - n1]; if (c == 'R') { add(0, inf, 1, s, i); } if (c == 'B') { add(0, inf, 1, i, t); } if (c == 'U') { add(0, inf, 0, s, i); add(0, inf, 0, i, t); } } add(0, inf, 0, t, s); build(); int cost = dinic(); if (cost == -1) { puts("-1"); return 0; } printf("%d\n", cost); for (int i = 0; i < 4 * m; i += 4) { if (!e[i].fl) { putchar('R'); } else if (!e[i + 2].fl) { putchar('B'); } else { putchar('U'); } } puts(""); return 0; }
cpp
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
[ "implementation", "math" ]
#include<bits/stdc++.h> using namespace std; #define endl '\n' #define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int main() { optimize(); long long n,a,b,c,d=0,e,f,g,h,i,j,k; cin>>a>>b; /*e=a; c=log2(b/a); d=log2(b/a)/log2(3); //cout<<c<<" "<<d<<endl; if(a==b){ cout<<0<<endl; } else if(((int)(b)%2!=0 && (int)(b)%3!=0) || a>(b/3)){ cout<<-1<<endl; } else if(floor(c)==ceil(c)){ cout<<log2(c)<<endl; } else if(floor(d)==ceil(d)){ cout<<log2(d)/log2(3)<<endl; } else{ g=0; h=0; for( i=2;;i+=2){ e=e*6; if(e==b){ cout<<i<<endl; return 0; } else if(e>b){ e/=6; f=e; i-=2; for( j=1;;j++){ e*=2; if(e==b){ cout<<i+j<<endl; return 0; } else if(e>b){ e/=2; j--; g=1; break; } } for( k=1;;k++){ f*=3; if(e==b){ cout<<i+j+k<<endl; return 0; } else if(f>b){ h=1; break; } } if(g==1 && h==1){ cout<<-1<<endl; } } } }*/ if(a==b){ cout<<0<<endl; return 0; } else if(b%a!=0 || a>b/2){ cout<<-1<<endl; return 0; } c=b/a; while(c!=1){ if(c%2==0){ c/=2; d++; } else if(c%3==0){ c/=3; d++; } else{ break; } } if(c==1){ cout<<d<<endl; } else{ cout<<-1<<endl; } return 0; }
cpp
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
#include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #include<cmath> #include<map> #include<stack> #include<queue> #include<vector> #include<set> #include<limits> using namespace std; typedef long long ll; const int mx=3e5+5; const int mod=1e9+7; const int inf=0x3f3f3f3f; char s[mx]; int n, q, l, r, sum[mx][26]; int main() { /*std::ios::sync_with_stdio(false); std::cin.tie(0);*/ scanf("%s",s+1); n = strlen(s + 1); for (int i = 1; i <= n; i++) { for (int j = 0; j < 26; j++) { sum[i][j] = sum[i - 1][j]; } sum[i][s[i] - 'a']++; } cin >> q; while (q--) { cin >> l >> r; int cnt = 0; for (int i = 0; i < 26; i++) { cnt += (sum[r][i] - sum[l - 1][i] > 0); } if (l == r || cnt >= 3 || s[l] != s[r]) { cout << "Yes\n"; } else { cout << "No\n"; } } return 0; }
cpp
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
#include <bits/stdc++.h> using namespace std; #define IOS \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0); #define ll long long const int N = 100001; const int P = 1e9 + 7; const ll inf = LLONG_MAX; #define rep(i, a, b) for (int i = a; i < b; i++) #define pb push_back #define all(x) x.begin(), x.end() #define ff first #define ss second #define cnu continue int am() { ll n,x; cin>>n>>x; string s; cin>>s; map<ll,ll>m; ll val = 0; for( int i = 0 ; i < n; i ++) { if( s[i] == '0') val++; else val--; m[val]++; } if( val == 0 ) { if( m[x] != 0) cout<<"-1\n"; else cout<<"0\n"; return 0; } ll ans = 0; for( auto it = m.begin() ; it != m.end() ; ++it) { if( (x-it->ff) % val== 0 && (x-it->ff) * val >= 0) ans += (it->ss); } if(x == 0) ans++; cout<<ans<<"\n"; return 0; } /***********************************************************/ int main() { IOS; // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); ll T = 1; cin >> T; while (T--) am(); return 0; }
cpp
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3 1 2 1 2 1 2 OutputCopy499122177 InputCopy2 42 1337 13 420 OutputCopy578894053 InputCopy2 1 1 0 0 OutputCopy1 InputCopy2 1 1 1 1 OutputCopy1 NoteThe real answer in the first test is 1212.
[ "combinatorics", "dp", "probabilities" ]
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int N=50+5; const int Mod=998244353; int n,m,ans,a[N],b[N],c[N<<1],f[N],g[N]; int qpow(int x,int k) { int res=1; while(k) { if(k&1)res=1ll*res*x%Mod; x=1ll*x*x%Mod,k>>=1; } return res; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d%d",&a[i],&b[i]); c[++m]=a[i],c[++m]=++b[i]; } sort(c+1,c+1+m); m=unique(c+1,c+1+m)-c-1; for(int i=1;i<=n;i++) { a[i]=lower_bound(c+1,c+1+m,a[i])-c; b[i]=lower_bound(c+1,c+1+m,b[i])-c; } f[0]=1; for(int j=m-1;j>=1;j--) { int l=c[j+1]-c[j]; g[0]=1; for(int i=1;i<=n;i++)g[i]=1ll*g[i-1]*(l+i-1)%Mod*qpow(i,Mod-2)%Mod; for(int i=n;i>=1;i--) if(a[i]<=j&&j<b[i])for(int o=1,k=i-1;k>=0;k--,o++) { f[i]=(f[i]+1ll*g[o]*f[k]%Mod)%Mod; if(a[k]>j||j>=b[k])break; } } ans=f[n]; for(int i=1;i<=n;i++)ans=1ll*ans*qpow(c[b[i]]-c[a[i]],Mod-2)%Mod; printf("%d\n",ans); return 0; }
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> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template<class T> using oset =tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update> ; typedef long long ll; typedef vector<ll> vll; typedef pair<ll,ll> pll; typedef long double ld; typedef map<ll,ll> mll; typedef vector<int> vi; typedef set<ll> sll; typedef pair<int,int> ii; typedef vector<ii> vii; ll gcd(ll a, ll b) {return a == 0? b: gcd(b%a,a);} ll lcm(ll a, ll b) {return a * (b / gcd(a,b));} #define inf 1e17 #define pb(x) push_back(x) #define rep(x,n) for (int i = x; i < n; i++) #define all(x) (x).begin(), (x).end() #define fo(x) find_by_order(x) #define ok(x) order_of_key(x) ll mod = 1e9 + 7; int MAXN = 100000; ii f(vector<vi> &grid, int k, vector<vi> &adj){ int n = grid.size(), m = grid[0].size(); vi cnt(1 << m,-1); for (int i = 0; i < n; i++) { int mask = 0; for (int j = 0; j < m; j++) { if (grid[i][j] >= k) mask |= (1 << j); } cnt[mask] = i; for (auto v : adj[mask]) if (cnt[v] != -1) return {i,cnt[v]}; } return {-1,-1}; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); int n,m; cin >> n >> m; int M = 1 << m; vector<vi> adj(M); for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { if ((i | j) == (M - 1)) adj[i].pb(j); } } vector<vi> grid(n,vi(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cin >> grid[i][j]; } int l = 0, r = 1e9; while (l <= r) { int mid = l + (r - l) / 2; if (f(grid,mid,adj).first != -1) { l = mid + 1; }else r = mid - 1; } ii ans = f(grid,r,adj); //cout << r << "\n"; cout << ans.first + 1 << " " << ans.second + 1 << "\n"; return 0; }
cpp
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3 1 2 1 2 1 2 OutputCopy499122177 InputCopy2 42 1337 13 420 OutputCopy578894053 InputCopy2 1 1 0 0 OutputCopy1 InputCopy2 1 1 1 1 OutputCopy1 NoteThe real answer in the first test is 1212.
[ "combinatorics", "dp", "probabilities" ]
// LUOGU_RID: 90477872 #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) #define int long long const int maxn=1005,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 Pow(int x,int y){int res=1;while(y){if(y&1)res=res*x%mod;x=x*x%mod;y=y/2;}return res;} int n,m,x,y,tot=0,ans=0,a[maxn],b[maxn],c[maxn],C[maxn],g[maxn]; signed main(){ //freopen("1.in","r",stdin); //freopen(".out","w",stdout); n=read();//cout<<"A"; for(int i=1;i<=n;i++){ a[i]=read(),b[i]=read();c[++tot]=a[i],c[++tot]=b[i]+1; }sort(c+1,c+tot+1);C[0]=g[0]=1; int un=unique(c+1,c+tot+1)-c-1; for(int i=1;i<=n;i++){ a[i]=lower_bound(c+1,c+un+1,a[i])-c; b[i]=lower_bound(c+1,c+un+1,b[i]+1)-c; } for(int i=un;i>=2;i--){ int L=c[i]-c[i-1]; for(int j=1;j<=n;j++)C[j]=C[j-1]*(L+j-1)%mod*Pow(j,mod-2)%mod; for(int j=n;j>=1;j--)if(a[j]<=i-1&&i<=b[j]){ for(int k=j-1,p=1;k>=0;k--,p++){ g[j]=(g[j]+C[p]*g[k])%mod; if(a[k]>i-1||i>b[k])break; } } }int ans=g[n]; for(int i=1;i<=n;i++)ans=ans*Pow(c[b[i]]-c[a[i]],mod-2)%mod; cout<<ans<<endl; return 0; }
cpp
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define MOD 1000000007 using namespace std; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //priority_queue <int, vector<int>, greater<int>> q; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int test; cin >> test; while(test--){ int n, x, nr = 0, sol = 0; string s; cin >> n >> x >> s; for(int i = 0; i < n; i++){ if(s[i] == '0') nr++; else nr--; if(nr == x) sol++; } if(nr == 0){ if(sol > 0) cout << "-1\n"; else cout << "0\n"; continue; } if(x == 0) sol++; int num = 0; for(int i = 0; i < n; i++){ if(s[i] == '0') num++; else num--; int dif = x - num; if((dif > 0 && nr > 0) || (dif < 0 && nr < 0)){ if(dif % nr == 0) sol++; } } cout << sol << "\n"; } return 0; }
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> #define int long long #define MOD 1000000007 #define all(x) x.begin(),x.end() #define ff first #define ss second #define pb push_back using namespace std; int32_t main(){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++)cin>>arr[i]; priority_queue<int>pq; int ans=0; for(int i=0;i<n;i++){ if(!pq.empty() && pq.top()>arr[i]){ ans+=pq.top()-arr[i]; pq.pop(); pq.push(arr[i]); } pq.push(arr[i]); } cout<<ans<<endl; }
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" ]
// Problem: B. Madhouse (Easy version) // Contest: Codeforces - Blitztage vs Kira_1234 Round 3 // URL: https://codeforces.com/group/kWHBMLaEjt/contest/415298/problem/B // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) #include <bits/stdc++.h> //Blitztage using namespace std; //for loop macros #define fo(i,n) for(int i = 0; i < n; i++) #define foL(i,n) for(long long i = 0; i < n; i++) #define foa(i,k,n) for(int i = k; i < n; i++) #define fob(i,k,n) for(int i = k; i >= n; i--) #define foaL(i,k,n) for(long long i = k; i < n; i++) #define fobL(i,k,n) for(long long i = k; i >= n; i--) constexpr int bits(int x) {return x == 0 ? 0 : 31-__builtin_clz(x);} //template -> AnandOza && bqi343 Github #define pb push_back #define eb emplace_back #define mp make_pair #define F first #define S second #define resz resize #define sz(x) int((x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define trav(a, x) for (auto &a : x) #define L1(u, ...) [&](auto &&u) { return __VA_ARGS__; } #define L2(u, v, ...) [&](auto &&u, auto &&v) { return __VA_ARGS__; } #define sort_by(x, y) sort(all(x), [&](const auto &l, const auto &r) { return y; }) #define getunique(v) {sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end());} using ld = long double; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using vll = vector<ll>; using vvll = vector<vll>; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vs = vector<string>; using pii = pair<int, int>; using pll = pair<ll, ll>; using pdd = pair<double, double>; using vpii = vector<pii>; using vpll = vector<pll>; using vpdd = vector<pdd>; template <typename T> void ckmin(T &a, const T &b) { a = min(a, b); } template <typename T> void ckmax(T &a, const T &b) { a = max(a, b); } mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); namespace __input { template <class T1, class T2> void re(pair<T1, T2> &p); template <class T> void re(vector<T> &a); template <class T, size_t SZ> void re(array<T, SZ> &a); template <class T> void re(T &x) { cin >> x; } void re(double &x) { string t; re(t); x = stod(t); } template <class Arg, class... Args> void re(Arg &first, Args &...rest) { re(first); re(rest...); } template <class T1, class T2> void re(pair<T1, T2> &p) { re(p.f, p.s); } template <class T> void re(vector<T> &a) { for (int i = 0; i < sz(a); i++) re(a[i]); } template <class T, size_t SZ> void re(array<T, SZ> &a) { for (int i = 0; i < SZ; i++) re(a[i]); } } using namespace __input; namespace __output { template <typename T> struct is_outputtable { template <typename C> static constexpr decltype(declval<ostream &>() << declval<const C &>(), bool()) test(int) { return true; } template <typename C> static constexpr bool test(...) { return false; } static constexpr bool value = test<T>(int()); }; template <class T, typename V = decltype(declval<const T &>().begin()), typename S = typename enable_if<!is_outputtable<T>::value, bool>::type> void pr(const T &x); template <class T, typename V = decltype(declval<ostream &>() << declval<const T &>())> void pr(const T &x) { cout << x; } template <class T1, class T2> void pr(const pair<T1, T2> &x); template <class Arg, class... Args> void pr(const Arg &first, const Args &...rest) { pr(first); pr(rest...); } template <class T, bool pretty = true> void prContain(const T &x) { if (pretty) pr("{"); bool fst = 1; for (const auto &a : x) pr(!fst ? pretty ? ", " : " " : "", a), fst = 0; if (pretty) pr("}"); } template <class T> void pc(const T &x) { prContain<T, false>(x); pr("\n"); } template <class T1, class T2> void pr(const pair<T1, T2> &x) { pr("{", x.f, ", ", x.s, "}"); } template <class T, typename V, typename S> void pr(const T &x) { prContain(x); } void ps() { pr("\n"); } template <class Arg> void ps(const Arg &first) { pr(first); ps(); } template <class Arg, class... Args> void ps(const Arg &first, const Args &...rest) { pr(first, " "); ps(rest...); } } using namespace __output; #define __pn(x) pr(#x, " = ") #ifdef ANAND_LOCAL #define pd(...) __pn((__VA_ARGS__)), ps(__VA_ARGS__), cout << flush #else #define pd(...) #endif namespace __algorithm { template <typename T> void dedup(vector<T> &v) { sort(all(v)); v.erase(unique(all(v)), v.end()); } template <typename T> typename vector<T>::const_iterator find(const vector<T> &v, const T &x) { auto it = lower_bound(all(v), x); return it != v.end() && *it == x ? it : v.end(); } template <typename T> size_t index(const vector<T> &v, const T &x) { auto it = find(v, x); assert(it != v.end() && *it == x); return it - v.begin(); } template <typename I> struct _reversed_struct { I &v_; explicit _reversed_struct(I &v) : v_{v} {} typename I::reverse_iterator begin() const { return v_.rbegin(); } typename I::reverse_iterator end() const { return v_.rend(); } }; template <typename I> _reversed_struct<I> reversed(I &v) { return _reversed_struct<I>(v); } } using namespace __algorithm; namespace __io { void setIO() { ios_base::sync_with_stdio(0); cin.tie(0); cout << setprecision(15); } } using namespace __io; template<typename T_vector> void outvec(const T_vector &v, bool add_one = false, int start = -1, int end = -1) { if (start < 0) start = 0; if (end < 0) end = int(v.size()); for (int i = start; i < end; i++) cout << v[i] + (add_one ? 1 : 0) << (i < end - 1 ? ' ' : '\n'); } //#define int long long #define noo {ps("NO");return;} #define yess {ps("YES");return;} #define GOOGLE 0 const ld pi = 3.14159265358979323846; const ll N = 7e5; //Global declarations ll n, m, k, l, r, x, y, z; string s, t; const ll mod = 1000000007; #define Multitests 0 multiset<string> ask(int l, int r, int len){ multiset<string> ans; cout << "? " << l << " " << r << endl; cout.flush(); while(sz(ans) < len){ string s; cin >> s; sort(all(s)); ans.insert(s); } return ans; } void answer(string s){ cout << "! " << s << endl; cout.flush(); } void solve(){ ll n; cin >> n; if(n == 1){ multiset<string> a1 = ask(1,1,1); for(auto x : a1){ if(sz(x) == 1){ answer(x); return; } } } if(n == 2){ multiset<string> a1 = ask(1,1,1); string ans; for(auto x : a1){ if(sz(x) == 1){ ans += x; break; } } multiset<string> a2 = ask(2,2,1); for(auto x : a2){ if(sz(x) == 1){ ans += x; break; } } answer(ans); return; } multiset<string> a1 = ask(1, n, n * (n + 1) / 2); multiset<string> a2 = ask(2, n, n * (n - 1) / 2); multiset<string> a3 = ask(1, 1, 1); string ans; for(auto x : a2) a1.erase(a1.find(x)); vector<string> aa1(n + 1); for(auto x : a1) aa1[sz(x)] = x; vll alp(26); for(int i = 1; i <= n; i++){ vll temp(26); for(char c : aa1[i]){ temp[c - 'a']++; } for(int i = 0; i < 26; i++){ if(alp[i] + 1 == temp[i]){ ans += char(i + 'a'); break; } } alp = temp; } answer(ans); } int32_t main(){ #if Multitests int t; cin >> t; for(int i = 0; i < t; i++){ #if GOOGLE cout<<"Case #"<<i + 1<<": "; #endif solve(); } #else solve(); #endif return 0; }
cpp
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
#include <iostream> using namespace std; int main() { int Nr; cin >> Nr; while(Nr--){ int a , b, c, d; cin >> a >> b >>c >> d; if((b-a)%(c+d) == 0){ cout << (b - a) / (c + d) << endl; } else cout << "-1" << endl; } }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#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; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int x0,y0,ax,ay,bx,by;cin>>x0>>y0>>ax>>ay>>bx>>by; const int MX = 2e16+1; vii pts = {{x0,y0}}; while (true) { auto [x,y] = pts.back(); int nx = x*ax + bx; int ny = y*ay + by; if (nx >= MX || ny >= MX) break; pts.push_back({nx,ny}); } int xs,ys,t;cin>>xs>>ys>>t; int bst = 0; int n = pts.size(); auto ditbetween = [&](int x, int y) { auto [x1,y1] = pts[x]; auto [x2,y2] = pts[y]; return abs(x1-x2) + abs(y1-y2); }; auto totdist = [&](int x, int y) { int tot = 0; REPL(i, x, y) { auto [x1,y1] = pts[i]; auto [x2,y2] = pts[i+1]; tot += abs(x1-x2) + abs(y1-y2); } return tot; }; REP(i, n) { auto [xx,yy] = pts[i]; int inid = abs(xx - xs) + abs(yy - ys); if (inid <= t) { bst = max(bst, 1LL); } for (int j = i - 1; j >= 0; j--) { REPL(k, i+1, n) { int d1 = totdist(j, i); int d2 = totdist(i, k); if (inid + d1 <= t) { bst = max(1LL + abs(j-i), bst); } if (inid + d2 <= t) { bst = max(1 + abs(k-i), bst); } int excess = d1 + d2 + min(d1,d2); if (excess + inid <= t) { bst = max(abs(k-j) + 1, bst); } } } } auto [xx,yy] = pts[0]; auto [xx1,yy1] = pts[n-1]; int inid = abs(xx - xs) + abs(yy - ys); int inid2 = abs(xx1-xs) + abs(yy1 - ys); REP(i, n) { if (inid + ditbetween(0,i) <= t) { bst = max(bst, i+1); } if (inid2 + ditbetween(n-1, i) <= t) { bst = max(bst, n-i); } } cout<<bst; }
cpp
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10 codeforces dodivthree OutputCopy5 7 8 4 9 2 2 9 10 3 1 InputCopy7 abaca?b zabbbcc OutputCopy5 6 5 2 3 4 6 7 4 1 2 InputCopy9 bambarbia hellocode OutputCopy0 InputCopy10 code?????? ??????test OutputCopy10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
[ "greedy", "implementation" ]
// ~BhupinderJ #include <bits/stdc++.h> using namespace std; #define endl "\n" #define spc <<" "<< #define pii pair<int, int> #define vvi vector<vector<int>> #define all(t) t.begin(), t.end() //#define int long long const int Mod = 1e9+7; const int N = 1e5+1; void SOLVE(){ int n; cin >> n; string l, r; cin >> l >> r; vvi li(27), ri(27); for(int i=0 ; i<n ; i++){ if(l[i] == '?') li[26].push_back(i+1); else li[l[i] - 'a'].push_back(i+1); if(r[i] == '?') ri[26].push_back(i+1); else ri[r[i] - 'a'].push_back(i+1); } vector<pii> ans; vector<int> pLeft, pRight; for(int i=0 ; i<26 ; i++){ int m = min(li[i].size(), ri[i].size()); for(int j=0 ; j<m ; j++){ ans.push_back({li[i][j], ri[i][j]}); } for(int j = m ; j < li[i].size() ; j++){ pLeft.push_back(li[i][j]); } for(int j = m ; j < ri[i].size() ; j++){ pRight.push_back(ri[i][j]); } } int i = 0, j = 0; int pr = 0, pl = 0; while(i < li[26].size() and pr < pRight.size()){ ans.push_back({li[26][i], pRight[pr]}); i++, pr++; } while(j < ri[26].size() and pl < pLeft.size()){ ans.push_back({pLeft[pl], ri[26][j]}); j++, pl++; } while(i < li[26].size() and j < ri[26].size()){ ans.push_back({li[26][i], ri[26][j]}); i++, j++; } cout << ans.size() << endl; for(pii x : ans) cout << x.first spc x.second << endl; } signed main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int T = 1; //cin >> T; while(T--) SOLVE(); }
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
//Author: Ankush Bhagat (https://github.com/ankushbhagat124) //RFIPITIDS #include <bits/stdc++.h> #define int long long const int N = (int)(3e5 + 1); const int mod = (int)(1e9 + 7); using namespace std; void init() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } signed main() { init(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); /* */ int n; cin >> n; vector <int> a(n), t(n); for (auto &x : a) cin >> x; for (auto &x : t) cin >> x; map <int, vector <int>> mp; int back = INT_MAX; for (int i = 0; i < n; i++) { mp[a[i]].push_back(t[i]); back = min(back, a[i]); } priority_queue <int> pq; int sum = 0; int ans = 0; sort (a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); int sz = (int)a.size(); int i = 0; while (i < sz) { if (back == a[i]) { for (auto x : mp[a[i]]) { pq.push(x); sum += x; } i++; } if (!pq.empty()) { sum -= pq.top(); ans += sum; pq.pop(); } back++; } while (!pq.empty()) { sum -= pq.top(); ans += sum; pq.pop(); } cout << ans << endl; }
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" ]
//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=1; //cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } //sort(a,a+n); vector<int> bf(35,0); // for(int i=n-1;i>=0;i--){ // cout<<a[i]<<" "; // } // cout<<endl; for (int i = 0; i < n; ++i) { for(int j=0;j<32;j++){ int check=a[i]&(1<<j); if(check>0){ bf[j]++; } } } set<int> s; vector<int> v; for(int i=31;i>=0;i--){ if(bf[i]==1){ for(int j=0;j<n;j++){ int check=a[j]&(1<<i); if(check>0 and s.find(j)==s.end()){ v.push_back(a[j]); s.insert(j); break; } } } } for(int i=0;i<n;i++){ if(s.find(i)==s.end()){ v.push_back(a[i]); } } for (int i = 0; i < v.size(); ++i) { cout<<v[i]<<" "; } cout<<endl; } return 0; }
cpp
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; typedef pair<int, int> pii; const ll MAXN = 5e5 + 20; const ll MOD = 1e9 + 7; const ll INF = 1e18; #define pb push_back #define Mp make_pair #define F first #define S second #define Sz(x) int((x).size()) #define endll '\n' vector <int> adj[MAXN], vec; bool mark[MAXN]; int ask(int r){ vec.clear(); for(int u : adj[r]) if(!mark[u]) vec.pb(u); while(Sz(vec) > 1){ int u = vec.back(), v = vec[Sz(vec) - 2], par; vec.pop_back(), vec.pop_back(); mark[u] = mark[v] = 1; cout << "? " << u << " " << v << endl; cin >> par; if(par != r){ mark[r] = 1; return ask(par); } } if(Sz(vec) == 1){ int i = 0; while(i < Sz(adj[vec[0]]) && (mark[adj[vec[0]][i]] || adj[vec[0]][i] == r)) i ++; if(i == Sz(adj[vec[0]])){ mark[vec[0]] = mark[r] = 1; cout << "? " << r << " " << vec[0] << endl; cin >> r; return r; } else{ int par; mark[adj[vec[0]][i]] = mark[r] = 1; cout << "? " << r << " " << adj[vec[0]][i] << endl; cin >> par; if(par == vec[0]) return ask(par); if(par == adj[vec[0]][i]){ mark[vec[0]] = 1; return ask(par); } } } return r; } int main(){ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n; cin >> n; for(int i = 0; i < n - 1; i ++){ int u, v; cin >> u >> v; adj[u].pb(v), adj[v].pb(u); } int rt = ask(1); cout << "! " << rt << endl; 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; #define ll long long int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<vector<int>> g(n); vector<int> C(n); vector<vector<int>> ans(n); int rt = -1; for (int i = 0; i < n; i++) { int p; cin >> p >> C[i]; if (p == 0) rt = i; else g[p - 1].push_back(i); } function<void(int)> dfs = [&](int c) { for (int i : g[c]) { dfs(i); for (int x : ans[i]) { ans[c].push_back(x); } } if (C[c] > ans[c].size()) { cout << "NO\n"; exit(0); } ans[c].insert(ans[c].begin() + C[c], c); }; dfs(rt); vector<int> res(n); assert(ans[rt].size() == n); for (int i = 0; i < n; i++) { res[ans[rt][i]] = i + 1; } cout << "YES\n"; for (int i : res) cout << i << " "; cout << "\n"; } // ~ BucketPotato
cpp
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cassert> #define siz(x) int((x).size()) #define cauto const auto #define all(x) (x).begin(),(x).end() using std::cin;using std::cout; using loli=long long; using venti=__int128_t; using pii=std::pair<int,int>; constexpr int N=52,M=20002; int n,m,k,sum[N][M],a[N][M],l[N][M],r[N][M]; template<typename any>inline void chkmax(any &x,const any &y){if(x<y)x=y;} signed main(){ // freopen("range.in","r",stdin); // freopen("range.out","w",stdout); std::ios::sync_with_stdio(false);cin.tie(nullptr); cin>>n>>m>>k; for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>a[i][j],sum[i][j]=a[i][j]+sum[i][j-1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m-k+1;j++){ int v=std::max(l[i-1][j-1],r[i-1][j+k])+sum[i][j+k-1]-sum[i][j-1]+sum[i+1][j+k-1]-sum[i+1][j-1]; chkmax(l[i][j+k-1],v); chkmax(r[i][j],v); } for(int j=1;j<=m;j++)chkmax(l[i][j],l[i][j-1]); for(int j=m;j>=1;j--)chkmax(r[i][j],r[i][j+1]); for(int j=m;j>=1;j--)chkmax(l[i][j-1],l[i][j]-a[i+1][j]); for(int j=1;j<=m;j++)chkmax(r[i][j+1],r[i][j]-a[i+1][j]); } cout<<l[n][m]; return 0; }
cpp
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define MOD 1000000007 using namespace std; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //priority_queue <int, vector<int>, greater<int>> q; int fr[800005], ne[800005]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int q, x, nmax = 800000, sol = 0; cin >> q >> x; for(int i = 0; i < x; i++){ ne[i] = i; } for(int i = 1; i <= q; i++){ int y; cin >> y; y = y % x; if(ne[y] + x <= nmax){ ne[y] = ne[y] + x; } y = ne[y] - x; fr[y] = 1; while(fr[sol] == 1){ sol++; } cout << sol << "\n"; } return 0; }
cpp
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define int ll const int N = 2e5 + 5; const int M = 1e6 + 5; int n, prime[M], tot; ll a[N]; mt19937_64 rnd(19260817); bool vis[M]; inline void Euler() { for (int i = 2; i <= M - 5; i++) { if (!vis[i]) prime[++tot] = i; for (int j = 1; j <= tot && 1ll * i * prime[j] <= M - 5; j++) { vis[i * prime[j]] = true; if (!(i % prime[j])) break; } } } set<ll> s; inline void solve(ll x) { for (int i = 1; i <= tot && x > 1; i++) if (!(x % prime[i])) { s.insert(prime[i]); while (!(x % prime[i])) x /= prime[i]; } if (x > 1) s.insert(x); } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); Euler(); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= 50; i++) { int x = rnd() % n + 1; if (a[x] > 2) solve(a[x] - 1); solve(a[x]), solve(a[x] + 1); } int ans = n, cur; for (ll x : s) { cur = 0; for (int i = 1; i <= n; i++) cur += a[i] < x ? x - a[i] : min(a[i] % x, x - a[i] % x); ans = min(ans, cur); } cout << ans; return 0; }
cpp
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
#include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ t--; int n,s,k; cin >> n >> s >> k; set<int> st; for(int i=-(k+3);i<=(k+3);i++){ int cf=s+i; if(1<=cf && cf<=n){st.insert(cf);} } for(int i=0;i<k;i++){ int x; cin >> x; st.erase(x); } int res=1e9; auto it=st.lower_bound(s); if(it!=st.end()){res=min(res,(*it)-s);} if(it!=st.begin()){ it--; res=min(res,s-(*it)); } cout << res << "\n"; } return 0; }
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> using namespace std; #define ll long long #define l1(i, n) for (ll i = 1; i <= n; i++) #define l0(i, n) for (ll i = 0; i < n; i++) #define pb push_back #define xx first #define yy second #define sorted(x) sort(x.begin(), x.end()) #define reversed(x) reverse(x.begin(), x.end()) #define all(x) x.begin(), x.end() #define ms(a, b) memset(a, b, sizeof(a)); #define cases(tc) cout<<"Case #"<<tc<<": " #define nl cout<<"\n"; #define pi acos(-1) #define mod 1000000007 #define inf 1000000000000000001 #define maxn 1000001 ll seg[4*maxn]; ll lazy[4*maxn]; vector <ll> val(maxn, -inf); void build(ll st, ll en, ll nd){ if(st==en){ seg[nd]=val[st]; return; } ll mid=(st+en)/2; build(st, mid, 2*nd); build(mid+1, en, 2*nd+1); seg[nd]=max(seg[2*nd], seg[2*nd+1]); } void update(ll st, ll en, ll nd, ll l, ll r, ll val){ if(lazy[nd]!=0){ ll temp=lazy[nd]; lazy[nd]=0; seg[nd]+=temp; if(st!=en){ lazy[2*nd]+=temp; lazy[2*nd+1]+=temp; } } if(st>r || en<l){ return; } if(st>=l && en<=r){ seg[nd]+=val; if(st!=en){ lazy[2*nd]+=val; lazy[2*nd+1]+=val; } return; } ll mid=(st+en)/2; update(st, mid, 2*nd, l, r, val); update(mid+1, en, 2*nd+1, l, r, val); seg[nd]=max(seg[2*nd], seg[2*nd+1]); } ll query(ll st, ll en, ll nd, ll l, ll r){ if(lazy[nd]!=0){ ll temp=lazy[nd]; lazy[nd]=0; seg[nd]+=temp; if(st!=en){ lazy[2*nd]+=temp; lazy[2*nd+1]+=temp; } } if(st>r || en<l){ return -inf; } if(st>=l && en<=r){ return seg[nd]; } ll mid=(st+en)/2; return max(query(st, mid, 2*nd, l, r) , query(mid+1, en, 2*nd+1, l, r)); } int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); ll t; t=1; while(t--){ ll n, m, p; cin>>n>>m>>p; vector<vector<ll>> a(n, vector <ll> (2)); vector<vector<ll>> b(m, vector <ll> (2)); vector<vector<ll>> mon(p, vector <ll> (3)); l0(i, n){ cin>>a[i][0]>>a[i][1]; } sorted(a); l0(i, m){ cin>>b[i][0]>>b[i][1]; val[b[i][0]]=max(val[b[i][0]], -b[i][1]); } l0(i, p){ cin>>mon[i][0]>>mon[i][1]>>mon[i][2]; } sorted(mon); queue <vector<ll>> q; l0(i, p){ q.push(mon[i]); } ll ans=-inf; build(1, maxn-1, 1); l0(i, n){ while(!q.empty() && q.front()[0]<a[i][0]){ vector <ll> v=q.front(); q.pop(); update(1, maxn-1, 1, v[1]+1, maxn-1, v[2]); } ans=max(ans, query(1, maxn-1, 1, 1, maxn-1)-a[i][1]); } cout<<ans; nl } return 0; }
cpp
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
#include <bits/stdc++.h> #include<iostream> #include <conio.h> typedef long long ll; #define vec vector #define pb push_back #define lop(n) for(int i=0;i<n;i++) #define lopj(n) for(int j=0;j<n;j++) #define lop1(n) for(int i=1;i<=n;i++) #define lopj1(n) for(int j=1;j<=n;j++) #define pf push_front #define ppb pop_back #define ppf pop_front #define yes(f) cout << (f?"YES":"NO") << endl #define fast ios::sync_with_stdio(NULL);cin.tie(0);cout.tie(0) using namespace std; ll t, n, k, x , res , freq[100]; bool ans; vec<ll> a; bool getX(ll n) { ll index = 0; while(n) { if(n%k > 1) return false; if(n%k) freq[index]++; n /= k; index++; } return true; } int main() { cin >> t; while(t--) { a.clear(); ans = true; res = 0; memset(freq , 0 , sizeof freq); cin >> n >> k; lop(n) { cin >> x; if(!getX(x)) ans = false; } lop(100) { if(freq[i] > 1) ans = false; } yes(ans); } return 0; }
cpp
1310
E
E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function ff of multiset aa as the multiset of number of occurences of every number, that is present in aa.E.g., f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}f({5,5,1,2,5,2,3,3,9,5})={1,1,2,2,4}.Let's define fk(a)fk(a), as applying ff to array aa kk times: fk(a)=f(fk−1(a)),f0(a)=afk(a)=f(fk−1(a)),f0(a)=a. E.g., f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}f2({5,5,1,2,5,2,3,3,9,5})={1,2,2}.You are given integers n,kn,k and you are asked how many different values the function fk(a)fk(a) can have, where aa is arbitrary non-empty array with numbers of size no more than nn. Print the answer modulo 998244353998244353.InputThe first and only line of input consists of two integers n,kn,k (1≤n,k≤20201≤n,k≤2020).OutputPrint one number — the number of different values of function fk(a)fk(a) on all possible non-empty arrays with no more than nn elements modulo 998244353998244353.ExamplesInputCopy3 1 OutputCopy6 InputCopy5 6 OutputCopy1 InputCopy10 1 OutputCopy138 InputCopy10 2 OutputCopy33
[ "dp" ]
#include <bits/stdc++.h> using namespace std; #define fo(x) freopen(#x".in", "r", stdin); freopen(#x".out", "w", stdout); typedef long long ll; template <typename T> void rd(T &x) { x = 0; char c; bool f = false; while (c = getchar(), !isdigit(c)) f |= (c == '-'); while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); if (f) x *= -1; } const int maxn = 2020 + 5; const int mod = 998244353; int qpow(int a, int b) { int c = 1; for (; b; b >>= 1, a = (ll)a * a % mod) if (b & 1) c = (ll)c * a % mod; return c; } int inv(int x) { return qpow(x, mod - 2); } int n, k; namespace Solve1 { int f[maxn], A; void solve() { f[0] = 1; for (int i = 1; i <= n; ++i) for (int j = i; j <= n; ++j) (f[j] += f[j - i]) %= mod; for (int i = 1; i <= n; ++i) (A += f[i]) %= mod; printf("%d", A); } } namespace Solve2 { int f[maxn], A; void solve() { f[0] = 1; for (int i = 1, u; (u = i * (i + 1) / 2) <= n; ++i) for (int j = u; j <= n; ++j) (f[j] += f[j - u]) %= mod; for (int i = 1; i <= n; ++i) (A += f[i]) %= mod; printf("%d", A); } } int A; vector<int> v, p, q; bool chk() { p = v; for (int _ = 0; _ < k - 2; ++_) { for (int i = 0; i < (int)p.size(); ++i) for (int j = 0; j < p[i]; ++j) q.push_back(i + 1); p = move(q), q.clear(), reverse(p.begin(), p.end()); ll C = 0; for (int i = 0; i < (int)p.size(); ++i) C += ll(i + 1) * p[i]; if (C > n) return false; } return true; } void dfs(int p) { if (!chk()) return; ++A; for (int i = p; i >= 1; --i) { v.push_back(i); dfs(i); v.pop_back(); } } void solve() { dfs(64); printf("%d", A - 1); } int main() { // fo(function) rd(n), rd(k); if (k == 1) return Solve1::solve(), 0; if (k == 2) return Solve2::solve(), 0; solve(); return 0; }
cpp
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
// LUOGU_RID: 100584762 #include<bits/stdc++.h> //#include<type_traits> //#include<debug/debug.h> //#include<bits/stl_pair.h> //#pragma GCC optimize(1) //#pragma GCC optimize(2) //#ifndef _STL_ALGOBASE_H //#if __cplusplus > 201703L //#define _STL_ALGOBASE_H 1 //#if __cplusplus >= 201103L //#include<bits/c++config.h> //#include<ext/type_traits.h> //#include<bits/functexcept.h> //#include<bits/stl_iterator.h> //#include<ext/numeric_traits.h> //#include<bits/concept_check.h> //#include<bits/predefined_ops.h> //#include<bits/cpp_type_traits.h> //#include<bits/move.h> // For std::swap //#include<bits/stl_iterator_base_types.h> //#include<bits/stl_iterator_base_funcs.h> using namespace std; //#define int long long //#define ll long long int //#define db double //#define ld long double #define ull unsigned long long typedef long long ll; //#define I using //#define AK namespac //#define IOI std //I AK IOI; const int N=2e5+5; int n,k,d[N],ans[N]; vector<int>v[N],p[N]; bool cmp(int x,int y){ return x>y; } void dfs(int x,int fa,int col){ int now=1; for(int i=0;i<v[x].size();i++) if(v[x][i]!=fa){ if(col==now&&now<d[k+1]) now++; ans[p[x][i]]=now; dfs(v[x][i],x,now); if(now<d[k+1]) now++; } } int main(){ scanf("%d%d",&n,&k); for(int i=1,x,y;i<n;i++) scanf("%d%d",&x,&y),v[x].push_back(y),p[x].push_back(i),v[y].push_back(x),p[y].push_back(i),d[x]++,d[y]++; sort(d+1,d+n+1,cmp); printf("%d\n",d[k+1]); dfs(1,-1,-1); for(int i=1;i<n;i++) printf("%d ",ans[i]); return 0; }
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 <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <ranges> #include <set> #include <string> #include <vector> using namespace std; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } #ifdef DUPA #define debug(x...) \ cerr << "[" << #x << "] = ["; \ _print(x) #else #define debug(x, ...) #endif typedef long long LL; // HMMMM #define int LL typedef pair<int, int> PII; typedef pair<int, PII> PIII; const int INF = 1e18 + 1; int g(deque<PII> left, deque<PII> right) { sort(all(left)); sort(all(right)); int res = 0; int sum = 0; for (auto [y, _] : right) sum += y; for (auto [x, d1] : left) { assert(d1 <= 0); while (!right.empty()) { auto [y, d2] = right.front(); if (d1 == 0 && d2 == 0) { sum -= y; right.pop_front(); } else if (!(y > x)) { sum -= y; right.pop_front(); } else break; } res += sum - right.size() * x; } return res; } void add(vector<int> &tree, int k, int x) { int n = tree.size() - 1; k = n - k; assert(k >= 1); while (k <= n) { tree[k] += x; k += k & -k; } } int get(vector<int> &tree, int k) { int n = tree.size() - 1; k = n - k; assert(k >= 1); int s = 0; while (k >= 1) { s += tree[k]; k -= k & -k; } return s; } int f(deque<PII> right) { sort(all(right)); map<int, int> re_map; for (auto [_, y] : right) re_map[y] = 0; int idx = 0; for (auto &[_, y] : re_map) y = idx++; for (auto &[_, y] : right) y = re_map[y]; int sz = re_map.size() + 2; vector<int> sum(sz, 0); vector<int> cnt(sz, 0); for (auto [y, d2] : right) { add(sum, d2, y); add(cnt, d2, 1); } int res = 0; for (auto [x, d1] : right) { add(sum, d1, -x); add(cnt, d1, -1); res += get(sum, d1) - x * get(cnt, d1); } return res; } int solve() { int n; vector<PII> dupa; cin >> n; dupa.resize(n); for (int i = 0; i < n; i++) cin >> dupa[i].first; for (int i = 0; i < n; i++) cin >> dupa[i].second; deque<PII> left, right; for (auto x : dupa) { if (x.second < 0) left.push_back(x); if (x.second >= 0) right.push_back(x); } int res = g(left, right); for (auto &[x, y] : left) { x *= -1; y *= -1; } res += f(left); res += f(right); return res; } #undef int int main() { ios::sync_with_stdio(false); cin.exceptions(cin.failbit); cin.tie(0); int t = 1; #ifdef DUPA cin >> t; #endif for (int i = 0; i < t; i++) cout << solve() << endl; }
cpp
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
#include<bits/stdc++.h> #define ll long long using namespace std; void solve(){ int n; cin >> n; int x = 0, y = 0; vector<pair<int,int>>kor(n); for(int i = 0; i < n; ++i){ cin >> kor[i].first >> kor[i].second; } sort(kor.begin(),kor.end()); string ans = ""; for(int i = 0; i < n; ++i){ if(x > kor[i].first || y > kor[i].second){ cout << "NO\n"; return; } else { int t1 = abs(kor[i].first - x); int t2 = abs(kor[i].second - y); while(t1--){ ans.push_back('R'); } while(t2--){ ans.push_back('U'); } x = kor[i].first; y = kor[i].second; } } cout << "YES\n" << ans << '\n'; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int TC = 1; cin >> TC; while(TC--){ solve(); } }
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> using namespace std; const int N=1e6+10,R=1e6; const int mod=1e9+7; typedef long long LL; LL c[N][2],n; int lowbit(int x){ return x&(-x); } pair<LL,LL> query(int x){ pair<LL,LL> res={0,0}; for(int i=x;i>=1;i-=lowbit(i)){ res.first+=c[i][0]; res.second+=c[i][1]; } return res; } void update(int x,int k){ for(int i=x;i<=n;i+=lowbit(i)){ c[i][0]+=k; c[i][1]++; } } void solve() { cin>>n; vector<pair<int,int> >a(n); vector<int>b(n); for(int i=0;i<n;i++)cin>>a[i].first; for(int i=0;i<n;i++){ cin>>a[i].second; b[i]=a[i].second; } sort(b.begin(),b.end()); for(int i=0;i<n;i++)a[i].second=lower_bound(b.begin(),b.end(),a[i].second)-b.begin()+1; long long ans=0; sort(a.begin(),a.end()); for(int i=0;i<n;i++){ ans+=query(a[i].second).second*a[i].first-query(a[i].second).first; update(a[i].second,a[i].first); } cout<<ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T=1; while(T--) { solve(); } return 0; } /* */
cpp
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; #define ll long long #define fr(m) for(int i=0; i<m; i++) #define frr(n) for(int i=n; i>=0; i--) #define yes cout<<"YES"<<"\n" #define no cout<<"NO"<<"\n" #define vr vector<ll> #define all(x) x.begin(),x.end() #define pb push_back #define maxof(x) *max_element(x.begin(),x.end()); #define minof(x) *min_element(x.begin(),x.end()); #define srt(x) sort(x.begin(), x.end()) #define dsrt(x) sort(x.begin(), x.end(),greater<ll>()) #define _a-z_ "abcdefghijklmnopqrstuvwxyz" #define SuperFast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define sp " " #define ln "\n" #define fi first #define se second using pii = pair<int, int>; using pll = pair<ll, ll>; const int mxn=1e5+9; const int N=1e5+5; const int mod=1e9+7; //Check Prime or not???!!! bool prime(int n){ if(n<2)return false; if(n<=3)return true; if(n%2==0)return false; for(int i=3;i*i<=n;i+=2){ if(n%i==0) return false; } return true; } //Greatest Common Divisor--> GCD ll gcd (int p, int q) { if (q == 0) return p; return gcd(q, p % q); } //Least Common Multiple--> LCM ll lcm(int p, int q){ return (p / gcd(p, q))*q; } void testCase(){ string s;cin>>s; int l=0, mx=0; fr(s.size()){ if(s[i]=='L'){ l++; mx=max(mx,l); } else l=0; } cout<<mx+1<<ln; } int main(){ SuperFast; //int t=1; int t;cin>>t; while(t--){ testCase(); } }
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" ]
#include <bits/stdc++.h> #define ll long long #define pb push_back using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; int l, r; switch(n%4) { case 0: l = n/2+1; r = n/2-1; break; case 1: l = n/2+1; r = n/2; break; case 2: l = n/2+2; r = n/2-2; break; case 3: l = n/2; r = n/2+1; } if(n==2) { l = 1; r = 1; } vector<vector<int>> L(l+1, vector<int>(26, 0)), R(r+1, vector<int>(26, 0)), N(n+1, vector<int>(26, 0)); vector<string> left, right, all; if(l>1) { cout << "? 1 " << l << "\n"; cout.flush(); string x; for(int i=0; i<l*(l+1)/2; i++) { cin >> x; for(char c: x) { L[x.size()][c-97]++; } } vector<int> prev(26, 0); for(int s=1; s<=(l+1)/2; s++) { string S; vector<int> temp(26, 0); for(int i=0; i<26; i++) { temp[i] += L[1][i] + L[s][i] - L[s+1][i] - prev[i]; prev[i] += temp[i]; while(temp[i]-->0) S += (char) 97+i; } //cout << "! " << S << "\n"; left.pb(S); } } else if(l==1) { cout << "? 1 " << l << "\n"; cout.flush(); string x; cin >> x; left.pb(x+x); } if(r>1) { cout << "? " << l + 1 << " " << n << "\n"; cout.flush(); string x; for(int i=0; i<r*(r+1)/2; i++) { cin >> x; for(char c: x) { R[x.size()][c-97]++; } } vector<int> prev(26, 0); for(int s=1; s<=(r+1)/2; s++) { string S; vector<int> temp(26, 0); for(int i=0; i<26; i++) { temp[i] += R[1][i] + R[s][i] - R[s+1][i] - prev[i]; prev[i] += temp[i]; while(temp[i]-->0) S += (char) 97+i; } //cout << "! " << S << "\n"; right.pb(S); } } else if(r==1) { cout << "? " << l + 1 << " " << n << "\n"; cout.flush(); string x; cin >> x; right.pb(x+x); } if(n>1) { cout << "? 1 " << n << "\n"; cout.flush(); string x; for(int i=0; i<n*(n+1)/2; i++) { cin >> x; for(char c: x) { N[x.size()][c-97]++; } } vector<int> prev(26, 0); for(int s=1; s<=(n+1)/2; s++) { string S; vector<int> temp(26, 0); for(int i=0; i<26; i++) { temp[i] += N[1][i] + N[s][i] - N[s+1][i] - prev[i]; prev[i] += temp[i]; while(temp[i]-->0) S += (char) 97+i; } //cout << "! " << S << "\n"; all.pb(S); } } else if(n==1) { cout << "? 1 " << n << "\n"; cout.flush(); string x; cin >> x; all.pb(x+x); } int now = (l+1)/2; string ans(n, ' '); ans[now-1] = left[now-1][0]; for(int i=0; i<n; i++) { //cout << now << " " << ans[now-1] << "\n"; if(i%2==0) { now = n + 1 - now; if(all[min(now, n+1-now)-1][0]==ans[n-now]) ans[now-1] = all[min(now, n+1-now)-1][1]; else ans[now-1] = all[min(now, n+1-now)-1][0]; } else if(now<=l) { now = l + 1 - now; if(left[min(now, l+1-now)-1][0]==ans[l-now]) ans[now-1] = left[min(now, l+1-now)-1][1]; else ans[now-1] = left[min(now, l+1-now)-1][0]; } else { now = n + l + 1 - now; if(right[min(now, n+l+1-now)-l-1][0]==ans[n+l-now]) ans[now-1] = right[min(now, n+l+1-now)-l-1][1]; else ans[now-1] = right[min(now, n+l+1-now)-l-1][0]; } } cout << "! " << ans << "\n"; cout.flush(); } /* 5 a as ask s sk k b y by askby askb skby ask skb kby as sk kb by a s y k b */
cpp
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
#include "bits/stdc++.h" using namespace std; #define all(x) begin(x),end(x) template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; } #define debug(a) cerr << "(" << #a << ": " << a << ")\n"; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pi; const int mxN = 1e5+1, oo = 1e9; string str; vector<array<int,3>> es; string hidden = "xasdungo"; void query(int l, int r) { cout << "? " << l+1 << ' ' << r+1 << endl; int len = r-l+1; vector<int> v(len+1); for(int i=0;i<len*(len+1)/2;++i) { string s; cin >> s; auto& w = v[s.size()]; for(auto c : s) w+=c; } // for(int i=l;i<=r;++i) for(int j=i;j<=r;++j) { // string s = hidden.substr(i,j-i+1); // auto& w = v[s.size()]; // for(auto c : s) w+=c; // } // take biggest string, do it times two, subtract out those two? vi res = {}; for(int i=0;i<(len+1)/2;i++) { int ans=-v[len-i-1]; for(int j=0;j<i;++j) { ans+=res[j]*(j+1 - (i+2)); } ans += v[len]*(i+2); res.push_back(ans); } for(int i=0;i<len/2;++i) { es.push_back({l+i,r-i,res[i]}); } if(len%2==1) { str[(l+r)/2]=res.back()/2; } } int main() { int n; cin >> n; str.resize(n,'?'); if(n==1) { query(0,0); } else if(n==2) { query(0,0); query(0,1); } else { query(0,(n+1)/2 -1); query(0,(n+1)/2 -2); query(0,n-1); } vector<vector<pi>> adj(n); for(auto& [u,v,w] : es) adj[u].push_back({v,w}),adj[v].push_back({u,w}); for(int i=0;i<n;++i) if(str[i]!='?') { auto dfs = [&](auto&& self, int at) -> void { for(auto [to,w] : adj[at]) if(str[to]=='?') { str[to]=w-str[at]; self(self,to); } }; dfs(dfs,i); break; } cout << "! " << str << endl; }
cpp
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
#include<bits/stdc++.h> using namespace std; #define int long long const int N = 2e5 + 10; int sum[N][26]; signed main(){ std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); string str; cin >> str; int n = str.size(); str = " " + str; for(int i = 1; i <= n; i++){ int k = str[i] - 'a'; sum[i][k]++; for(int j = 0; j < 26; j++){ sum[i][j] += sum[i - 1][j]; } } int q; cin >> q; while(q--){ int l, r; cin >> l >> r; int cnt = 0; bool flag = false; if(l == r) flag = true; for(int i = 0; i < 26; i++){ if(sum[r][i] - sum[l - 1][i]) cnt++; } if(cnt == 2 && str[l] != str[r]) flag = true; if(cnt > 2) flag = true; if(flag) cout << "Yes\n"; else cout << "No\n"; } return 0; }
cpp
13
D
D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500; 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7
[ "dp", "geometry" ]
#include<bits/stdc++.h> using namespace std; using ll=long long; const ll maxN=2e5; #define taskname "codeforce" #define int long long struct pt { ll a,b; bool operator<(const pt&o) { return a<o.a; } }x[maxN],d[maxN]; struct Tvector { ll u,v; Tvector(pt a, pt b) { u=a.a-b.a; v=a.b-b.b; } }; ll mul(Tvector a, Tvector b) { return abs(a.u*b.v-b.u*a.v); } ll s(pt a,pt b,pt c,pt d) { Tvector x1(a,b); Tvector x2(a,c); Tvector x3(a,d); return mul(x1,x2)+mul(x2,x3); } bool check(pt x,pt a,pt b,pt c,pt d) { Tvector x1(x,a); Tvector x2(x,b); Tvector x3(x,c); Tvector x4(x,d); if(mul(x1,x2)+mul(x2,x3)+mul(x3,x4)+mul(x4,x1)==s(a,b,c,d)) return true; return false; } ll dp[501][501],n,m; bool c(ll i,ll j,ll k) { return dp[i][j]+dp[j][k]==dp[i][k]; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); ///freopen(taskname".inp","r",stdin); ///freopen(taskname".out","w",stdout); srand(time(0)); cin >> n >> m; ll del=0; for(int i=1;i<=n;i++) cin >> x[i].a >> x[i].b,del=min(del,x[i].b); for(int i=1;i<=m;i++) cin >> d[i].a >> d[i].b; sort(x+1,x+n+1); del=abs(del); //cout << '\n'; for(int i=1;i<=n;i++) x[i].b+=del;//,cout <<x[i].a<<' '<<x[i].b<<'\n';; for(int i=1;i<=m;i++) d[i].b+=del;//cout <<d[i].a<<' '<<d[i].b<<'\n';; for(int i=1;i<=n;i++) { dp[i][i]=0; for(int j=i+1;j<=n;j++) { for(int k=1;k<=m;k++) { if(d[k].b<0) continue; if(d[k].a==x[i].a&&check(d[k],x[i],x[j],(pt){x[j].a,0},(pt){x[i].a,0})==1) continue; dp[i][j]+=check(d[k],x[i],x[j],(pt){x[j].a,0},(pt){x[i].a,0}); } } } ll ans=0; for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { for(int k=j+1;k<=n;k++) { if(c(i,j,k)) ans++; } } } cout << ans; }
cpp