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
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
#include<bits/stdc++.h> using namespace std; struct hashFunction { size_t operator()(const vector<string> &myVector) const { std::hash<string> hasher; size_t answer = 0; for (string i : myVector) { answer ^= hasher(i) + 0x9e3779b9 + (answer << 6) + (answer >> 2); } return answer; } }; int solve() { int n,k,count=0; cin >> n >> k; unordered_map<string , int> m; unordered_set<vector<string>, hashFunction> s; for(int i = 0; i < n; i++){ string temp1; cin >> temp1; m[temp1]++; } for(auto it = m.begin(); it != m.end(); ++it){ auto xyz=it; for(auto lt = ++xyz; lt != m.end(); ++lt){ string s1 = it->first; string s2 = lt->first; string temp = ""; for(int a = 0; a < k; a++){ if(s1[a] == s2[a]){ temp = temp + s1[a]; } else if((s1[a] == 'S' && s2[a] == 'T') || (s1[a] == 'T' && s2[a] == 'S')){ temp = temp + "E"; } else if((s1[a] == 'S' && s2[a] == 'E') || (s1[a] == 'E' && s2[a] == 'S')){ temp = temp + "T"; } else if((s1[a] == 'E' && s2[a] == 'T') || (s1[a] == 'T' && s2[a] == 'E')){ temp = temp + "S"; } } if(m.find(temp)!=m.end()){ vector<string> v; v.push_back(s1); v.push_back(s2); v.push_back(temp); sort(v.begin(),v.end()); s.insert(v); } } } cout << s.size() << "\n"; return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); }
cpp
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define ld long double #define el "\n" #define matrix vector<vector<int>> #define pt complex<ld> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ordered_multiset tree<ll, null_type,less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> using namespace __gnu_pbds; using namespace std; const ll N = 2e5 + 7, LOG = 20; const ld pi = acos(-1); const ll mod = 1e9 + 7; int dx[] = {0, -1, 0, 1, -1, 1, -1, 1}; int dy[] = {-1, 0, 1, 0, 1, -1, -1, 1}; ll n, m, k, x, y; int a[N]; void dowork() { cin >> n; int ans = 0, cnt = 0; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i <= n; i++) { if (a[i]) { cnt++; } else { cnt = 0; } ans = max(ans, cnt); } for (int i = 1; i <= n; i++) { if (a[i]) { cnt++; } else { break; } ans = max(ans, cnt); } ans = min(ans, (int) n); cout << ans << el; } int main() { fast //freopen("cowland.in", "r", stdin); //freopen("cowland.out", "w", stdout); int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { dowork(); } }
cpp
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
#include<bits/stdc++.h> using namespace std; int64_t n,a,b,i; map<int,int64_t> m; main(){ cin >> n; while(i++<n) { cin >> b; m[b-i]+=b; a=max(a,m[b-i]); } cout << a; }
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int N, M; cin >> N >> M; vector<int> A(N); for (auto &a : A) cin >> a; sort(A.rbegin(), A.rend()); map<int, int> cnt; vector<int> nums; int res = 1; for (auto a : A) { a %= M; if (cnt[a]) res = 0; else { nums.push_back(a); cnt[a]++; } } for (int i = 0; i < nums.size(); ++i) { for (int j = i+1; j < nums.size(); ++j) { res *= (nums[i] - nums[j]); res %= M; } } if (res < 0) res += M; cout << res << endl; 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<iostream> #include<cstring> #include<set> #include<algorithm> using namespace std; using LL = long long; void ask(int l, int r){ cout << "? " << l << ' ' << r << endl; } int main(){ #ifdef LOCAL freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif cin.tie(0); cout.tie(0); ios::sync_with_stdio(0); int n; cin >> n; if (n == 1){ ask(1, 1); string s; cin >> s; cout << "! " << s << '\n'; return 0; } multiset<string> s; ask(1, n); for(int i = 1; i <= n * (n + 1) / 2; i++){ string str; cin >> str; sort(str.begin(), str.end()); s.insert(str); } ask(1, n - 1); for(int i = 1; i <= n * (n - 1) / 2; i++){ string str; cin >> str; sort(str.begin(), str.end()); s.erase(s.find(str)); } vector<array<int, 26> > c(n + 1); string ans; for(auto str : s){ int x = str.size(); for(auto u : str) c[x][u - 'a']++; } for(int i = 1; i <= n; i++){ for(int j = 0; j < 26; j++) if (c[i][j] == c[i - 1][j] + 1){ ans += char('a' + j); break; } } reverse(ans.begin(), ans.end()); cout << "! " << ans << endl; }
cpp
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3 13 35 77 OutputCopy1001InputCopy6 1 2 4 8 16 32 OutputCopy32
[ "binary search", "combinatorics", "number theory" ]
#include<bits/stdc++.h> using namespace std; const int maxn=1e5+9; const int mx=1e5; int mob[maxn]; vector<int>d[maxn]; int turn[maxn]; int cnt[maxn]; int coprime(int x){ int ans=0; for (auto v:d[x]){ ans+=mob[v]*cnt[v]; } return ans; } signed main(){ ios_base::sync_with_stdio(NULL); cin.tie(nullptr); //freopen("usaco.INP","r",stdin); //freopen("usaco.OUT","w",stdout); mob[1]=1; for (int i=1;i<=mx;i++){ for (int j=i*2;j<=mx;j+=i){ mob[j]-=mob[i]; } } for (int i=1;i<=mx;i++){ if (mob[i]!=0){ for (int j=i;j<=mx;j+=i){ d[j].push_back(i); } } } int n; cin>>n; long long ans=0; for (int i=1;i<=n;i++){ int x; cin>>x; if (turn[x])ans=max(ans,1ll*x); turn[x]=1; } for (int i=1;i<=mx;i++){ vector<int>suzy; for (int j=(mx/i);j>=1;j--){ if (turn[j*i]==0)continue; int cop=coprime(j); while (cop){ int u=suzy.back(); suzy.pop_back(); if (__gcd(u,j)==1){ ans=max(ans,1ll*u*j*i); cop--; } for (auto v:d[u]){ cnt[v]--; } } for (auto v:d[j])cnt[v]++; suzy.push_back(j); } while (!suzy.empty()){ int u=suzy.back(); for (auto v:d[u])cnt[v]--; suzy.pop_back(); } } cout<<ans; }
cpp
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int sum = 0; bool odd = false, even = false; for (int i = 0; i < n; ++i) { int x; cin >> x; sum += x; odd |= x % 2 != 0; even |= x % 2 == 0; } if (sum % 2 != 0 || (odd && even)) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
cpp
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
#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; const int maxM = 250000001; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,m;cin>>n>>m; int tot = 0; REP(i, n) { int x = i/2; tot += x; } if (tot < m) { cout<<-1<<"\n";return 0; } if (n <= 2) { REP(i, n) { cout<<i+1<<" "; }return 0; } bitset<maxM> covered; covered.reset(); vi curarr = {1,2}; while (m != 0) { int nxt = curarr.size(); int grp = nxt/2; //debug(grp); if (grp <= m) { curarr.push_back(curarr.back() + 1); m -= grp; } else { int tode = 2*m; int curmx = curarr.back(); int curlw = curmx - tode + 1; curarr.push_back(curmx + curlw); m = 0; } } debug(curarr); int curs = curarr.size(); covered[0] = 1; REP(i, curs) { covered[curarr[i]] = 1; REPL(j, i+1, curs) { int x = curarr[i] + curarr[j]; if (x < maxM) { covered[x] = 1; } } } int currentmex = -1; REP(i, maxM) { if (!covered[i]) { currentmex = i;break; } } assert(currentmex != -1); while ((int)curarr.size() != n) { //debug(currentmex); int y = currentmex; for (auto x: curarr) { covered[y+x] = 1; } covered[y] = 1; curarr.push_back(y); while (true) { currentmex++; if (!covered[currentmex])break; } } for (auto x: curarr) { cout<<x<<" "; } }
cpp
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
#pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; #define int long long int //bool prime[30007]; //vector<int> fact(200005); #define INF 1e9; #ifndef ONLINE_JUDGE #define debug(x) cerr<< #x <<"= "; _print(x);cerr<<endl; #else #define debug(x) #endif #define reverse(v) reverse(v.begin(),v.end()); #define ascending(v) sort(v.begin(),v.end()); #define descending(v) sort(v.rbegin(),v.rend()); void _print(string a) {cerr << a;} void _print(int a) {cerr << a;} void _print(char a) {cerr << a;} void _print(bool a) {cerr << a;} void _print(double a) {cerr << a;} void _print(float a) {cerr << a;} template<class T, class V> void _print(unordered_map<T, V> m) { cerr << "\n"; for (auto &pr : m) { cerr << pr.first << "->"; cerr << pr.second << "\n"; } } template<class T, class V> void _print(map<T, vector<V>> m) { cerr << "\n"; for (auto &pr : m) { cerr << pr.first << "->"; for (auto i : pr.second) { _print(i); cerr << " "; } cerr << "\n"; } } template<class T, class V> void _print(map<T, V> m) { cerr << "\n"; for (auto &pr : m) { _print(pr.first); cerr << "->"; _print(pr.second); cerr << "\n"; } } template<class T> void _print(vector<T> v1) { cerr << "["; for (T i : v1) { _print(i); cerr << " "; } cerr << "]"; } template<class T, class V> void _print(vector<pair<T, V>> v1) { cerr << "["; for (auto &pr : v1) { cerr << "{"; _print(pr.first); cerr << " "; _print(pr.second); cerr << "}"; cerr << " "; } cerr << "]"; } template<class T> void _print(vector<vector<T>> v1) { cerr << "\n"; for (auto &vec : v1) { for (T i : vec) { _print(i); cerr << " "; } cerr << "\n"; } } template<class T> void _print(vector<set<T>> v1) { for (auto &vec : v1) { for (T i : vec) { _print(i); cerr << " "; } cerr << "\n"; } } template<class T> void _print(set<T> s1) { cerr << "["; for (T i : s1) { _print(i); cerr << " "; } cerr << "]"; } template<class T> void _print(queue<T> q1) { cerr << "["; while (!q1.empty()) { T i = q1.front(); q1.pop(); cerr << i; cerr << " "; } cerr << "]"; } template<class T> void _print(stack<T> st1) { cerr << "["; while (!st1.empty()) { _print(st1.top()); st1.pop(); cerr << " "; } cerr << "]"; } template<class T> void _print(list<T> lis1) { cerr << "["; for (T i : lis1) { _print(i); cerr << " "; } cerr << "]"; } template<class T> void _print(deque<T> lis1) { cerr << "["; for (T i : lis1) { _print(i); cerr << " "; } cerr << "]"; } template<class T, class V> void _print(deque<pair<T, V>> lis1) { cerr << "["; for (auto i : lis1) { cerr << "{"; _print(i.first); cerr << " "; _print(i.second); cerr << "}"; } cerr << "]"; } template<class T> void _print(priority_queue<T> pq1) { cerr << "["; for (T i : pq1) { _print(i); cerr << " "; } cerr << "]"; } int moduloMultiplication(int a, int b, int mod) { // Initialize result int res = 0; // Update a if it is more than // or equal to mod a %= mod; while (b) { // If b is odd, add a with result if (b & 1) res = (res + a) % mod; // Here we assume that doing 2*a // doesn't cause overflow a = (2 * a) % mod; b >>= 1; // b = b / 2 } return res; } int modpower(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } int power(int x, int y) { int res = 1; // Initialize result if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { if (y & 1) res = (res * x); // y must be even now y = y >> 1; // y = y/2 x = (x * x); } return res; } // C++ function for extended Euclidean Algorithm int gcdExtended(int a, int b, int* x, int* y); // Function to find modulo inverse of b. It returns // -1 when inverse doesn't exists int modInverse( int b, int m) { int x, y; // used in extended GCD algorithm int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x % m + m) % m; } // C function for extended Euclidean Algorithm (used to // find modular inverse. int gcdExtended(int a, int b, int* x, int* y) { // Base Case if (a == 0) { *x = 0, *y = 1; return b; } // To store results of recursive call int x1, y1; int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd; } // Function to compute a/b under modlo m int modDivide( int a, int b, int m) { a = a % m; int inv = modInverse(b, m); if (inv == -1) // cout << "Division not defined"; return 0; else return (inv * a) % m; } // Function to calculate nCr % p // int nCr(int n, int r, int p) // { // int calc1 = fact[n]; // int calc2 = ((fact[n - r] % p) * (fact[r] % p)) % p; // return modDivide(calc1, calc2, p); // } // void SieveOfEratosthenes(int n) // { // // Create a boolean array // // "prime[0..n]" and initialize // // all entries it as true. // // A value in prime[i] will // // finally be false if i is // // Not a prime, else true. // memset(prime, true, sizeof(prime)); // for (int p = 2; p * p <= n; p++) // { // // If prime[p] is not changed, // // then it is a prime // if (prime[p] == true) // { // // Update all multiples // // of p greater than or // // equal to the square of it // // numbers which are multiple // // of p and are less than p^2 // // are already been marked. // for (int i = p * p; i <= n; i += p) // prime[i] = false; // } // } // } int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not // present in array return -1; } // void factorial(int p) // { // fact[0] = 1; // fact[1] = 1; // for (int i = 2; i < fact.size(); i++) // { // fact[i] = (i * fact[i - 1]) % p; // } //} int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } int ceil(int a, int x) { if (a % x == 0) return a / x; else return a / x + 1; } int countBits(int n) { int count = 0; while (n) { count++; n >>= 1; } return count; } bool isPower(int x, int y) { int res1 = log2(y) / log2(x); double res2 = log2(y) / log2(x); // compare to the result1 or result2 both are equal return (res1 == res2); } bool isPerfectSquare(int x) { // Find floating point value of // square root of x. if (x >= 0) { long long sr = sqrt(x); // if product of square root //is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false; } //-------------------------------------------------------------------------------------------------------------------------------------------- const int mod = 998244353; const int M = 1e9 + 7; const int inf = 1e18; void solve() { string s; cin >> s; int n = s.length(); map<char, vector<int>> m; for (int i = 0; i < n; i++) { m[s[i]].push_back(i); } debug(m); int ans = INT_MIN; for (auto it = m.begin(); it != m.end(); it++) { auto it1 = it; it1++; debug(it->first); vector<int> &v1 = it->second; for (; it1 != m.end(); it1++) { int count = 0; debug(it1->first); int count1 = 0; vector<int> &v2 = it1->second; debug(v2) for (int i = 0; i < v1.size(); i++) { auto at = lower_bound(v2.begin(), v2.end(), v1[i]); if (at != v2.end()) { int indx = (int)(at - v2.begin()); debug(indx) count += (v2.size() - indx); } } for (int i = 0; i < v2.size(); i++) { auto at = lower_bound(v1.begin(), v1.end(), v2[i]); if (at != v1.end()) { int indx = (int)(at - v1.begin()); count1 += (v1.size() - indx); } } debug(count) debug(count1) ans = max(ans, max(count, count1)); } int val = it->second.size(); int val1 = (val * (val - 1ll)) / 2ll; ans = max(ans, max(val, val1)); } cout << ans << "\n"; return; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("Error2.txt", "w", stderr); #endif//ONLINE_JUDGE int T = 1; //cin >> T; int t = 1; //SieveOfEratosthenes(100005); // debug(primes); //cout << (char)('z' - 25) << "\n"; //factorial(mod); while (T--) { cerr << T << "____________________________________" << "\n"; //cout << "Case #" << t << ": "; solve(); t++; } }
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" ]
// LUOGU_RID: 95985746 #include<bits/stdc++.h> using namespace std; #define pb push_back #define ppb pop_back #define pf push_front #define ppf pop_front #define eb emplace_back #define ef emplace_front #define lowbit(x) (x & (-x)) #define ti chrono::system_clock::now().time_since_epoch().count() #define Fin(x) freopen(x, "r", stdin) #define Fout(x) freopen(x, "w", stdout) #define Fio(x) Fin(x".in"), Fout(x".out"); // #define SGT // #define int long long // int main() -> signed // #define PAIR #define ll long long #ifdef PAIR #define fi first #define se second #endif #ifdef SGT #define lson (p << 1) #define rson (p << 1 | 1) #define mid ((l + r) >> 1) #endif const int maxn = 2022, mod = 998244353; int n, k, f[maxn], ans; vector<int> cur, a, b; bool check(){ a = cur; // printf("checking "); // for(int i : a) printf("%d ", i); // puts(""); for(int _ = 1; _ < k; _++){ reverse(a.begin(), a.end()); ll sum = 0; for(int i = 0; i < (int)a.size(); i++) sum += 1ll * (i + 1) * a[i]; if(sum > n) return 0; if(_ == k - 1) break; b.clear(); for(int i = 0; i < (int)a.size(); i++) for(int j = 1; j <= a[i]; j++) b.pb(i + 1); a = b; } return 1; } void dfs(int dep, int x){ // printf("dfs %d %d\n", dep, x); for(int i = x; ; i++){ cur.pb(i); int res = check(); // printf("%d - %d\n", i, res); if(res) ans++, dfs(dep + 1, i); cur.ppb(); if(!res) return; } } signed main(){ scanf("%d%d", &n, &k), f[0] = 1; if(k == 1){ for(int i = 1; i <= n; i++) for(int j = i; j <= n; j++) f[j] = (f[j] + f[j - i]) % mod; for(int i = 1; i <= n; i++) ans = (ans + f[i]) % mod; }else if(k == 2){ for(int i = 1; i * (i + 1) / 2 <= n; i++) for(int j = i * (i + 1) / 2; j <= n; j++) f[j] = (f[j] + f[j - i * (i + 1) / 2]) % mod; for(int i = 1; i <= n; i++) ans = (ans + f[i]) % mod; }else dfs(1, 1); printf("%d\n", ans); return 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; void res(){ long long a,c = 0; cin>>a; long long n[a]; for( long long i = 1 ; i <= a ; i++ ){ cin>>n[i]; c+=(n[i]%2); } if( c==a || c==0) { cout<<"YES"; } else{ cout<<"NO"; } cout<<endl; } int main(){ long long r; cin>>r; while(r--){ res(); } return 0; }
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#include <bits/stdc++.h> using namespace std; #define int long long int void solve() { int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(3)); for (int i = 0; i < n; i++) cin >> a[i][0] >> a[i][1] >> a[i][2]; // sort(a.begin(), a.end()); int lt = m, ht = m; int prvt = 0; for (int i = 0; i < n; i++) { int ftime = (a[i][0] - prvt); lt -= ftime; ht += ftime; if (lt > a[i][2] || ht < a[i][1]) { cout << "NO"; // cout << " -> " << i; return; } lt = max(lt, a[i][1]); ht = min(ht, a[i][2]); prvt = a[i][0]; } cout << "YES"; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; cin >> t; while (t--) { solve(); cout << "\n"; } 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 <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; typedef tree< pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<pair<int, int>> p(n); for (auto &pnt : p) cin >> pnt.first; for (auto &pnt : p) cin >> pnt.second; sort(p.begin(), p.end()); ordered_set s; long long ans = 0; for (int i = 0; i < n; ++i) { int cnt = s.order_of_key(make_pair(p[i].second + 1, -1)); ans += cnt * 1ll * p[i].first; s.insert(make_pair(p[i].second, i)); } s.clear(); for (int i = n - 1; i >= 0; --i) { int cnt = int(s.size()) - s.order_of_key(make_pair(p[i].second - 1, n)); ans -= cnt * 1ll * p[i].first; s.insert(make_pair(p[i].second, i)); } cout << ans << endl; return 0; }
cpp
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vb = vector<bool>; using vll = vector<ll>; using vs = vector<string>; #define ALL(v) v.begin(), v.end() #define SORT(v) sort(ALL(v)) #define SZ(v) int(v.size()) #ifdef DLOCAL #include <local.h> #else #define deb(...); #endif void solve() { int n; cin >> n; string s; cin >> s; vi ans(n); vi positions(27, 0); map<char, bool> seen; for (int i = 0; i < n; ++i) { if (seen.upper_bound(s[i]) != seen.end()) { positions[s[i] - 'a'] = *max_element(positions.begin() + (s[i] - 'a') + 1, positions.end()) + 1; ans[i] = positions[s[i] - 'a']; } else { positions[s[i] - 'a'] = 1; ans[i] = positions[s[i] - 'a']; } seen[s[i]] = 1; } cout << *max_element(ALL(ans)) << "\n"; for (int i = 0; i < n; ++i) { cout << ans[i] << " "; } } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin ("puzzle_name.in"); //ofstream cout ("puzzle_name.out"); solve(); return 0; }
cpp
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> //#include <ext/pb_ds/assoc_container.hpp> //#include <ext/pb_ds/tree_policy.hpp> //#include <bits/extc++.h> typedef long long ll; #define int long long #define pb push_back #define mp make_pair #define mt make_tuple #define all(a) (a).begin(), (a).end() #define clr(a, h) memset(a, (h), sizeof(a)) #define F first #define S second #define fore(i, b, e) for (int i = (int) b, o_o = e; i < (int) o_o; ++i) #define forr(i, b, e) for (int i = (int) b, o_o = e; i < (int) o_o; ++i) #define deb(x) cerr << "# " << (#x) << " = " << (x) << endl; #define sz(x) (int) x.size() #define endl '\n' // int in(){int r=0,c;for(c=getchar();c<=32;c=getchar());if(c=='-') return -in();for(;c>32;r=(r<<1)+(r<<3)+c-'0',c=getchar());return r;} using namespace std; //using namespace __gnu_pbds; //#pragma GCC target ("avx2") //#pragma GCC optimization ("O3") //#pragma GCC optimization ("unroll-loops") typedef pair < int, int > ii; typedef vector < int > vi; typedef vector < ii > vii; typedef vector < ll > vll; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; //find_by_order kth largest order_of_key < //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int INF = 1e17; const double PI = acos(-1); const int tam = 1e6 + 10; int weapon[tam]; int armor[tam]; const int maxN = 2e5 + 10; struct node { int val, lazy; node() { val = lazy = 0; } node(int v, int l) { val = v; lazy = l; } void join(node a, node b) { val = max(a.val, b.val); } }; node t[4*tam]; #define index int l = 2*nodo+1, r = l+1, mid = (b+e)/2; void propagate(int b, int e, int nodo) { if (t[nodo].lazy == 0) return; t[nodo].val += t[nodo].lazy; index; if (b != e) { t[l].lazy += t[nodo].lazy; t[r].lazy += t[nodo].lazy; } t[nodo].lazy = 0; } void update(int b, int e, int nodo, int i, int j, int val) { propagate(b, e, nodo); if (b > j || e < i) return; if (b >= i && e <= j) { t[nodo].lazy += val; propagate(b, e, nodo); return; } index; update(b, mid, l, i, j, val); update(mid + 1, e, r, i, j, val); t[nodo].join(t[l], t[r]); } node query(int b, int e, int nodo, int i, int j) { propagate(b, e, nodo); if (b > j || e < i) return node(-INF, 0); if (b >= i && e <= j) return t[nodo]; index; node a = query(b, mid, l, i, j); node c = query(mid + 1, e, r, i, j); node ans; ans.join(a, c); return ans; } inline void update(int l, int r, int val) { update(0, tam-1, 0, l, r, val); } inline node query(int l, int r) { return query(0, tam-1, 0, l, r); } signed main() { std::ios::sync_with_stdio(false); cin.tie(0); //freopen("","r",stdin); //freopen("","w",stdout); fore(i, 0, tam) weapon[i] = armor[i] = INF; int n, m, p; cin >> n >> m >> p; fore(i, 0, n) { int a, b; cin >> a >> b; weapon[a] = min(weapon[a], b); } fore(i, 0, m) { int a, b; cin >> a >> b; armor[a] = min(armor[a], b); } for (int i = tam-1; i >= 0; --i) { if (i + 1 < tam) { weapon[i] = min(weapon[i], weapon[i + 1]); armor[i] = min(armor[i], armor[i + 1]); } if (i+1 < tam) update(i, i, - weapon[i+1]); else update(i, i, -INF); } int ans = - weapon[0] - armor[0]; vector<pair<ii, ii>> vals; fore(i, 0, p) { int a, b, c; cin >> a >> b >> c; vals.pb({{a, b}, {c, i}}); } sort(all(vals), [](pair<ii, ii> a, pair<ii, ii> b) { return mp(a.F.S, a.F.F) < mp(b.F.S, b.F.F); }); // fore(i, 0, p) vals[i].S.S = i; // sort(all(vals), [](pair<ii, ii> a, pair<ii, ii> b) { // return a.F < b.F; // }); fore(i, 0, p) { int pos = vals[i].S.S; int val = vals[i].S.F; int x = vals[i].F.F; int y = vals[i].F.S; update(x, tam-1, val); ans = max(ans, query(0, tam-1).val - armor[y+1]); // cerr << x << " " << y << " " << ans << endl; } cout << ans << endl; return 0; } // Dinosaurs
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" ]
/* iamujj15 */ #pragma GCC optimize("O3,unroll-loops") #include "bits/stdc++.h" using namespace std; using namespace std::chrono; #define fstio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define MOD 1000000007 #define MOD1 998244353 #define INF 5e18 #define nline "\n" #define pb emplace_back #define ppb pop_back #define mp make_pair #define ff first #define ss second #define PI 3.141592653589793238462 #define FIXED_FLOAT(x) std::fixed << std::setprecision(15) << (x) #define set_bits __builtin_popcountll #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define vcin(a) for (auto &i : a) cin >> i #define vcout(a) for (auto i : a) cout << i << " " #ifndef iamujj15 #define debug(x) cerr << #x << " "; _print(x); cerr << nline; #else #define debug(x); #endif typedef unsigned long long ull; typedef long double lld; typedef pair<long long, long long> pll; typedef vector<long long> vll; typedef long long ll; typedef unsigned long long ull; 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(float 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) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} template <class T, class V> void _print(multimap <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); /*---------------------------------------------------------------------------------------------------------------------------*/ 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 >>= 1;} return res;} void extendgcd(ll a, ll b, ll*v) {if (b == 0) {v[0] = 1; v[1] = 0; v[2] = a; return ;} extendgcd(b, a % b, v); ll x = v[1]; v[1] = v[0] - v[1] * (a / b); v[0] = x; return;} //pass an arry of size1 3 ll mminv(ll a, ll b) {ll arr[3]; extendgcd(a, b, arr); return arr[0];} //for non prime b ll mminvprime(ll a, ll b) {return expo(a, b - 2, b);} ll pow2(ll k) {ll i = 1; if (k == 0) return 1; while (k--) i *= 2; return i;} ll pow10(ll k) {ll i = 1; if (k == 0) return 1; while (k--) i *= 10; return i;} ll lcm(ll a, ll b) { return (a / __gcd(a, b)) * b;} ll mx(ll a, ll b) {return a > b ? a : b;} ll mn(ll a, ll b) {return a < b ? a : b;} ll combination(ll n, ll r, ll m, ll *fact, ll *ifact) {ll val1 = fact[n]; ll val2 = ifact[n - r]; ll val3 = ifact[r]; return (((val1 * val2) % m) * val3) % m;} void google(int t) {cout << "Case #" << t << ": ";} void sieve(vector<bool>& prime) {for (int p = 2; p * p <= prime.size(); p++) {if (prime[p] == true) {for (int i = p * p; i <= prime.size(); i += p) prime[i] = false;}}} ll mod_add(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} ll mod_mul(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} ll mod_sub(ll a, ll b, ll m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} ll mod_div(ll a, ll b, ll m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;} //only for prime m ll phin(ll n) {ll number = n; if (n % 2 == 0) {number /= 2; while (n % 2 == 0) n /= 2;} for (ll i = 3; i <= sqrt(n); i += 2) {if (n % i == 0) {while (n % i == 0)n /= i; number = (number / i * (i - 1));}} if (n > 1)number = (number / n * (n - 1)) ; return number;} //O(sqrt(N)) ll getRandomNumber(ll l, ll r) {return uniform_int_distribution<ll>(l, r)(rng);} ll modInverse(ll A, ll M) {ll m0 = M; ll y = 0, x = 1; if (M == 1)return 0; while (A > 1) {ll q = A / M; ll t = M; M = A % M, A = t; t = y; y = x - q * y; x = t;} if (x < 0)x += m0; return x;} void preclc(vll &fact, vll &invf) {fact[0] = 1; fact[1] = 1; invf[0] = 1; invf[1] = 1; for (ll i = 2; i < (ll)fact.size(); i++) {fact[i] = (fact[i - 1] * i) % MOD; invf[i] = modInverse(fact[i], MOD);}} ll ncr(ll n, ll r, vll &fact, vll &invf) {return ((fact[n] * invf[r] % MOD) * invf[n - r]) % MOD;} /*--------------------------------------------------------------------------------------------------------------------------*/ string spi = "3141592653589793238462643383279"; class DSU { public: vector<pll> parent; vll size; DSU(ll n) { size.resize(n, 1); for (ll i = 0; i < n; i++) parent.pb(i, 0); } ll find_set(ll x) { if (parent[x].ff == x) return x; return parent[x].ff = find_set(parent[x].ff); } bool same_set(ll x, ll y) { return find_set(x) == find_set(y); } void union_set(ll x, ll y) { ll xroot = find_set(x); ll yroot = find_set(y); if (xroot == yroot) return; if (parent[xroot].ss > parent[yroot].ss) { parent[yroot].ff = xroot; size[xroot] += size[yroot]; } else if (parent[yroot].ss > parent[xroot].ss) { parent[xroot].ff = yroot; size[yroot] += size[xroot]; } else { parent[xroot].ss++; parent[yroot].ff = xroot; size[xroot] += size[yroot]; } } ll size_set(ll x) { return size[find_set(x)]; } }; /* ----------------------------------Errors to be taken care of---------------------------------- ⬥ Initialised a variable, with some other variable (say n), before cin >> n? ⬥ Checked for the domain of the answer, & what extreme values your solution could get? ⬥ In C++, comparator should return false if its arguments are equal ⬥ Use custom sqrt function */ void solution() { //vector<bool> prime(4e6, true); //sieve(prime); ll t; cin >> t; for (ll i = 1; i <= t; ++i) { string s, t; cin >> s >> t; bool flg = true; set<char> ss; for (auto i : s) ss.insert(i); for (auto i : t) { if (ss.find(i) == ss.end()) { flg = false; break; } } if (!flg) cout << -1 << nline; else { ll cnt = 0, cr = -1, id = 0; vector<set<ll>> pos(26); for (ll i = 0; i < s.length(); ++i) pos[s[i] - 'a'].insert(i); while (id < t.size()) { if (pos[t[id] - 'a'].lower_bound(cr + 1) != pos[t[id] - 'a'].end()) { cr = *pos[t[id] - 'a'].lower_bound(cr + 1); id++; } else { cr = -1; cnt++; } } cout << cnt + 1 << nline; } } } int main() { #ifndef iamujj15 freopen("error.txt", "w", stderr); #endif fstio(); auto start1 = high_resolution_clock::now(); solution(); auto stop1 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop1 - start1); #ifdef iamujj15 cerr << "Time: " << duration . count() / 1000 << nline; #endif }
cpp
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; vector<int> v; for (int i = 0; i < 3; i++) { int a; cin >> a; v.push_back(a); } cin >> n; int a = v[0]; int b = v[1]; int c = v[2]; sort(v.begin(),v.end()); for (int i = 0; i < 2; i++) { n -= v[2]-v[i]; } if(n%3 == 0 && n>=0){ cout << "YES" << endl; }else{ cout << "NO" << endl; } } }
cpp
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
//ANY TIME YOU SEE OPTIMIZATION PROBLEM -> BINARY SEARCH THE ANSWER!!! #include <bits/stdc++.h> using namespace std; #define ll long long #define No cout<<"No"<<endl; #define NO cout<<"NO"<<endl; #define Yes cout<<"Yes"<<endl; #define YES cout<<"YES"<<endl; #define MOD 1000000007 #define endl '\n' void solve() { ll n, m, i, j, a[1005], b[300005], fin =0, fink; ll ans[1005][1005]; cin>>n; for(i=1;i<=n;i++) { cin>>a[i]; ans[i][0] = 1e18; } for(i=1;i<=n;i++) { ll s =0; ans[i][i] = a[i]; //cout<<i<<" "<<ans[i][i]<<endl; s+=a[i]; for(j=i+1;j<=n;j++) { ans[i][j] = min(ans[i][j-1], a[j]); s+=ans[i][j]; } for(j=i-1;j>=1;j--) { ans[i][j] = min(ans[i][j+1], a[j]); s+=ans[i][j]; } if(s>fin) { fin = s; fink = i; } } //cout<<fink<<endl; for(i=1;i<=n;i++) { cout<<ans[fink][i]<<" "; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //int t; cin>>t; //while(t--) solve(); }
cpp
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
#include<bits/stdc++.h> #define nl "\n" #define fi first #define se second #define pi 3.14159 #define ll long long #define odd(a) (a&1) #define even(a) !(a&1) #define Mod 1'000'000'007 #define INF 2'000'000'000 #define sz(x) int(x.size()) #define charToInt(s) (s - '0') #define ull unsigned long long #define number_line iota(all(vec) , 1) #define all(s) s.begin(), s.end() #define rall(v) v.rbegin() , v.rend() #define fixed(n) fixed << setprecision(n) #define Num_of_Digits(n) ((int)log10(n) + 1) #define to_decimal(bin) stoll(bin, nullptr, 2) #define Ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0)) #define Floor(n, m) (((n) / (m)) - ((n) % (m) ? 0 : 1)) #define Upper(s) transform(all(s), s.begin(), ::toupper); #define Lower(s) transform(all(s), s.begin(), ::tolower); #define cout_map(mp) for(auto& [f, s] : mp) cout << f << " " << s << "\n"; // ----- bits------- #define pcnt(n) __builtin_popcount(n) #define pcntll(n) __builtin_popcountll(n) #define clz(n) __builtin_clz(n) // <---100 #define clzll(n) __builtin_clzll(n) #define ctz(n) __builtin_ctz(n) // 0001----> #define ctzll(n) __builtin_ctzll(n) using namespace std; template < typename T = int > istream& operator >> (istream &in, vector < T > & v){ for(auto & x : v) in >> x; return in; } template < typename T = int > ostream& operator << (ostream &out, const vector < T > & v){ for(const T & x : v) out << x << " "; return out; } void esraa() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout); #endif } void solve(){ int n , k; string s , t = ""; cin >> n >> k >> s; vector < int > v(26 , 0) , p(k) , suffix(n); cin >> p; for(int i = 0 ; i < k ; i++){ suffix[p[i] - 1]++; } for(auto & i : s) v[i - 'a']++; for(int i = n - 2 ; i >= 0 ; i--){ suffix[i] += suffix[i + 1]; } for(int i = 0 ; i < n ; i++){ v[s[i] - 'a'] += suffix[i]; } cout << v << nl; } int main() { esraa(); int t = 1; cin >> t; //cin.ignore(); while(t--) solve(); return 0; }
cpp
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
#include<iostream> #include<math.h> #include<algorithm> #include<string> #include<cstring> #include<string.h> #include<vector> #include<map> #include<cmath> #include<cstdio> #include<set> #include<deque> #include<queue> #include<stack> using namespace std; const int inf=0x3f3f3f3f,hamod=1e9+7,HAmod=1e9+9,mod=200907,N=1e6+10,maxn=1e5+10; const double pi=acos(-1.0); typedef long long ll; #define mp make_pair #define eps 1e-8 //#define lighting ios::sync_with_stdio(false);cin.tie(0),cout.tie(0); #define lighting ios::sync_with_stdio(false);cin.tie(nullptr),cout.tie(nullptr); ll n,a[N],m[N],maxx,tem,tt2,tt1,an[N]; signed main() { cin>>n; for(ll i=1;i<=n;i++) cin>>m[i]; for(ll i=1;i<=n;i++) { tem=0; tt1=tt2=m[i]; tem+=m[i]; a[i]=m[i]; for(ll j=i+1;j<=n;j++) { if(m[j]>tt1) { a[j]=tt1; tem+=a[j]; tt1=a[j]; continue; } a[j]=m[j]; tem+=a[j]; tt1=a[j]; } for(ll j=i-1;j>=1;j--) { if(m[j]>tt2) { a[j]=tt2; tem+=a[j]; tt2=a[j]; continue; } a[j]=m[j]; tem+=a[j]; tt2=a[j]; } if(tem>maxx) { maxx=tem; for(ll i=1;i<=n;i++) { an[i]=a[i]; } } } for(ll i=1;i<=n;i++) { cout<<an[i]<<" "; } }
cpp
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5 64 32 97 2 12345 OutputCopyYES 2 4 8 NO NO NO YES 3 5 823
[ "greedy", "math", "number theory" ]
// LUOGU_RID: 102499094 #include<iostream> using namespace std; int main() { int t; cin>>t; for(int i=1;i<=t;i++) { int n; cin>>n; int x[3]={0,0,0},len=0; for(int j=2;j*j<=n;j++) { if(n%j==0) { x[0]=j; break; } } if(x[0]==0) { cout<<"NO\n"; continue; } n/=x[0]; for(int j=x[0]+1;j*j<=n;j++) { if(n%j==0) { x[1]=j; break; } } if(x[1]==0) { cout<<"NO\n"; continue; } n/=x[1]; if(n!=x[1]&&n!=x[0]&&n>=1) { cout<<"YES\n"; cout<<x[0]<<" "<<x[1]<<" "<<n<<endl; continue; } cout<<"NO\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 ll; typedef pair <int,int> pii; typedef pair <ll , ll> pll; #define sp " " #define nl "\n" #define F first #define S second #define PB push_back #define all(arr) arr.begin(), arr.end() const int N = 1e6 + 5; const int MOD = 1e9 + 7; const ll INF = 1e18; void freop(){ if(fopen("FILE.INP", "r")){ freopen("FILE.INP", "r", stdin); freopen("FILE.OUT", "w", stdout); } } int n, m; int a[N], pre[N]; vector <int> seg[4 * N]; void build(int id, int l, int r){ if(l == r){ seg[id].PB(pre[l]); return; } int mid = (l + r) / 2; build(id*2, l, mid); build(id*2+1, mid+1, r); merge(all(seg[id*2]), all(seg[id*2+1]), back_inserter(seg[id])); } int get(int id, int l, int r, int u, int v, int val){ if(r < u || l > v) return 0; if(u <= l && r <= v) { int pos = lower_bound(all(seg[id]), val) - seg[id].begin(); return pos; } int mid = (l + r) / 2; return get(id*2, l, mid, u, v, val) + get(id*2+1, mid+1, r, u, v, val); } int st[4*N]; void add(int node, int val){ node += n; st[node] = val; for(node /= 2; node > 0; node /= 2) st[node] = st[node*2] + st[node*2+1]; } int query(int lo, int hi){ lo += n, hi += n; int ans = 0; while(lo <= hi){ if(lo % 2 == 1) ans += st[lo++]; if(hi % 2 == 0) ans += st[hi--]; lo /= 2, hi /= 2; } return ans; } pii ans[N]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //freop(); //srand(time(NULL)); cin >> n >> m; for(int i = 1; i <= m; ++i) cin >> a[i]; map <int, int> pos; for(int i = 1; i <= m; ++i){ pre[i] = pos[a[i]]; pos[a[i]] = i; } build(1, 1, m); pos.clear(); for(int i = 1; i <= n; ++i) ans[i].F = ans[i].S = i; for(int i = 1; i <= m; ++i){ int val = a[i]; if(pos[val] == 0){ ans[val].S = max(ans[val].S, val + query(val + 1, n)); } else{ int pre = pos[val]; ans[val].S = max(ans[val].S, 1 + get(1, 1, m, pre + 1, i - 1, pre + 1)); } pos[val] = i; ans[val].F = 1; add(val, 1); } for(int i = 1; i <= n; ++i){ if(pos[i] == 0){ ans[i].S = max(ans[i].S, i + query(i + 1, n)); } else{ int pre = pos[i]; // cout << "w" << i << sp << pre << sp << get(1, 1, m, pre + 1, m, pre + 1) << nl; ans[i].S = max(ans[i].S, 1 + get(1, 1, m, pre + 1, m, pre + 1)); } } // cout << nl; for(int i = 1; i <= n; ++i) { cout << ans[i].F << sp << ans[i].S << nl; } return 0; }
cpp
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
#include <iostream> #include <vector> #include <stack> #include <queue> #include <unordered_set> #include <set> #include <map> #include <algorithm> using namespace std; #define int long long #define ld long double typedef vector<int> vi; typedef vector<pair<int,int> > vpi; #define FOR(i,a,b) for (int i = a; i < b; i++) #define FORR(i,a,b) for (int i = a; i > b; i--) #define srch binary_search #define ub upper_bound #define lb lower_bound #define MP make_pair #define MT make_tuple #define PB push_back #define PP pop_back #define F first #define SQ(x) x * x #define S second #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define endl '\n' #define LSOne(S) __builtin_ctz((S & -S)) #define nx continue; #define tc int te; cin >> te; while(te--) #define pq priority_queue #define fateen ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); typedef pair<int,int> pii; const int inf = 1e18; const int mod = 1e9 + 7; signed main() { fateen; tc { int n; cin >> n; vi v(n); int evencnt = 0, oddcnt = 0; FOR(i, 0, n) { cin >> v[i]; if (v[i] & 1) oddcnt++; else evencnt++; } if (evencnt >= 1) { int i = 0; cout << 1 << endl; while (i < n) { if (!(v[i] & 1)) { cout << ++i << endl; break; } i++; } } else if (oddcnt >= 2) { int cnt = 0; int i = 0; cout << 2 << endl; while (cnt != 2) { if (v[i] & 1) { cout << ++i << " "; } else i++; cnt++; } cout << endl; } else { cout << -1 << endl; } } return 0; }
cpp
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <iostream> using namespace std; int main() { int t; cin>>t; for(int i=0;i<t;i++){ string s; cin>>s; int firstnumber=0,secondnumber=0; for(int j=0;j<s.size();j++){ if(s[j]=='1'){ firstnumber=j; break; } } for(int k=s.size()-1;k>firstnumber;k--){ if(s[k]=='1'){ secondnumber=k; break; } } int count=0; for(int g=firstnumber;g< secondnumber;g++){ if(s[g]=='0') count++; } cout<<count<<endl; } return 0; }
cpp
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define endl '\n' const int maxn=1e5+11; const int Maxx=1e5+11; const int mod=1e9+7; //int t; ll xo,yo,ax,ay,bx,by; ll xs,ys,t; void solve() { cin>>xo>>yo>>ax>>ay>>bx>>by; cin>>xs>>ys>>t; vector<pair<ll,ll>>v; v.emplace_back(xo,yo); pair<ll,ll>pi=make_pair(xo,yo); while(1) { if((ll(1e17)-bx)/pi.first<ax||(ll(1e17)-by)/pi.second<ay) break; ll px=ax*pi.first*1ll+bx; ll py=ay*pi.second*1ll+by; v.emplace_back(px,py); pi=make_pair(px,py); } //cout<<int(v.size())<<endl; int ans=0; for(int i=0;i<v.size();++i) { for(int j=i;j<v.size();++j) { for(int k=i;k<=j;++k) { ll sum=abs(xs-v[k].first)+abs(ys-v[k].second); sum+=abs(v[i].first-v[j].first)+abs(v[i].second-v[j].second); sum+=min(abs(v[i].first-v[k].first)+abs(v[i].second-v[k].second),abs(v[j].first-v[k].first)+abs(v[j].second-v[k].second)); if(sum<=t) { ans=max(ans,j-i+1); } } } } cout<<ans<<endl; } int main() { //scanf("%d",&t); ios::sync_with_stdio(false);cin.tie(0); //ios::sync_with_stdio(false);cin.tie(0);cin>>t;while(t--) solve(); 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" ]
// Problem: B. Navigation System // Contest: Codeforces - Codeforces Round #625 (Div. 1, based on Technocup 2020 Final Round) // URL: https://codeforces.com/problemset/problem/1320/B // Memory Limit: 512 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org) #include<bits/stdc++.h> #define pb push_back #define endl '\n' #define mod 1000000007 #define N 500005 #define vi vector<int> #define vvi vector<vector<int>> #define vb vector<bool> #define control ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define int long long int #define ffor(i, n) for(int i=0; i<n; i++) #define fforr(i, n) for(int i=1; i<=n; i++) #define rfor(i, n) for(int i=n-1; i>=0; i--) #define rforr(i, n) for(int i=n; i>0; i--) #define all(x) x.begin(), x.end() #define F first #define S second #define inf 9223372036854775807 using namespace std; void setIO() { control; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif } void print(bool chk){ if(chk){ cout << "YES" << endl; }else{ cout << "NO" << endl; } } int min(int a, int b){ return a>b?b:a; } int max(int a, int b){ return a<b?b:a; } int power(int x,int y,int p) { int ans=1; x=x%p; if(x==0) { return 0; } while(y>0) { if(y&1) { ans=(ans*x)%p; } y=y>>1; x=(x*x)%p; } return ans; } vvi graph; vvi matrix; vvi level; vi lev; int32_t main(){ int n, m; cin >> n >> m; graph.resize(n+1); level.resize(n+1); lev.resize(n+1, -1); matrix.resize(n+1); ffor(i, m){ int u, v; cin >> u >> v; graph[v].pb(u); matrix[u].pb(v); } int k; cin >> k; int s, t; vi path(k); ffor(i, k){ cin >> path[i]; } s = path[0]; t = path[k-1]; queue<int> q; level[0].pb(t); lev[t] = 0; q.push(t); while(!q.empty()){ int node = q.front(); q.pop(); for(int x:graph[node]){ if(lev[x] == -1){ q.push(x); lev[x] = lev[node] + 1; level[lev[x]].pb(x); } } } int curr = lev[s]; int mxans = 0; int mnans = 0; for(int i=1; i<k; i++){ if(lev[path[i]] < curr){ int cnt = 0; for(int x:matrix[path[i-1]]){ if(lev[x] == lev[path[i]])cnt++; } curr = lev[path[i]]; if(cnt > 1){ mxans += 1; } }else{ curr = lev[path[i]]; mxans += 1; mnans += 1; } } cout << mnans << " " << mxans << endl; }
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: 99461421 #include <stdio.h> #include <random> #include <time.h> #include <set> #define int long long std::mt19937 random_pool(time(NULL)); std::set<int> PrimeFactor; int n, a[200001], m = 1e18; inline void Decompose(int x) { if(x <= 0) return; for(register int i = 2; i * i <= x; ++ i) if(!(x % i)) { PrimeFactor.insert(i); while(!(x % i)) x /= i; } if(x != 1) PrimeFactor.insert(x); } signed main() { scanf("%lld", &n); for(register int i = 1; i <= n; ++ i) scanf("%lld", a + i); for(register int i = 1; i <= 50; ++ i) { int item = a[random_pool() % n + 1]; Decompose(item - 1); Decompose(item); Decompose(item + 1); } for(auto i : PrimeFactor) { int sum = 0; for(register int j = 1; j <= n; ++ j) sum += a[j] > i ? std::min(a[j] % i, i - a[j] % i) : i - a[j]; m = std::min(m, sum); } printf("%lld", m); }
cpp
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include<fstream> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <iomanip> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> #include <random> #include <bitset> #include <fstream> #include <array> #include <functional> #include <stack> #include <memory> #define debug(x) std::cerr << __FUNCTION__ << ":" << __LINE__ << " " << #x << " = " << x << '\n'; using ll = long long; using ull = unsigned long long; using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; using namespace std; int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); string s; cin >> s; //s = "qdpinbmcrfwxpdbfgozvvocemjructoadewegtvbvbfwwrpgyeaxgddrwvlqnygwmwhmrhaizpyxvgaflrsvzhhzrouvpxrkxfza"; map<char, ll> sl; for (int i = 0; i < s.size(); i++) { sl[s[i]]++; } //cout << sl['r'] << " " << sl['v'] << '\n'; pair<char, ll> big1; pair<char, ll> big2; //cout << big1.first << " " << big1.second << "\n"; //cout << big2.first << " " << big2.second << "\n"; ll maxi = INT64_MIN; string s_helper = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < s_helper.size(); i++){ ll now = 0; for (int j = 0; j < s_helper.size(); j++){ big1 = {s_helper[i], sl[s_helper[i]]}; big2 = {s_helper[j], sl[s_helper[j]]}; now = 0; if (i == j){ maxi = max(maxi, max((sl[s_helper[i]] * (sl[s_helper[i]] - 1)) / 2, (sl[s_helper[i]]))); //cout << sl[s_helper[i]] << '\n'; } else { for (int k = 0; k < s.size(); k++) { if (s[k] == big1.first) { now = now + (max(0ll, big2.second)); //cout << s_helper[i] << " " << s_helper[j] << " " << big2.second << " " << now << '\n'; } if (s[k] == big2.first) { big2.second--; } } maxi = max(maxi, now); } } } cout << maxi; return 0; }
cpp
1310
D
D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8 0 1 2 2 0 0 0 1 1 2 0 1 0 0 0 2 1 1 0 0 2 0 1 2 0 OutputCopy2 InputCopy3 2 0 1 1 2 0 1 2 2 0 OutputCopy3
[ "dp", "graphs", "probabilities" ]
// LUOGU_RID: 97142796 #include <bits/stdc++.h> #define int long long using namespace std; const int INF=85; int n,k,Map[INF][INF],p[INF],f[INF][INF],ans; mt19937 rnd(20080209); int gen(int l,int r) {return rnd()%(r-l+1)+l;} void solve() { memset(f,63,sizeof f); for (int i=1;i<=n;i++) p[i]=gen(0,1); f[1][0]=0; for (int i=0;i<k;i++) for (int j=1;j<=n;j++) { for (int l=1;l<=n;l++) { if (p[j]==p[l]) continue; f[l][i+1]=min(f[j][i]+Map[j][l],f[l][i+1]); } } ans=min(ans,f[1][k]); return ; } signed main() { ios::sync_with_stdio(false); cin>>n>>k;ans=1e18; for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) cin>>Map[i][j]; int T=5000; while (T--) solve(); cout<<ans<<"\n"; return 0; }
cpp
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
#include<bits/stdc++.h> #include<iostream> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define ll long long #include<math.h> #include<algorithm> #include<vector> #include<stdbool.h> using std::cout; const int N = 3000008; using namespace std; int main(){ ll n; cin>>n; ll a[n],b[n]; for(int i=0;i<n;i++){ cin>>a[i]; } for(int i=0;i<n;i++){ cin>>b[i]; } ll x=0,y=0; for(int i=0;i<n;i++){ if(a[i]==1 && b[i]==0) ++x; if(a[i]==0 && b[i]== 1) ++y; } if(x==0) cout<<-1; else cout<<y/x+1; }
cpp
1307
F
F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia; there are nn cities, with n−1n−1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering vv possible vacation plans, with the ii-th one consisting of a start city aiai and destination city bibi.It is known that only rr of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than kk consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers nn, kk, and rr (2≤n≤2⋅1052≤n≤2⋅105, 1≤k,r≤n1≤k,r≤n)  — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n−1n−1 lines contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), meaning city xixi and city yiyi are connected by a road. The next line contains rr integers separated by spaces  — the cities with rest stops. Each city will appear at most once.The next line contains vv (1≤v≤2⋅1051≤v≤2⋅105)  — the number of vacation plans.Each of the following vv lines contain two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi)  — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than kk roads without resting for the ii-th vacation plan, print YES. Otherwise, print NO.ExamplesInputCopy6 2 1 1 2 2 3 2 4 4 5 5 6 2 3 1 3 3 5 3 6 OutputCopyYES YES NO InputCopy8 3 3 1 2 2 3 3 4 4 5 4 6 6 7 7 8 2 5 8 2 7 1 8 1 OutputCopyYES NO NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query; Bessie can visit these cities in order: 1,2,31,2,3.For the second query, Bessie can visit these cities in order: 3,2,4,53,2,4,5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3,2,4,5,63,2,4,5,6, she travels on more than 22 roads without resting. The graph for the second example is shown below.
[ "dfs and similar", "dsu", "trees" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; #define eb emplace_back inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 4e5 + 10; const int inf = 1e9; int n, m, r, dis[N], dep[N], con[N], par[N][20]; vector<int> g[N]; int find(int x) {return x == con[x] ? x : con[x] = find(con[x]);} void dfs(int u, int fa) { dep[u] = dep[par[u][0] = fa] + 1; for(int i = 1; (1 << i) <= dep[u]; i ++) par[u][i] = par[par[u][i - 1]][i - 1]; for(int v : g[u]) if(v != fa) dfs(v, u); } int getlca(int x, int y) { if(dep[x] > dep[y]) swap(x, y); per(i, 18, 0) if(dep[par[y][i]] >= dep[x]) y = par[y][i]; if(x == y) return x; per(i, 18, 0) if(par[x][i] != par[y][i]) x = par[x][i], y = par[y][i]; return par[x][0]; } int calc(int x, int y) { per(i, 18, 0) if(y >> i & 1) x = par[x][i]; return x; } int main() { n = read(), m = read(), r = read(); rep(i, 1, n - 1) { int u = read(), v = read(); g[u].eb(n + i), g[n + i].eb(u); g[v].eb(n + i), g[n + i].eb(v); } n = 2 * n - 1; queue<int> q; rep(i, 1, n) con[i] = i, dis[i] = inf; rep(i, 1, r) {int x = read(); q.push(x), dis[x] = 0;} while(! q.empty()) { int u = q.front(); q.pop(); if(dis[u] == m) break; for(int v : g[u]) { con[find(v)] = find(u); if(dis[v] > dis[u] + 1) dis[v] = dis[u] + 1, q.push(v); } } dfs(1, 0); int t = read(); while(t --) { int x = read(), y = read(), z = getlca(x, y); int len = dep[x] + dep[y] - 2 * dep[z]; if(len <= 2 * m) {puts("YES"); continue;} int a = (dep[x] - dep[z] >= m) ? calc(x, m) : calc(y, len - m); int b = (dep[y] - dep[z] >= m) ? calc(y, m) : calc(x, len - m); if(find(a) == find(b)) puts("YES"); else puts("NO"); } return 0; }
cpp
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 OutputCopy5 1 8 6 NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.
[ "dfs and similar", "dp", "greedy", "trees" ]
#include <bits/stdc++.h> // 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 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 const int N=2e5+7; vector<int> adj[N]; int main() {ios_base::sync_with_stdio(0),cin.tie(0); int n;cin>>n; for(int i=0;i<n-1;i++){ int a,b;cin>>a>>b;adj[a].pb(b);adj[b].pb(a); } int d[n+1];memset(d,-1,sizeof(d));d[1]=0; queue<int> q;q.push(1); int x[3]={1,2,3}; while(!q.empty()){ int node=q.front();q.pop(); x[0]=node; for(int u:adj[node]){ if(d[u]!=-1)continue; d[u]=d[node]+1;q.push(u); } } memset(d,-1,sizeof(d));d[x[0]]=0;q.push(x[0]); int p[n+1]; while(!q.empty()){ int node=q.front();q.pop(); x[1]=node; for(int u:adj[node]){ if(d[u]!=-1)continue; d[u]=d[node]+1;q.push(u);p[u]=node; } } ll ans=d[x[1]]; memset(d,-1,sizeof(d));d[x[0]]=d[x[1]]=0; int virt_node=x[1]; while(virt_node!=x[0]){ virt_node=p[virt_node];d[virt_node]=0; if(virt_node!=x[0])q.push(virt_node); } q.push(x[0]);q.push(x[1]); int mx=0; while(!q.empty()){ int node=q.front();q.pop(); if(d[node]>=mx&&node!=x[0]&&node!=x[1]){ x[2]=node;mx=d[node]; } for(int u:adj[node]){ if(d[u]!=-1)continue; d[u]=d[node]+1;q.push(u);p[u]=node; } } ans+=d[x[2]]; cout<<ans<<'\n'<<x[0]<<" "<<x[1]<<" "<<x[2]<<'\n'; return 0; } /* */
cpp
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
#include <bits/stdc++.h> #define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) using ll = long long; using namespace std; ll gcd(ll a, ll b) { if (a==0) return b; return gcd(b%a, a); } ll lcm(ll a, ll b) { return (a*b)/gcd(a,b); } int main() { IOS; time_t start, end; time(&start); ll n; cin >> n; ll a = 1, b = n; ll l = 2, r; for (l = 2; l<int(sqrt(n)+100); l++) { if (n%l!=0) {continue;} r = n/l; if (l>r) {break;} if (lcm(l,r)!=n) {continue;} a = l; b = r; } cout << a << " " << b; // time(&end); // cout << '\n' << end-start; return 0; }
cpp
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
#include<bits/stdc++.h> using namespace std; int main(){ string str , ans; int t,n,x,i; cin>>t; while( t-- ){ cin>>n>>str; x = 2; ans = ""; for( i=0 ; i<n && x>0 ; i++ ){ if( (str[i]-'0') % 2 ){ x--; ans += str[i]; } } if( x>0 ) cout<<-1<<endl; else cout<<ans<<endl; } return 0; }
cpp
1286
D
D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2 1 1 100 3 1 0 OutputCopy1 InputCopy3 7 10 0 9 4 86 14 5 100 OutputCopy0 InputCopy4 6 4 50 11 25 50 13 16 50 15 8 50 OutputCopy150902884
[ "data structures", "math", "matrices", "probabilities" ]
#include<bits/stdc++.h> #define LL long long #define mod 998244353 using namespace std; int n,vec_t=0; LL ans=0; LL X[100002],v[100002]; LL p[100002][2]; struct aaa { int x; bool o1,o2; LL a,b; }vec[200002]; inline bool cmp(aaa a,aaa b) { return a.a*b.b>b.a*a.b; } inline LL Pow(int a,int b) { if(!b)return 1; LL c=Pow(a,b>>1); c=(c*c)%mod; if(b&1)c=(c*a)%mod; return c; } struct Matrix { LL a[2][2]; }F[100002]; inline Matrix Mul(Matrix A,Matrix B) { Matrix C; for(int i=0;i<2;++i)for(int j=0;j<2;C.a[i][j]%=mod,++j)for(int k=C.a[i][j]=0;k<2;++k)C.a[i][j]+=A.a[i][k]*B.a[k][j]; return C; } inline int lson(int x) { return (x<<1); } inline int rson(int x) { return ((x<<1)|1); } struct SegTree { Matrix a[400002]; inline void build(int k,int l,int r) { if(l==r)return (void)(a[k]=F[l]); int mid=((l+r)>>1),ls=lson(k),rs=rson(k); build(ls,l,mid),build(rs,mid+1,r),a[k]=Mul(a[ls],a[rs]); } inline void modify(int k,int l,int r,int x) { if(l==r)return (void)(a[k]=F[l]); int mid=((l+r)>>1),ls=lson(k),rs=rson(k); if(x<=mid)modify(ls,l,mid,x); else modify(rs,mid+1,r,x); a[k]=Mul(a[ls],a[rs]); } }S; int main() { scanf("%d",&n); for(int i=1;i<=n;++i)scanf("%lld%lld%lld",&X[i],&v[i],&p[i][1]),F[i].a[0][0]=F[i].a[0][1]=p[i][0]=(1-(F[i].a[1][0]=F[i].a[1][1]=(p[i][1]*=Pow(100,mod-2))%=mod))%mod; for(int i=1;i<n;++i) { vec[++vec_t]=(aaa){i,1,0,X[i+1]-X[i],v[i]+v[i+1]},F[i].a[1][0]=0; if(v[i]<v[i+1])vec[++vec_t]=(aaa){i,0,0,X[i+1]-X[i],v[i+1]-v[i]},F[i].a[0][0]=0; if(v[i]>v[i+1])vec[++vec_t]=(aaa){i,1,1,X[i+1]-X[i],v[i]-v[i+1]},F[i].a[1][1]=0; } F[n].a[0][1]=F[n].a[1][0]=0,S.build(1,1,n),sort(vec+1,vec+vec_t+1,cmp); for(int i=1;i<=vec_t;++i) { F[0]=F[vec[i].x]; for(int j=0;j<2;++j)for(int k=0;k<2;++k)F[vec[i].x].a[j][k]=(j==vec[i].o1 && k==vec[i].o2? p[vec[i].x][j]:0); S.modify(1,1,n,vec[i].x),(ans+=(((S.a[1].a[0][0]+S.a[1].a[0][1]+S.a[1].a[1][0]+S.a[1].a[1][1])*vec[i].a)%mod)*Pow(vec[i].b,mod-2))%=mod,F[vec[i].x]=F[0],F[vec[i].x].a[vec[i].o1][vec[i].o2]=p[vec[i].x][vec[i].o1],S.modify(1,1,n,vec[i].x); } return 0&printf("%lld",(ans+mod)%mod); }
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#include<bits/stdc++.h> using namespace std; #define int long long #define cel(x,a) ((x + a - 1) / a) #define all(v) v.begin(),v.end() #define mod 1000000007 #define haan cout<<"YES\n"; #define na cout<<"NO\n"; #define pb push_back #define finish if(flag){cout<<"YES\n";}else{cout<<"NO\n";} #define start int arr[n];for(int i=0;i<n;i++){cin>>arr[i];} #define N 200010 #define dis(v) for(auto &x:v){cout<<x<<" ";}cout<<"\n"; #define dis2(v) for(auto &x:v){cout<<x.first<<" "<<x.second<<"\n";} signed main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin.tie(NULL); int t=1; cin>>t; while(t--){ int n,m;cin>>n>>m; int i=m,j=m; int prev=0; bool flag=true; while(n--){ int a,b,c; cin>>a>>b>>c; i-=a-prev; j+=a-prev; prev=a; if(b>j or c<i){ flag=false; } i=max(i,b); j=min(j,c); } finish } }
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
#include <bits/stdc++.h> using namespace std; using ll = long long; using ii = tuple<int, int>; using vi = vector<ll>; using vii = vector<ii>; using vvi = vector<vi>; using si = set<ll>; int main() { cin.tie(0), ios::sync_with_stdio(0); ll n, m; cin >> n >> m;; vi a(n); ll p = 1; for (int i = 0; i < n; i++) cin >> a[i]; if (n > 2000) { cout << "0\n"; return 0; } for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) { ll d = a[i] > a[j] ? a[i] - a[j] : a[j] - a[i]; (d %= m); (p *= d) %= m; } cout << p << '\n'; }
cpp
1292
F
F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3 2 6 8 OutputCopy2 InputCopy5 2 3 4 9 12 OutputCopy4 InputCopy4 5 7 2 9 OutputCopy1 NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.
[ "bitmasks", "combinatorics", "dp" ]
#include<bits/stdc++.h> #define Cn const #define CI Cn int& #define N 60 #define X 1000000007 using namespace std; int n,a[N+5],C[N+5][N+5],c,s[N+5],tt,ans=1; int vis[N+5];void dfs(int x) { vis[x]=1,s[++c]=a[x];for(int i=1;i<=n;++i) !vis[i]&&(!(a[i]%a[x])||!(a[x]%a[i]))&&(dfs(i),0); } int w[N+5],q[N+5],g[1<<N/4],f[N+5][1<<N/4];void Solve() { if(c==1) return;sort(s+1,s+c+1); int i,j,k,c_=0,ct=0;for(i=1;i<=c;++i) {j=1;for(j=1;j<=ct&&s[i]%q[j];++j);(j>ct?q[++ct]:s[++c_])=s[i];}c=c_; for(i=1;i<=c;++i) {w[i]=0;for(j=1;j<=ct;++j) !(s[i]%q[j])&&(w[i]|=1<<j-1);++g[w[i]];} int l=1<<ct;for(i=1;i<=n;++i) for(j=0;j^l;++j) f[i][j]=0;for(j=0;j^l;++j) g[j]=0; for(i=1;i<=c;++i) ++f[1][w[i]],++g[w[i]]; for(i=0;i^ct;++i) for(j=0;j^l;++j) j>>i&1&&(g[j]+=g[j^(1<<i)]); for(i=1;i^c;++i) for(j=0;j^l;++j) if(f[i][j]) { f[i+1][j]=(f[i+1][j]+1LL*f[i][j]*(g[j]-i))%X; for(k=1;k<=c;++k) w[k]&j&&(w[k]|j)^j&&(f[i+1][w[k]|j]=(f[i+1][w[k]|j]+f[i][j])%X); } ans=1LL*ans*f[c][l-1]%X*C[tt+c-1][tt]%X,tt+=c-1; } int main() { int i,j;for(scanf("%d",&n),i=1;i<=n;++i) scanf("%d",a+i); for(C[0][0]=i=1;i<=n;++i) for(C[i][0]=j=1;j<=i;++j) C[i][j]=(C[i-1][j-1]+C[i-1][j])%X; for(i=1;i<=n;++i) !vis[i]&&(c=0,dfs(i),Solve(),0);return printf("%d\n",ans),0; }
cpp
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
#include <bits/stdc++.h> #define Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0) #define all(x) (x).begin(), (x).end() #define int long long #define mp make_pair #define endl '\n' using namespace std; typedef unsigned long long ULL; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int inf = 0x3f3f3f3f; const ll INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-9; const int N = 1e5 + 10; int n; int a[N]; int stk1[N], tt1, stk2[N], tt2; void solve() { cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; int ans = 0; int pos = -1; for (int i = 1; i <= n; ++i) { tt1 = tt2 = 0; int sum = 0; for (int j = i; j >= 1; --j) { if (tt1 && a[j] > stk1[tt1]) { int t = stk1[tt1]; stk1[++tt1] = t; sum += stk1[tt1]; } else if (tt1 && a[j] <= stk1[tt1] || !tt1) { stk1[++tt1] = a[j]; sum += stk1[tt1]; } } for (int j = i; j <= n; ++j) { if (tt2 && a[j] > stk2[tt2]) { int t = stk2[tt2]; stk2[++tt2] = t; sum += stk2[tt2]; } else if (tt2 && a[j] <= stk2[tt2] || !tt2) { stk2[++tt2] = a[j]; sum += stk2[tt2]; } } sum -= a[i]; if (sum > ans) { ans = sum; pos = i; } } tt1 = tt2 = 0; for (int j = pos; j >= 1; --j) { if (tt1 && a[j] > stk1[tt1]) { int t = stk1[tt1]; stk1[++tt1] = t; } else if (tt1 && a[j] <= stk1[tt1] || !tt1) stk1[++tt1] = a[j]; } for (int j = pos; j <= n; ++j) { if (tt2 && a[j] > stk2[tt2]) { int t = stk2[tt2]; stk2[++tt2] = t; } else if (tt2 && a[j] <= stk2[tt2] || !tt2) stk2[++tt2] = a[j]; } while (tt1) { cout << stk1[tt1] << " "; tt1--; } for (int i = 2; i <= tt2; ++i) cout << stk2[i] << " "; cout << endl; } signed main(void) { Zeoy; int T = 1; // cin >> T; while (T--) { solve(); } return 0; }
cpp
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
#include <bits/stdc++.h> using namespace std; #define ll long long // ll int N = 1e9+7; #define f(n) for (auto i = 0; i < n; i++) #define fo(i, k, n) for (auto i = k; i < n; i++) #define ff first #define ss second #define vi vector<int> #define rep(i, a, b) for (int i = a; i < b; i++) #define pb push_back #define mp make_pair #define sorr \ { \ ios_base::sync_with_stdio(false); \ cin.tie(nullptr); \ } double pi = 2 * acos(0.0); const int N = 1e9 + 7; ll int comp=1e18+1; // Sort the array in descending order // sort(arr, arr + n, greater<int>()); // global varible = 0. // cout<<fixed<<setprecision(9); // memset(array name,value to be filled,sizeof(array name)); // void rest(int a){ // f(a){par[i]=0;sze[i]=0;}return; // } int par[150008]; int sz[150008]; void make(int q) { par[q] = q; sz[q] = 1; } int find(int q) { if (par[q] == q) return q; return par[q] = find(par[q]); } void Union(int x, int y) { x = find(x); y = find(y); if (x != y) { if (sz[x] < sz[y]) swap(x, y); par[y] = x; sz[x] += sz[y]; } } // bool vis[10005]; // bool is_valid(int x,int y,int n,int qx,int qy){ // return(x>0&&y>0&&x<=n&&y<=n&&((qx-x)!=(qy-y))&&((qy-y)!=-(qx-x))&&x!=qx&&y!=qy); // } // vector<pair<int,int>>mov{ // {1,0},{0,1},{-1,0},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1} // }; // void rest(int n){ // f(n+2)v[i].clear(); // } // ll int t[2000006]; // ll int val[2000006]; // val[3]=1; // vector<int>v[100005]; // bool vis[1005]; // // ll int val[200005][20]; // ll int dis[1005]; // ll int par[1005]; // f(1005) {par[i]=-1;dis[i]=INT_MAX;} // vector<pair<ll int,ll int>>v[1005]; // void dfs(int strt){ // set<pair<ll int,ll int>>s;s.insert({0,strt}); // dis[strt]=0; // while(s.size()){ // pair<ll int ,ll int >p=*s.begin();s.erase(s.begin()); // ll int ind=p.second,wt=p.first; vis[ind]=true; // for(auto x:v[ind]){ // ll int nex=x.first,wigh=x.second; // if(wigh+wt<dis[nex]&&!vis[nex]){ // dis[nex]=wigh+wt;par[nex]=ind; // s.insert({dis[nex],nex}); // } // } // } // return; // } // void path(ll int source,vector<pair<ll int,ll int>>&vec,ll int& ans=0){ // while(source!=-1){ // if(par[source]!=-1) {vec.pb({par[source],source});if(m[par[source]][source]==0)ans++;} // return path(par[source],vec,ans); // } // return; // } // map<int,int>m; // void to_find(){ // for(int i=0;i<5000050;i++){ // ll int d=(2*i)+1; // m[d]++; // } // return 0; // } bool is_val[200004]; bool vis[200004]; bool dfs(int ind,vector<vector<int>>&v){ if(ind==1)return true; vis[ind]=true; for(auto child:v[ind]){ if(vis[child]||(!is_val[child]))continue; if( dfs(child,v))return true; } return false; } int main(){ int t;cin>>t;while(t--){ ll int a,b,p,res=0;cin>>a>>b>>p; vector<pair<ll int,ll int>>v;string s;cin>>s;ll int n=s.size(); f(n-1){ if(s[i]!=s[i+1]&&s[i]=='A'){v.pb({a,i+1});res+=a;} else if(s[i]!=s[i+1]&&s[i]=='B'){v.pb({b,i+1});res+=b;} } if(s[n-1]==s[n-2]){if(s[n-1]=='A'){v.pb({a,n-1});res+=a;}else {v.pb({b,n-1});res+=b;}} if(p>=res){cout<<1<<endl;} else{int ind=0; while(p<res&&ind<v.size()){res-=v[ind].first;ind++;} cout<<v[ind-1].second+1<<endl; } } return 0;}
cpp
1286
D
D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are nn pipes with coordinates xixi that are connected to LCC. When the experiment starts at time 0, ii-th proton flies from the ii-th pipe with speed vivi. It flies to the right with probability pipi and flies to the left with probability (1−pi)(1−pi). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer nn — the number of pipes (1≤n≤1051≤n≤105). Each of the following nn lines contains three integers xixi, vivi, pipi — the coordinate of the ii-th pipe, the speed of the ii-th proton and the probability that the ii-th proton flies to the right in percentage points (−109≤xi≤109,1≤v≤106,0≤pi≤100−109≤xi≤109,1≤v≤106,0≤pi≤100). It is guaranteed that all xixi are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/QP/Q, where PP is an integer and QQ is a natural number not divisible by 998244353998244353. In this case, print P⋅Q−1P⋅Q−1 modulo 998244353998244353.ExamplesInputCopy2 1 1 100 3 1 0 OutputCopy1 InputCopy3 7 10 0 9 4 86 14 5 100 OutputCopy0 InputCopy4 6 4 50 11 25 50 13 16 50 15 8 50 OutputCopy150902884
[ "data structures", "math", "matrices", "probabilities" ]
#include <bits/stdc++.h> using namespace std; #define ll long long #define pii pair<int, int> const int MOD = 998244353; inline ll _p(ll x, ll y) { ll ans = 1; while (y) { if (y & 1) ans = ans * x % MOD; x = x * x % MOD, y >>= 1; } return ans; } inline ll inv(ll x) { return _p(x, MOD - 2); } struct lazy_segment_tree { vector<ll> t, lazy; int n; lazy_segment_tree() {} lazy_segment_tree(int n) : n(n), t(4 * n), lazy(4 * n, 1) {} inline void push(int v, int tl, int tr) { if (tl == tr) return; int l = 2 * v, r = 2 * v + 1; lazy[l] = lazy[l] * lazy[v] % MOD; lazy[r] = lazy[r] * lazy[v] % MOD; t[l] = (t[l] * lazy[v]) % MOD; t[r] = (t[r] * lazy[v]) % MOD; lazy[v] = 1; } void upd(int v, int tl, int tr, int p, ll val) { push(v, tl, tr); if (tl == tr) { t[v] = val; return; } int m = (tl + tr) / 2; if (p <= m) upd(2 * v, tl, m, p, val); else upd(2 * v + 1, m + 1, tr, p, val); t[v] = (t[2 * v] + t[2 * v + 1]) % MOD; } void upd(int v, int tl, int tr, int l, int r, ll mult) { if (l > r) return; push(v, tl, tr); if (tl == l && tr == r) { t[v] = (t[v] * mult) % MOD; lazy[v] = mult; return; } int m = (tl + tr) / 2; upd(2 * v, tl, m, l, min(m, r), mult); upd(2 * v + 1, m + 1, tr, max(m + 1, l), r, mult); t[v] = (t[2 * v] + t[2 * v + 1]) % MOD; } ll qry(int v, int tl, int tr, int l, int r) { if (l > r) return 0; push(v, tl, tr); if (tl == l && tr == r) return t[v]; int m = (tl + tr) / 2; return (qry(2 * v, tl, m, l, min(m, r)) + qry(2 * v + 1, m + 1, tr, max(m + 1, l), r)) % MOD; } }; struct fraction { ll a, b; fraction() : a(0), b(1) {} fraction(ll a, ll b) : a(a), b(b) {} inline bool operator==(const fraction& rhs) { return a * rhs.b == b * rhs.a; } inline bool operator!=(const fraction& rhs) { return !(fraction(a, b) == rhs); } inline bool operator<(const fraction& rhs) { return a * rhs.b < b * rhs.a; } }; struct proton { ll pos, vel, p; proton() {} }; int n; vector<proton> arr; struct prefix_products { vector<ll> left, right; prefix_products() { left.resize(2 * n), right.resize(2 * n); ll percent = inv(100); for (int i = 0; i < n; ++i) { left[i + n] = (100 - arr[i].p) * percent % MOD; right[i + n] = arr[i].p * percent % MOD; } for (int i = n - 1; i > 0; --i) { left[i] = (left[2 * i] * left[2 * i + 1]) % MOD; right[i] = (right[2 * i] * right[2 * i + 1]) % MOD; } } ll qryLeft(int a, int b) { ll ans = 1; for (a += n, b += n + 1; a < b; a >>= 1, b >>= 1) { if (a & 1) ans = ans * left[a++] % MOD; if (b & 1) ans = ans * left[--b] % MOD; } return ans; } ll qryRight(int a, int b) { ll ans = 1; for (a += n, b += n + 1; a < b; a >>= 1, b >>= 1) { if (a & 1) ans = ans * right[a++] % MOD; if (b & 1) ans = ans * right[--b] % MOD; } return ans; } }; struct probability_maintainer { lazy_segment_tree segtree; prefix_products pre; set<pair<pii, pii>> s; ll ans = 1; probability_maintainer() : segtree(n), pre() { for (int i = 0; i < n; ++i) s.insert({{i, i}, {i, i + 1}}); for (int i = 0; i < n; ++i) segtree.upd(1, 0, n, i, pre.qryRight(i, i)); } void add(int i) { if (ans == 0) return; auto cur = s.lower_bound({{i, i}, {i, i}}); auto bef = prev(cur); s.erase(cur), s.erase(bef); pii sa = bef->first, sb = cur->first; int a = sa.first, b = sa.second, c = sb.first, d = sb.second; pii ra = bef->second, rb = cur->second; int w = ra.first, x = ra.second, y = rb.first, z = rb.second; ll tl = segtree.qry(1, 0, n, w, min(x, b)); if (x == b + 1) tl += pre.qryLeft(a, b); ll tr = segtree.qry(1, 0, n, y, min(z, d)); if (z == d + 1) tr += pre.qryLeft(c, d); ans = ans * inv(tl * tr % MOD) % MOD; if (x <= b && y > c) { ans = 0; return; } segtree.upd(1, 0, n, a, b, pre.qryRight(c, d)); segtree.upd(1, 0, n, c, d, pre.qryLeft(a, b)); int nw = y > c ? y : w; int nx = x <= b ? x : z; ll ad = segtree.qry(1, 0, n, nw, min(nx, d)); if (nx == d + 1) ad += pre.qryLeft(a, d); ans = ans * ad % MOD; s.insert({{a, d}, {nw, nx}}); } void addRestriction(int i) { if (ans == 0) return; auto cur = --s.lower_bound({{i, i}, {i, i}}); s.erase(cur); int a = cur->first.first, b = cur->first.second; int w = cur->second.first, x = cur->second.second; ll tl = segtree.qry(1, 0, n, w, min(x, b)); if (x == b + 1) tl += pre.qryLeft(a, b); ans = ans * inv(tl) % MOD; if (arr[i].vel > arr[i - 1].vel) { if (w > i) { ans = 0; return; } x = min(x, i); } else { if (x < i) { ans = 0; return; } w = max(w, i); } tl = segtree.qry(1, 0, n, w, min(x, b)); if (x == b + 1) tl += pre.qryLeft(a, b); ans = ans * tl % MOD; s.insert({{a, b}, {w, x}}); } ll getProbability() { return ans; } }; int main() { ll percent = inv(100); cin >> n; arr.resize(n); for (int i = 0; i < n; ++i) cin >> arr[i].pos >> arr[i].vel >> arr[i].p; vector<pair<fraction, int>> ways; for (int i = 1; i < n; ++i) { ll d = arr[i].pos - arr[i - 1].pos; ll v = arr[i].vel + arr[i - 1].vel; ways.push_back({fraction(d, v), i}); v = abs(arr[i].vel - arr[i - 1].vel); if (v) ways.push_back({fraction(d, v), i}); } sort(ways.begin(), ways.end(), [&](pair<fraction, int> a, pair<fraction, int> b) { if (a.first != b.first) return a.first < b.first; return a.second < b.second; }); probability_maintainer maintainer; vector<bool> done(n); ll ans = 0; for (int i = 0; i < ways.size(); ++i) { ll prob = maintainer.getProbability(); if (!prob) break; int mx; for (mx = i; mx < ways.size(); ++mx) if (ways[i].first != ways[mx].first) break; fraction time = ways[i].first; ll colt = time.a * inv(time.b) % MOD; for (int j = i; j < mx; ++j) { int i = ways[j].second; if (!done[i]) maintainer.add(i); else maintainer.addRestriction(i); done[i] = true; } i = mx - 1; ll prob2 = maintainer.getProbability(); ll left = (prob - prob2 + MOD) % MOD; ans = (ans + left * colt) % MOD; } cout << ans << '\n'; return 0; }
cpp
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
/*████████████████████████████████████████████████████████████████████████████████████ ██████████████████████████████████████████████████████████████████████████████████████ ███████████████████████████▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓▓╬╬╬╬╬╬▓███████████████████████ ███████████████████████████▓███████▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▓▓▓█▓╬╬╬▓███████████████████████ ███████████████████████████████▓█████▓▓╬╬╬╬╬╬╬╬▓███▓╬╬╬╬╬╬╬▓╬╬▓███████████████████████ ████████████████████████████▓▓▓▓╬╬▓█████╬╬╬╬╬╬███▓╬╬╬╬╬╬╬╬╬╬╬╬╬███████████████████████ ███████████████████████████▓▓▓▓╬╬╬╬╬╬▓██╬╬╬╬╬╬▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ ████████████████████████████▓▓▓╬╬╬╬╬╬╬▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ ███████████████████████████▓█▓███████▓▓███▓╬╬╬╬╬╬▓███████▓╬╬╬╬▓███████████████████████ ████████████████████████████████████████▓█▓╬╬╬╬╬▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬███████████████████████ ███████████████████████████▓▓▓▓▓▓▓╬╬▓▓▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ ████████████████████████████▓▓▓╬╬╬╬▓▓▓▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ ███████████████████████████▓█▓▓▓▓▓▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ █████████████████████████████▓▓▓▓▓▓▓▓█▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████ █████████████████████████████▓▓▓▓▓▓▓██▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████ █████████████████████████████▓▓▓▓▓████▓▓▓█▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████ ████████████████████████████▓█▓▓▓▓██▓▓▓▓██╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬████████████████████████ ████████████████████████████▓▓███▓▓▓▓▓▓▓██▓╬╬╬╬╬╬╬╬╬╬╬╬█▓╬▓╬╬▓████████████████████████ █████████████████████████████▓███▓▓▓▓▓▓▓▓████▓▓╬╬╬╬╬╬╬█▓╬╬╬╬╬▓████████████████████████ █████████████████████████████▓▓█▓███▓▓▓████╬▓█▓▓╬╬╬▓▓█▓╬╬╬╬╬╬█████████████████████████ ██████████████████████████████▓██▓███████▓╬╬╬▓▓╬▓▓██▓╬╬╬╬╬╬╬▓█████████████████████████ ███████████████████████████████▓██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬██████████████████████████ ███████████████████████████████▓▓██▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓██████████████████████████ ████████████████████████████████▓▓▓█████▓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓███████████████████████████ █████████████████████████████████▓▓▓█▓▓▓▓▓███▓╬╬╬╬╬╬╬╬╬╬╬▓████████████████████████████ ██████████████████████████████████▓▓▓█▓▓▓╬▓██╬╬╬╬╬╬╬╬╬╬╬▓█████████████████████████████ ███████████████████████████████████▓▓█▓▓▓▓███▓╬╬╬╬╬╬╬╬╬▓██████████████████████████████ ██████████████████████████████████████▓▓▓███▓▓╬╬╬╬╬╬╬╬████████████████████████████████ ███████████████████████████████████████▓▓▓██▓▓╬╬╬╬╬╬▓█████████████████████████████████ ██████████████████████████████████████████████████████████████████████████████████████ */ /* ______ __ __ __ __ ________ _______ __ __ ______ ______ ______ ______ __ __ / \| \ | \ \ / \ \ \ | \ | \/ \ / \ / \ / \| \ | \ | ▓▓▓▓▓▓\ ▓▓ | ▓▓ ▓▓\ / ▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓\ | ▓▓ | ▓▓ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓\ | ▓▓ | ▓▓__| ▓▓ ▓▓__| ▓▓ ▓▓▓\ / ▓▓▓ ▓▓__ | ▓▓ | ▓▓ | ▓▓__| ▓▓ ▓▓__| ▓▓ ▓▓___\▓▓ ▓▓___\▓▓ ▓▓__| ▓▓ ▓▓▓\| ▓▓ | ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓\ ▓▓▓▓ ▓▓ \ | ▓▓ | ▓▓ | ▓▓ ▓▓ ▓▓ ▓▓\▓▓ \ \▓▓ \| ▓▓ ▓▓ ▓▓▓▓\ ▓▓ | ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓\▓▓ ▓▓ ▓▓ ▓▓▓▓▓ | ▓▓ | ▓▓ | ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓_\▓▓▓▓▓▓\_\▓▓▓▓▓▓\ ▓▓▓▓▓▓▓▓ ▓▓\▓▓ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓| ▓▓ ▓▓_____| ▓▓__/ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ \__| ▓▓ \__| ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ \▓ | ▓▓ ▓▓ \ ▓▓ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓\▓▓ ▓▓\▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ \▓▓▓ \▓▓ \▓▓\▓▓ \▓▓\▓▓ \▓▓\▓▓▓▓▓▓▓▓\▓▓▓▓▓▓▓ \▓▓ \▓▓\▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓\▓▓ \▓▓ __ __ __ __ __ ______ ______ _______ ______ __ | \ | \ | \ \ | \ / \ / \| \ / \ | \ | ▓▓ | ▓▓ ______ ______ ____| ▓▓\▓▓_______ ______ _| ▓▓_ ______ | ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓▓\ ▓▓▓▓▓▓\ \▓▓ _______ ______ | ▓▓__| ▓▓/ \ | \ / ▓▓ \ \ / \ | ▓▓ \ / \ | ▓▓__| ▓▓ ▓▓ \▓▓ ▓▓__/ ▓▓ ▓▓ \▓▓ | \/ \| \ | ▓▓ ▓▓ ▓▓▓▓▓▓\ \▓▓▓▓▓▓\ ▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓▓\ ▓▓▓▓▓▓\ \▓▓▓▓▓▓ | ▓▓▓▓▓▓\ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓▓▓▓▓▓ \▓▓▓▓▓▓\ | ▓▓▓▓▓▓▓▓ ▓▓ ▓▓/ ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓ | ▓▓ | ▓▓ __| ▓▓ | ▓▓ | ▓▓▓▓▓▓▓▓ ▓▓ __| ▓▓▓▓▓▓▓| ▓▓ __ | ▓▓\▓▓ \ / ▓▓ | ▓▓ | ▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓__| ▓▓ ▓▓ ▓▓ | ▓▓ ▓▓__| ▓▓ | ▓▓| \ ▓▓__/ ▓▓ | ▓▓ | ▓▓ ▓▓__/ \ ▓▓ | ▓▓__/ \ | ▓▓_\▓▓▓▓▓▓\ ▓▓▓▓▓▓▓ | ▓▓ | ▓▓\▓▓ \\▓▓ ▓▓\▓▓ ▓▓ ▓▓ ▓▓ | ▓▓\▓▓ ▓▓ \▓▓ ▓▓\▓▓ ▓▓ | ▓▓ | ▓▓\▓▓ ▓▓ ▓▓ \▓▓ ▓▓ | ▓▓ ▓▓\▓▓ ▓▓ \▓▓ \▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓\▓▓\▓▓ \▓▓_\▓▓▓▓▓▓▓ \▓▓▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓\▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓ | \__| ▓▓ \▓▓ ▓▓ \▓▓▓▓▓▓ */ #include<bits/stdc++.h> using namespace std; // todo defines #define ll long long #define int long long #define double long double #define ld long double #define f(i,n) for(ll i=0;i<(n);i++) #define f1(i,n) for(ll i=1;i<=(n);i++) #define el '\n' #define sq(a) (a)*(a) #define pb emplace_back #define sz(x) (int)((x).size()) #define all(x) (x).begin(), (x).end() #define asort(a,n) sort(a,a+n) #define dsort(a,n) sort(a,a+n,greater<>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<>()); #define cina(arr) f(i,n) cin >> arr[i]; #define YES cout << "YES\n" #define Yes cout << "Yes"<<el #define yes cout << "yes"<<el #define NO cout << "NO\n" #define No cout << "No"<<el #define no cout << "no"<<el #define covid19 ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define TC int t; cin >> t; while(t--) // todo typedefs typedef pair<int,int> pii; typedef map<int,int>mii; typedef vector<int>vi; typedef vector<pii>vii; typedef set<int> si; typedef set<char> sc; bool as_second(const pair<ll,ll> &a, const pair<ll,ll> &b) {return (a.second < b.second); }//sort the vector pair in assending order according to second element bool ds_first(const pair<ll,ll> &a, const pair<ll,ll> &b){ return (a.first > b.first);}//sort the vector pair in decending order according to first element bool ds_second(const pair<ll,ll> &a, const pair<ll,ll> &b) {return a.second>b.second;}//sort the vector pair in decending order according to second element bool isPrime(ll n) { if (n <= 1) return false; for (int i = 2; i * i <= (n); i++) if (n % i == 0) return false; return true; } ll factorial(ll n) { int fact = 1; for (int i = 1; i <= n; i++)fact *= i; return fact; } bool primeFactors(int n, int l, int r, bool notFound) { for (int i = l; i <= r; i++) { if (i == 1) i++; if (n % i == 0) { cout << i << " "; notFound = false; } while (n % i == 0) { n = n / i; } } return notFound; } bool IsInBinarySequence(ll number) { ll numberToCheck = 1; do { if (number == numberToCheck) return true; numberToCheck *= 2; } while (numberToCheck <= number); return false; } ll nextPowerOf2(ll n) { if (n && !(n & (n - 1))) return n; ll cnt = 0; while (n != 0) { n >>= 1; cnt++; } ll x = 1; x = x << cnt; return x; } ll highestPowerof2(ll n) { ll res = 0; for (ll i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res; } vector<ll> first50fib1_1_2() { vector<ll>v = { 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155, 165580141 ,267914296 ,433494437 ,701408733 ,1134903170 ,1836311903 ,2971215073 ,4807526976 ,7778742049,12586269025,20365011074 }; return v; } void first50fib0_0_1() { ll arr[51]={0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049}; } ll fib(ll n) { if (n == 1) return 0; if (n == 2) return 1; return fib(n - 1) + fib(n - 2); } ll binets_formula(ll n) { double sqrt5 = sqrt(5); int F_n = (pow((1 + sqrt5), n) - pow((1 - sqrt5), n)) / (pow(2, n) * sqrt5); return F_n; } /*const int N = 1e7; bool prime[N+3]; void Sieve() { memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= N; p++) { if (prime[p]) { for (int i = p * p; i <= N; i += p) prime[i] = false; } } } */ /* void Sieve(int n) { memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i <= n; i++) { if (prime[i]) { for (int j = 2 * i; j <= n; j += i) { prime[j] = false; } } } } */ void luckyGenerator() { vector<ll> lucky; lucky.pb(0); int idx = 0; while (lucky.back() < 1e10) { lucky.push_back(((lucky[idx] * 10) + 4)); lucky.push_back((lucky[idx] * 10) + 7); idx++; } } int binarySearch(int a[], int first, int last, int search_num) { int middle; if (last >= first) { middle = (first + last) / 2; //Checking if the element is present at middle loc if (a[middle] == search_num) return middle + 1; //Checking if the search element is present in greater half else if (a[middle] < search_num) return binarySearch(a, middle + 1, last, search_num); //Checking if the search element is present in lower half else return binarySearch(a, first, middle - 1, search_num); } return -1; } void factorize(long long n) { int count = 0; while (!(n % 2)) { n /= 2; count++; } if (count) cout << 2 << " " << count << endl; for (long long i = 3; i <= sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count) cout << i << " " << count << endl; } if (n > 2) cout << n << " " << 1 << endl; } vector<pair<int,int>> primeFactors(ll num) { ll fac = 2; vector<pair<int,int>>v; while (num > 1) { if (num % fac == 0) { num /= fac; ll pow = 1; while (num % fac == 0) { num /= fac; pow++; } v.pb(fac, pow); } else { fac++; } } return v; } bool onePrimeFactor(ll num) { ll fac = 2; int cnt = 0; while (num > 1) { if (num % fac == 0) { cnt++; while (num % fac == 0) num /= fac; } else fac++; if (cnt >= 2) return false; } return true; } bool isPerfect(ll d) { double temp = d; d = sqrt(d); temp = sqrt(temp); if (temp == d) return true; return false; } void sort(string s[], int n)//sort string according to length { for (int i = 1; i < n; i++) { string temp = s[i]; int j = i - 1; while (j >= 0 && temp.length() < s[j].length()) { s[j + 1] = s[j]; j--; } s[j + 1] = temp; } } bool IsPowerOfTwo(ll x) { return !(x & (x - 1)); } int binarySearchCount(ll arr[], int n, ll key) { int left = 0, right = n; int mid; while (left < right) { mid = (right + left) >> 1; if (arr[mid] == key) { while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } else if (arr[mid] > key) right = mid; else left = mid + 1; } while (mid > -1 && arr[mid] > key) mid--; return mid + 1; } int countOnesInBin(ll n) { int cnt = 0; while (n) { cnt += n & 1; n >>= 1; } return cnt; } string convertToBinary(ll x) { string s; while (x > 0) { if (x % 2) s += '1'; else s += '0'; x /= 2; } reverse(s.begin(), s.end()); return s; } ll convertToDecimal(string s) { reverse(s.begin(), s.end()); ll ans = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '1') ans += (1 << i); } return ans; } long long lcm(int a, int b) { return (a / __gcd(a, b)) * b; } bool palindrome(string s) { for (int i = 0; i < s.length() / 2; i++) { if (s[i] != s[s.length() - i - 1]) return false; } return true; } int sumOfDigits(ll n) { int sum = 0; string s = to_string(n); f(i, s.length())sum += s[i] - '0'; return sum; } bool isUnique(ll x) { int size = log10(x) + 1; set<int> s; while (x > 0) { s.insert(x % 10); x /= 10; } if (s.size() == size) return true; else return false; } void subString(string s, int n) { for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) cout << s.substr(i, len) << el; } bool sortByVal(const pair<string, int> &a, const pair<string, int> &b) { return (a.second > b.second); } ll Round(double n) { ll y = n; if (y == n) return y; else return y + 1; } bool isLetter(char x) { if (x >= 'A' && x <= 'Z') return true; else if (x >= 'a' && x <= 'z') return true; else return false; } int findLastIndex(string s, char x) { int index = -1; for (int i = 0; i < s.length(); i++) if (s[i] == x) index = i; return index; } bool isVowel(char c) { c = tolower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'u' || c == 'o') return true; else return false; } bool isOdd(char c) { if (c == '1' || c == '3' || c == '5' || c == '7' || c == '9') return true; else return false; } ll sum(ll n) { ll sum = (n * (n + 1)) / 2; return sum; } ll sumInRange(ll l , ll r) { ll ans = sum(r) - sum(l - 1); return ans; } bool sortedAsc(ll arr[],ll n) { for (int i = 1; i < n; i++) { if (arr[i] < arr[i-1]) return false; } return true; } bool sortedDesc(ll arr[],ll n) { for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) return false; } return true; } ll decimalDigitRoot(ll n) { return ((n - 1) % 9) + 1; } bool equal(char x , char y) { if (x == '.') return true; return x == y; } string add(string s , int n) { string temp = ""; while (n--) temp += s; return temp; } bool regularBracketSequence(string s) { stack<char> s1; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') s1.push('('); else { if (s1.empty()) return false; else s1.pop(); } } return s1.empty(); } bool sumDigits(int n) { int rem = 0; while (n) { rem += n % 10; n /= 10; } return rem == 10; } bool sortedA(int arr[],int n) { for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true; } bool sortedD(int arr[],int n) { for (int i = 1; i < n; i++) if (arr[i] > arr[i - 1]) return false; return true; } //int ans[N]; /* vector<int>adjList[N]; int dfs(int node,int parent) { visited[node] = true; for (auto adjNode : adjList[node]) { if (!visited[adjNode]) { group.pb(adjNode); dfs(adjNode, node); } else if (visited[adjNode] && adjNode != parent) return 1; } return 0; } */ /* void bfs(int node) { queue<int> q; q.push(node); visited[node] = 1; while (!q.empty()) { group.pb(q.front()); for (auto adjNode : adjList[q.front()]) if (!visited[adjNode]) q.push(adjNode), visited[adjNode] = 1; q.pop(); } } void dijkstra(int source, vector<vector<pair<int,int>>>&graph) { int n = graph.size(); vector<int> dist(n, inf), pre(n, -1); // cost , node priority_queue<pair<int, int>> nextToVisit; dist[source] = 0; pre[source] = source; nextToVisit.push({0, source}); while (!nextToVisit.empty()) { int u = nextToVisit.top().second; nextToVisit.pop(); if (visited[u])continue; visited[u] = 1; for (auto e : graph[u]) { int v = e.first; int c = e.second; if (dist[u] + c < dist[v]) { dist[v] = dist[u] + c; pre[v] = u; nextToVisit.push({-dist[v], v}); } } } } */ string onlyAlphaString(string s) { string temp = ""; for (int i = 0; i < s.size(); i++) if (isalpha(s[i]))temp += tolower(s[i]); return temp; } int computeXOR(ll a) { if (a % 4 == 0) return a; else if (a % 4 == 1) return 1; else if (a % 4 == 2) return a + 1; else return 0; } void sort3(int& a, int& b, int& c) { if (a > b)swap(a, b); if (b > c)swap(b, c); if (a > b)swap(a, b); } int lis(vector<int>&a) { int n = a.size(); vector<int> dp(n, 1); for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) if (a[j] < a[i])dp[i] = max(dp[i], dp[j] + 1); int ans = dp[0]; for (int i = 1; i < n; i++)ans = max(ans, dp[i]); return ans; } bool oneCharacterString(string s) { vasort(s) return s[0] == s[s.size() - 1]; } ll nPr(ll n , ll r) { ll fact = 1; while (r--) { fact *= n; n--; } return fact; } //todo consts //const int inf = 1e9 + 10; const double pi=acos(-1); bool containEven(string s) { for (int i = 0; i < s.size(); i++) if (s[i] == '2' || s[i] == '4' || s[i] == '6' || s[i] == '8')return true; return false; }void printNcR(int n, int r) { long long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; long long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else p = 1; cout << p << endl; } string convertToTernary(int n) { string ans = ""; while (n > 0) { ans += (char) ((n % 3) + '0'); n /= 3; } reverse(ans.begin(), ans.end()); return ans; } string sumOfTernaries(string s1,string s2) { string ans = ""; for (int i = 0; i < s1.size(); i++) { int x = (s1[i] - '0') + (s2[i] - '0'); x %= 3; ans += (char) (x + '0'); } return ans; } string unique_string(string s) { string t = ""; for (int i = 0; i < s.size(); i++) { if (s[i] == t.back())continue; t += s[i]; } return t; } int countOdd(int L, int R) { int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N += 1; return N; } /* void dfs(int node) { group.pb(node); visited[node] = true; for (auto adjNode: adjList[node]) if (!visited[adjNode]) dfs(adjNode); } */ bool isPowerof10(int n) { while (n >= 10 && n % 10 == 0)n /= 10; return n == 1; } int sumDigitsString(string s) { int sum = 0; for (int i = 0; i < s.size(); i++)sum += s[i] - '0'; return sum; } long long nCr(int n, int r) { if(r > n - r) r = n - r; // because C(n, r) == C(n, n - r) long long ans = 1; int i; for(i = 1; i <= r; i++) { ans *= n - r + i; ans /= i; } return ans; } int log_a_base_b(int a, int b) { return log2(a) / log2(b); } /* int dx[] = {1, 1, 1, -1, -1, -1, 0, 0}; int dy[] = {0, -1, 1, -1, 0, 1, -1, 1}; */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*/ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*void dfs(int node,int depth) { mx = max(mx, depth); vis[node] = 1; for (auto adjNode: adjList[node]) dfs(adjNode, depth + 1); } */ #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx,avx2,fma") #pragma GCC optimize("Ofast") string converToPigLatin(string s) { if (s.size() == 1) { s += "ay"; return s; } string ans = ""; for (int i = 1; i < s.size(); i++) { if (i == 1)ans += (char) toupper(s[i]); else ans += (char) tolower(s[i]); } ans += tolower(s[0]); ans += "ay"; return ans; } string cfRate(int n) { if (n < 1200)return "Newbie"; else if (n <= 1399)return "Pupil"; else if (n <= 1599)return "Specialist"; else if (n <= 1899)return "Expert"; else if (n <= 2099)return "Candidate master"; else if (n <= 2299)return "Master"; else if (n <= 2399)return "International master"; else if (n <= 2599)return "Grandmaster"; else if (n <= 2999)return "International grandmaster"; return "Legendary grandmaster"; } int maxDigit(int n) { int mx = 0; while (n > 0) { mx = max(mx, n % 10); n /= 10; } return mx; } int minDigit(int n) { int mn = 1e18; while (n > 0) { mn = min(mn, n % 10); n /= 10; } return mn; } string convert_from_decimal_to_X(int n, int x) { string ans = ""; while (n > 0) { int rem = n % x; if (rem >= 10) { rem -= 10; ans += ('A' + rem); } else ans += (rem + '0'); n /= x; } reverse(ans.begin(), ans.end()); return ans; } int convert_from_X_to_Decimal(string s,int x) { reverse(s.begin(), s.end()); int st = 1, ans = 0; for (int i = 0; i < s.size(); i++) { if (s[i] != '0') { if (isalpha(s[i])) { int dig = (s[i] - 'A') + 10; ans += dig * st; } else ans += (s[i] - '0') * st; } st *= x; } return ans; } int mod9 = 998244353; int fast_power(int a, int n) { if (n == 0) return 1; // putting a check to avoid unnecessary recursive calls if (a == 0) return 0; int tmp = fast_power(a, n / 2); if (n % 2 == 0) // b is even return (tmp * tmp ); else return (a * tmp * tmp ); } bool checkSemiPrime(int num) { int cnt = 0; for (int i = 2; i * i <= num && cnt < 2; i++) { while (num % i == 0) { num /= i; cnt++; if (cnt > 2)break; } } if (num > 1)cnt++; return cnt == 2; } string binaryAdd(string a, string b) { string result = ""; int temp = 0; int size_a = a.size() - 1; int size_b = b.size() - 1; while (size_a >= 0 || size_b >= 0 || temp == 1) { temp += ((size_a >= 0) ? a[size_a] - '0' : 0); temp += ((size_b >= 0) ? b[size_b] - '0' : 0); result = char(temp % 2 + '0') + result; temp /= 2; size_a--; size_b--; } return result; } int cmp(string a,string b) { int cnt = 0; for (int i = 0; i < a.size(); i++)cnt += (a[i] != b[i]); return cnt; } int sumOfDivisors(int n) { int sum = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0) { if (n / i == i)sum += i; else sum += (n / i) + i; } } return sum; } int cntDistinctLetters(string s) { int cnt = 0; map<char, bool> vis; for (auto c: s)if (!vis[c] && c != ' ')cnt++, vis[c] = 1; return cnt; } int numOfOnes(int x) { return __builtin_popcount(x); } bool checkPalindromeTime(string s1,string s2) { if (s1[0] == s2[1] && s1[1] == s2[0])return true; return false; } int cntVowels(string s) { int cnt = 0; f(i, s.size())if (isVowel(s[i]))cnt++; return cnt; } int largest_divisor(int x) { int mx = -1; for (int i = 1; i * i <= x; i++) { if (x % i == 0) { mx = max(mx, i); mx = max(mx, x / i); } } return mx; } char shift(char c , int x) { int y = x + (c - 'a'); y %= 26; return y + 'a'; } int max_Area_Given_Perimeter(double p) { return (int) ceil(p / 4.0) * floor(p / 4.0); } /* freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); */ bool checkRBS(string t) { stack<char> st; for (auto c: t) { if (c == '(')st.push(c); else { if (st.empty())return 0; else st.pop(); } } return st.empty(); } int cntTrailingZeroes(int x) { return __builtin_clz(x); } int cntLeadingZeroes(int x) { return __builtin_ctz(x); } double DecimalMod(double a, double b) { if (a < b) { return a; } return DecimalMod(a - b, b); } /* long long longPower (long long a, long long n) { if (n == 0) return 1; if (n % 2 == 1) return (longPower (a, n-1) * a) % mod; else { long long b = (longPower (a, n/2)) % mod; return (b * b) % mod; } } // sort vector descending by first , ascending by second auto comp = [](auto p1, auto p2) { if(p1.first < p2.first) return true; if(p1.first > p2.first) return false; return p1.second >= p2.second; } const int N = 5e5 + 5; ll fact[N]; ll mod = 1e9 + 7; ll fastP(ll b, ll e) { if (!e) return 1; if (e & 1) return b * 1ll * fastP(b * 1ll * b % mod, e >> 1) % mod; return fastP(b * 1ll * b % mod, e >> 1) % mod; } ll mod_inverse(ll x) { return fastP(x, mod - 2); } ll ncr(ll n, ll r) { if (r > n) return 0; return (1LL * fact[n] %mod* mod_inverse(fact[n - r])%mod * mod_inverse(fact[r])%mod) % mod; } void fac() { fact[0] = 1; for (int i = 1; i < N; i++) { fact[i] = (1LL * i * fact[i - 1]) % mod; } } */ const int N = 2e5 + 5 , mod = 1e9 + 7; ll fastP(ll b, ll e) { if (!e) return 1; if (e & 1) return b * 1ll * fastP(b * 1ll * b % mod, e >> 1) % mod; return fastP(b * 1ll * b % mod, e >> 1) % mod; } map<int,int>a,b; int32_t main() { covid19 TC { int n; string s; cin >> n >> s; int l = -1, r = n; map<pair<int, int>, int> vis; pair<int, int> cur = {0, 0}; vis[cur] = 0; for (int i = 0; i < n; ++i) { if (s[i] == 'L') --cur.first; if (s[i] == 'R') ++cur.first; if (s[i] == 'U') ++cur.second; if (s[i] == 'D') --cur.second; if (vis.count(cur)) if (i - vis[cur] + 1 < r - l + 1) l = vis[cur], r = i; vis[cur] = i + 1; } if (l == -1) cout << -1 << el; else cout << l + 1 << " " << r + 1 << el; } } /* NOTESSS decimal digit root :: d(n)=1+((n−1)mod9) */
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; const int N=310000, NN=710000; int n, m, bit[NN]={0}, a, mn[N], mx[N], now[N]={0}, cur; void update(int i, int x){ for(;i<NN;i+=i&(-i))bit[i]+=x; } int query(int i){ int res=0; for(;i>0;i-=i&(-i))res+=bit[i]; return res;} int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i=1; i<=n; i++){ now[i]=i+N, mn[i]=mx[i]=i; update(now[i],1); } cur=N; while(m--){ cin >> a; mn[a]=1, mx[a]=max(query(now[a]), mx[a]); update(now[a], -1); now[a]=cur--; update(now[a], 1); } for(int i=1; i<=n; i++){ a=i; int z=query(now[a]); mn[a]=min(z, mn[a]), mx[a]=max(z, mx[a]); cout << mn[i] << ' ' << mx[i] << '\n'; } 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" ]
// Author: yukito8069 //#include <bits/stdc++.h> #include <iostream> #include <algorithm> #include <cstring> using namespace std; #define IOS ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); #define int long long typedef long long ll; typedef double dd; typedef pair<int, int> pii; int f[55][20010]; int n, m, k; int a[55][20010]; int pre[55][20010]; int mxl[20010]; int mxr[20010]; signed main() { IOS; cin >> n >> m >> k; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; pre[i][j] = pre[i][j - 1] + a[i][j]; } } for (int i = 1; i <= m - k + 1; i++) { f[1][i] = pre[1][i + k - 1] - pre[1][i - 1] + pre[2][i + k - 1] - pre[2][i - 1]; mxl[i] = max(mxl[i - 1], f[1][i]); } for (int i = m -k + 1; i >= 1; i--) { mxr[i] = max(mxr[i + 1], f[1][i]); } for (int i = 2; i <= n; i++) { for (int j = 1; j <= m - k + 1; j++) { int xx = pre[i][j + k - 1] - pre[i][j - 1] + pre[i + 1][j + k - 1] - pre[i + 1][j - 1]; int mx = max(mxl[j - k], mxr[j + k]); f[i][j] = mx + xx; for (int z = j - k + 1; z <= j + k - 1; z++) { int jr = j + k - 1; int zr = z + k - 1; int l = max(j, z), r = min(j + k - 1, z + k - 1); f[i][j] = max(f[i][j], f[i - 1][z] + xx - (pre[i][r] - pre[i][l - 1])); } } for (int j = 1; j <= m - k + 1; j++) { mxl[j] = max(mxl[j - 1], f[i][j]); } for (int j = m - k + 1; j >= 1; j--) { mxr[j] = max(mxr[j + 1], f[i][j]); } } int ans = 0; for (int i = 1; i <= m - k + 1; i++) { ans = max(ans, f[n][i]); } cout << ans << "\n"; return 0; }
cpp
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "greedy" ]
#include<bits/stdc++.h> using namespace std; typedef long long ll; enum{N=1600}; map<ll,vector<pair<int,int>>>mp; ll a[N],p[N]; void solve(){ int n;cin>>n; for(int i=1;i<=n;i++)cin>>a[i],p[i]=p[i-1]+a[i]; for(int i=1;i<=n;i++)for(int j=1;j<=i;j++) if(mp[p[i]-p[j-1]].empty())mp[p[i]-p[j-1]].push_back({j,i}); else if(mp[p[i]-p[j-1]].back().second<j)mp[p[i]-p[j-1]].push_back({j,i}); vector<pair<int,int>>r={}; for(auto [x,v]:mp)if(v.size()>r.size())r=v; cout<<r.size()<<'\n'; for(auto[x,y]:r)cout<<x<<' '<<y<<'\n'; } int main(){ ios::sync_with_stdio(0); int T=1;//cin>>T; while(T--)solve(); }
cpp
1310
D
D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8 0 1 2 2 0 0 0 1 1 2 0 1 0 0 0 2 1 1 0 0 2 0 1 2 0 OutputCopy2 InputCopy3 2 0 1 1 2 0 1 2 2 0 OutputCopy3
[ "dp", "graphs", "probabilities" ]
// LUOGU_RID: 90587440 #include<bits/stdc++.h> using namespace std; const int N=90,K=20,INF=1e9+10; int n,k,ans=INF,rand_cnt; int g[N][N]; int col[N],f[K][N]; inline void get_rand() { for(int i=1;i<=n;i++) col[i]=rand()%2; return ; } int solve() { memset(f,0x3f,sizeof f); f[0][1]=0; for(int i=0;i<=k-1;i++) for(int u=1;u<=n;u++) for(int v=1;v<=n;v++) if(col[u]!=col[v]) f[i+1][v]=min(f[i+1][v],f[i][u]+g[u][v]); return f[k][1]; } int main() { srand(time(NULL)); scanf("%d%d",&n,&k); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&g[i][j]); for(int i=1;i<=4000;i++) { get_rand(); ans=min(ans,solve()); } printf("%d\n",ans); 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> using namespace std; using ll = long long; auto solve() { string s, t; cin >> s >> t; s = "_" + s; int n = (int)s.length(); vector<int> mp(26, n); for (int i = 1; i < n; ++i) { mp[s[i] - 'a'] = min(mp[s[i] - 'a'], i); } for (auto j : t) { if (mp[j - 'a'] == n) { cout << "-1\n"; return; } } vector<array<int, 26>> nxt(n); for (auto &i : nxt) { fill(i.begin(), i.end(), n); } for (int i = n - 2; i >= 0; --i) { nxt[i][s[i + 1] - 'a'] = i + 1; for (int j = 0; j < 26; ++j) { nxt[i][j] = min(nxt[i][j], nxt[i + 1][j]); } } int cur = 0, ans = 1; for (auto i : t) { if (nxt[cur][i - 'a'] == n) { cur = nxt[0][i - 'a']; ans++; } else { cur = nxt[cur][i - 'a']; } } cout << ans << "\n"; } auto main() -> int { ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); int _ = 1; cin >> _; while (_--) { solve(); } }
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; //#define int long long #define pb push_back #define mp make_pair constexpr int N = (int)1e5 + 111; constexpr int INF = (int)1e9 + 11; constexpr int md = (int)1e9+7; #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx2,popcnt") void solve(){ string s1,s2; cin >> s1 >> s2; int n = s1.size(); int m = s2.size(); short cnt[256]; memset(cnt,0,sizeof cnt); for(int i = 0; i < s1.size(); i++) cnt[s1[i]]++; for(int i = 0; i < s2.size(); i++) cnt[s2[i]]--; for(auto& y : cnt){ if(y < 0){ cout << "NO\n"; return; } } bool dp[m+1][m+1]; int pos = 0; int C = 0; int ptr = 0; for(int j = 0; j < s2.size(); j++){ while(ptr < s1.size() && s1[ptr] != s2[j]) ptr++; if(ptr == s1.size()) break; // cerr << "ptr: " << ptr << "\n"; C = j+1; ptr++; } // cerr << "C: " << C << "\n"; #pragma GCC ivdep for(int s = max(0,C/2-1); s <= min(m,max(0,C/2-1)+1000); s++){ memset(dp,0,sizeof dp); dp[0][0] = true; bool can = false; for(int i = 0; i < n; i++){ for(int j = min(i,s); j >= 0; j--){ for(int t = min(i,m-s); t >= 0; t--){ if(j + 1 <= s && s2[j] == s1[i]) dp[j+1][t] |= dp[j][t]; if(t + 1 <= m - s && s2[t+s] == s1[i]) dp[j][t+1] |= dp[j][t]; } } // for(int j = 0; j <= min(i+1,s); j++){ // for(int t = 0; t <= min(i+1,m - s); t++){ // dp[0][j][t] = dp[1][j][t]; //// dp[1][j][t] = 0; // } // } } for(int j = 0; j <= m-s; j++) can |= dp[s][j]; if(dp[s][m-s]){ // cerr << "s: " << s << "\n"; cout << "YES\n"; return; } // if(!can) // break; } cout << "NO\n"; return; } signed main(){ ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); int tests = 1; cin >> tests; for(int test = 1; test <= tests; test++){ solve(); } return 0; }
cpp
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
#include <stdio.h> int main(){ int t,n,m,sum,temp; scanf("%d",&t); while(t--){ temp=0; sum=0; scanf("%d%d",&n,&m); while(n--){ scanf("%d",&temp); sum+=temp; } if(sum<m) printf("%d\n",sum); else printf("%d\n",m); } return 0; }
cpp
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,…1,2,3,…). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,…,knk1,k2,…,kn (0≤ki≤50000≤ki≤5000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3 2 1 4 OutputCopy5 InputCopy4 3 1 4 4 OutputCopy6 InputCopy4 3 1 4 1 OutputCopy6 InputCopy5 3 1 4 1 5 OutputCopy11 NoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 5010; int n, m, c[N], p[N], s[N], f[N][N]; int main() { n = read(); rep(i, 1, n) {int x = read(); c[x] ++, m = max(m, x);} rep(i, 2, m) { rep(j, 2, i) f[i][j] = f[i - 1][j]; int cur = i; for(int k = 2; k <= cur; k ++) while(cur % k == 0) cur /= k, f[i][k] ++; } ll sum = 0; p[0] = 1; rep(i, 1, m) { if(! c[i]) {p[i] = 1; continue;} rep(j, 1, i) if(f[i][j]) p[i] = j, sum += 1ll * f[i][j] * c[i]; } ll ans = sum; while(true) { int pos = 1; rep(i, 1, m) s[i] = 0; rep(i, 0, m) s[p[i]] += c[i]; rep(i, 1, m) if(s[i] > s[pos]) pos = i; if(pos == 1 || s[pos] == 1 || 2 * s[pos] <= n) break; ans = min(ans, sum -= s[pos] * 2 - n); rep(i, 0, m) { if(p[i] != pos || p[i] == 1) {p[i] = 1; continue;} -- f[i][p[i]]; while(p[i] > 1 && ! f[i][p[i]]) p[i] --; } } printf("%lld\n", ans); return 0; }
cpp
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
#include<bits/stdc++.h> using namespace std; const int MOD=998244353; int main() { int n, m, k; long long t, u = 1; if (cin >> n >> m, k = n-2, k == 0) cout << 0, exit(0); for (t = k; k > 1; --k) t <<= 1, t %= MOD; for (k = m-n+1; m > k; --m) t *= m, t %= MOD; for (k = 2; k < n; ++k) u *= k, u %= MOD; for (k = MOD-2; k > 0; k >>= 1, u *= u, u %= MOD) if (k&1) t *= u, t %= MOD; cout << t; return 0; }
cpp
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105)  — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 OutputCopy16 4 4 4 0 InputCopy6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 OutputCopy36 4 16 16 16 InputCopy8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 OutputCopy64 0 16 4 16 4 36 0 NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
[ "binary search", "data structures", "dp", "implementation" ]
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <random> using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef unsigned long long ull; typedef tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #define AboTaha_on_da_code ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define X first #define Y second const int dx[8]={0, 0, 1, -1, 1, -1, -1, 1}, dy[8]={1, -1, 0, 0, 1, -1, 1, -1}; const int M = 1e9+7, M2 = 998244353; const double EPS = 1e-9; vector <vector <int>> dp[10][10], ps[4]; void burn(int tc) { map <char, int> mp{{'R', 0}, {'G', 1}, {'B', 2}, {'Y', 3}}; int n, m, q; cin >> n >> m >> q; for (auto &i : ps) i.resize(n, vector <int> (m, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char x; cin >> x; ps[mp[x]][i][j]++; } } for (int i = 0; i < n; i++) { for (int j = 1; j < m; j++) { for (int k = 0; k < 4; k++) { ps[k][i][j]+=ps[k][i][j-1]; } } } for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { for (int k = 0; k < 4; k++) { ps[k][j][i]+=ps[k][j-1][i]; } } } for (auto &i : dp) for (auto &j : i) j.resize(n, vector <int> (m, 0)); int mx[] = {0, 0, 1, 1}, my[] = {0, 1, 1, 0}; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int st = 1, en = n*m; while(st <= en) { int mi = (st+en)/2; bool ok = true; for (int k = 0; k < 4; k++) { int nx = i-mi+1+mi*mx[k], ny = j-mi+1+mi*my[k]; if (nx < 0 || ny < 0 || nx+mi-1 >= n || ny+mi-1 >= m) { ok = false; break; } int sm = ps[k][nx+mi-1][ny+mi-1]; if (nx > 0) sm-=ps[k][nx-1][ny+mi-1]; if (ny > 0) sm-=ps[k][nx+mi-1][ny-1]; if (nx > 0 && ny > 0) sm+=ps[k][nx-1][ny-1]; if (sm != 1LL*mi*mi) ok = false; } if (ok) dp[0][0][i][j] = mi, st = mi+1; else en = mi-1; } } } for (int i = 0; i < n; i++) { for (int p = 1; p < 10; p++) { for (int j = 0; j+(1<<p) <= m; j++) { dp[0][p][i][j] = max(dp[0][p-1][i][j], dp[0][p-1][i][j+(1<<(p-1))]); } } } for (int p1 = 0; p1 < 10; p1++) { for (int p2 = 1; p2 < 10; p2++) { for (int i = 0; i+(1<<p1) <= m; i++) { for (int j = 0; j+(1<<p2) <= n; j++) { dp[p2][p1][j][i] = max(dp[p2-1][p1][j][i], dp[p2-1][p1][j+(1<<(p2-1))][i]); } } } } while(q--) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; x1--, y1--, x2--, y2--; int st = 1, en = n*m, ans = 0; while(st <= en) { int mi = (st+en)/2; int r1 = x1+mi-1, c1 = y1+mi-1, r2 = x2-mi, c2 = y2-mi; bool ok = true; if (r1 > r2 || c1 > c2 || r2 >= n || c2 >= m) ok = false; else { int hei = 31-__builtin_clz(r2-r1+1), wid = 31-__builtin_clz(c2-c1+1); int opt = max({dp[hei][wid][r1][c1], dp[hei][wid][r1][c2-(1<<wid)+1], dp[hei][wid][r2-(1<<hei)+1][c1], dp[hei][wid][r2-(1<<hei)+1][c2-(1<<wid)+1]}); if (opt < mi) ok = false; } if (ok) ans = 4*mi*mi, st = mi+1; else en = mi-1; } cout << ans << '\n'; } } int main() { AboTaha_on_da_code // freopen("Ain.txt", "r", stdin); // freopen("Aout.txt", "w", stdout); int T = 1; // cin >> T; for (int i = 1; i <= T; i++) { // cout << "Case #" << i << ": "; burn(i); cout << '\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> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; //#pragma GCC optimization("g", on) //#pragma GCC optimization("03") ////#pragma comment(linker, "/stack:200000000") ////#pragma GCC optimize("Ofast") //#pragma GCC optimize("inline") //#pragma GCC optimize("-fgcse,-fgcse-lm") //#pragma GCC optimize("-ftree-pre,-ftree-vrp") //#pragma GCC optimize("-ffast-math") //#pragma GCC optimize("-fipa-sra") //#pragma GCC optimize("-fpeephole2") //#pragma GCC optimize("-fsched-spec") //#pragma GCC optimize("Ofast,no-stack-protector") ////#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") //#pragma GCC optimize("unroll-loops") //#pragma GCC optimize("Ofast") //#pragma comment(linker, "/stack:200000000") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #define aboba ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define br break; #define sp " " #define en "\n" #define pb push_back #define sz size() #define bg begin() #define ed end() #define in insert #define ss second #define ff first #define rbg rbegin() #define setp(a) cout << fixed; cout << setprecision(a); #define all(v) v.begin(), v.end() #define emp empty() typedef long long ll; typedef double ld; typedef pair<ll, ll> pll; typedef double db; typedef tree< long long, null_type, less_equal<long long>, rb_tree_tag, tree_order_statistics_node_update> orset; void freopen(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } ll bp(ll x, ll y, ll z) { ll res = 1; while (y) { if (y & 1) { res = (res * x) % z; y--; } x = (x * x) % z; y >>= 1; } return res; } // C(n, k) = ((fact[n] * bp(fact[k], mod - 2)) % mod * bp(fact[n - k], mod - 2)) % mod; ll lcm(ll a, ll b) { return (a / __gcd(a, b)) * b; } const ll N = 5e5 + 11; const ll inf = 1e18 + 7; ll tt = 1; ll a[N], b[N]; ll cnt[40]; void solve() { ll n; cin >> n; for (int i = 1;i <= n;i++) cin >> a[i]; ll ans = -1, h = 0; for (int i = 1;i <= n;i++) { for (int j = 0;j < 30;j++) { if (a[i] & (1 << j)) cnt[j]++; } } for (int i = 1;i <= n;i++) { ll tm = 0; for (int j = 29;j >= 0;j--) { if (a[i] & (1 << j)) { if (cnt[j] == 1) { tm += (1 << j); } } } if (tm > ans) { ans = tm; h = i; } } cout << a[h] << sp; for (int i = 1;i <= n;i++) { if (h == i) continue; cout << a[i] << sp; } } int main() { aboba // freopen("B"); // cin >> tt; // precalc(); for (int i = 1;i <= tt;i++) { solve(); } }
cpp
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> using namespace std; #define sz(s) (int)(s.size()) #define all(v) v.begin(),v.end() #define clr(d, v) memset(d,v,sizeof(d)) #define ll long long void file() { std::ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); } int main() { file(); ll h; ll n; cin >> h >> n; ll sum = 0; ll ans = -1; vector<ll> v(n); ll mx = 0; ll H = h; for (int i = 0; i < n; i++) { cin >> v[i]; sum -= v[i]; H += v[i]; if (H <= 0 && ans == -1) { ans = i + 1; } mx = max(mx, sum); } if (ans != -1) { cout << ans; } else if (sum <= 0) { cout << -1; } else { ll full = (h - mx) / sum; h -= full * sum; ll cnt = full * n; for (int i = 0;; i++) { h += v[i % n]; cnt++; if (h <= 0) { cout << cnt; return 0; } } } }
cpp
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#include<bits/stdc++.h> using namespace std; #define int long long typedef int ll; typedef pair<ll,ll> pi; const int N=2e5+10; pi isinter(pi a,pi b) { if (a.first > b.first)swap(a, b); if (a.first == b.first && b.second >= a.second)swap(a, b); // nested if (a.second >= b.second) { return b; } // inter if (a.second >= b.first) { return {max(a.first, b.first), min(a.second, b.second)}; } return {-1e18, -1}; } void solve() { ll n; pi now; cin >> n >> now.first; now.second = now.first; ll t = 0; bool can = true; for (int i = 0; i < n; ++i) { ll time; pi me, bounds; cin >> time >> me.first >> me.second; bounds.first = now.first - (time - t); bounds.second = now.second + (time - t); pi inter = isinter(bounds, me); if (inter.first == -1e18)can = false; now = {max(bounds.first, me.first), min(bounds.second, me.second)}; t = time; } if (can) { cout << "YES" << endl; } else { cout << "NO" << endl; } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t = 1; cin >> t; while (t--) { solve(); } }
cpp
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
#include <bits/stdc++.h> #define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); #define xs(a) cout<<setiosflags(ios::fixed)<<setprecision(a); #define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--) #define mem(a,b) memset(a,b,sizeof(a)); using namespace std; #define ull unsigned long long #define ll long long #define endl '\n' typedef pair<ll,ll> pll; const int N=1e6+5; const int mod=1e9+7; /*-----------------------------------------------------------------------------------------------*/ ll sa[N],sb[N],ea[N],eb[N]; ll n; bool check(){ multiset<ll>s,e; vector<array<ll,3>>vec; FOR(i,1,n){ vec.push_back({sa[i],i,-1}); vec.push_back({ea[i],i,1}); } sort(vec.begin(),vec.end(),[&](auto l,auto r){ if(l[0]==r[0])return l[2]<r[2]; else return l[0]<r[0]; }); for(auto &to:vec){ if(to[2]==1){ s.erase(s.find(sb[to[1]])); e.erase(e.find(eb[to[1]])); }else { s.insert(sb[to[1]]); e.insert(eb[to[1]]); ll mx=*s.rbegin(); ll mi=*e.begin(); if(mx>mi)return 0; } } return 1; } signed main(){IOS cin>>n; FOR(i,1,n)cin>>sa[i]>>ea[i]>>sb[i]>>eb[i]; bool f=1; f&=check(); swap(sa,sb); swap(ea,eb); f&=check(); if(f)cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }
cpp
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
/*▄███████▀▀▀▀▀▀███████▄ ░▐████▀▒▒▒▒▒▒▒▒▒▒▀██████▄ ░███▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▀█████ ░▐██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▌ ░▐█▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▌ ░░█▒▄▀▀▀▀▀▄▒▒▄▀▀▀▀▀▄▒▐███▌ ░░░▐░░░▄▄░░▌▐░░░▄▄░░▌▐███▌ ░▄▀▌░░░▀▀░░▌▐░░░▀▀░░▌▒▀▒█▌ ░▌▒▀▄░░░░▄▀▒▒▀▄░░░▄▀▒▒▄▀▒▌ ░▀▄▐▒▀▀▀▀▒▒▒▒▒▒▀▀▀▒▒▒▒▒▒█ ░░░▀▌▒▄██▄▄▄▄████▄▒▒▒▒█▀ ░░░░▄█████████████ █▒▒▐▌ ░░░▀███▀▀████▀█████▀▒▌ ░░░░░▌▒▒▒▄▒▒▒▄▒▒▒▒▒▒▐ ░░░░░▌▒▒▒▒▀▀▀▒▒▒▒▒▒▒▐*/ #include <bits/stdc++.h> //{بسم الله الرحمن الرحمن الرحيم} #define Amogus_elzengy ios::sync_with_stdio(0);cin. tie(0); #define ll long long #define pb push_back #define ppb pop_back #define pf push_front #define ppf pop_front using namespace std; void mortada_mansor() { int k,time; string students,prev,c; cin>>k>>students; do{ prev=students; c=students; for (int i = 0; i < k-1; ++i) { if(students[i]=='A') {c[i+1]='A';} } students=c; if(prev!=students) time++; } while(prev!=students); cout<<time<<endl; } int main () { Amogus_elzengy ll t; cin>>t; while(t--) { mortada_mansor(); } return 0; }
cpp
1290
F
F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given nn pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0,0)(0,0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x,y)(x,y) and you choose the vector (u,v)(u,v), draw a segment from your current point to the point at (x+u,y+v)(x+u,y+v) and set your current point to (x+u,y+v)(x+u,y+v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 00) and convex shapes made from applying the steps, such that the shape can be contained within a m×mm×m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m×mm×m square if there exists some parallel translation of this shape so that every point (u,v)(u,v) inside or on the border of the shape satisfies 0≤u,v≤m0≤u,v≤m.InputThe first line contains two integers nn and mm  — the number of vectors and the size of the square (1≤n≤51≤n≤5, 1≤m≤1091≤m≤109).Each of the next nn lines contains two integers xixi and yiyi  — the xx-coordinate and yy-coordinate of the ii-th vector (|xi|,|yi|≤4|xi|,|yi|≤4, (xi,yi)≠(0,0)(xi,yi)≠(0,0)).It is guaranteed, that no two vectors are parallel, so for any two indices ii and jj such that 1≤i<j≤n1≤i<j≤n, there is no real value kk such that xi⋅k=xjxi⋅k=xj and yi⋅k=yjyi⋅k=yj.OutputOutput a single integer  — the number of satisfiable shapes by modulo 998244353998244353.ExamplesInputCopy3 3 -1 0 1 1 0 -1 OutputCopy3 InputCopy3 3 -1 0 2 2 0 -1 OutputCopy1 InputCopy3 1776966 -1 0 3 3 0 -2 OutputCopy296161 InputCopy4 15 -4 -4 -1 1 -1 -4 4 3 OutputCopy1 InputCopy5 10 3 -4 4 -3 1 -3 2 -3 -3 -4 OutputCopy0 InputCopy5 1000000000 -2 4 2 -3 0 -4 2 4 -1 -3 OutputCopy9248783 NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is:
[ "dp" ]
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0' or ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0' and ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return x*f; } void write(int x){ if(x<0) putchar('-'),x=-x; if(x>=10) write(x/10); putchar(x%10+'0'); } const int mod = 998244353; int n,m; int x[5],y[5]; int dp[32][22][22][22][22][2][2]; void add(int &x,int y){x=(x+y)%mod;}; int get(int x,int y,int z){return (x^y)?y>x:z;} int dfs(int p,int a,int b,int c,int d,int f1,int f2){ if((1ll<<p)>m) return (!a and !b and !c and !d and !f1 and !f2); if(dp[p][a][b][c][d][f1][f2]>=0) return dp[p][a][b][c][d][f1][f2]; int g=(m>>p)&1,res = 0; for(int s=0;s<(1<<n);s++){ for(int i = 0;i<n;i++) if((s>>i)&1) (x[i]>0?a+=x[i]:b-=x[i]),(y[i]>0?c+=y[i]:d-=y[i]); if((a&1)==(b&1) and (c&1)==(d&1)) add(res,dfs(p+1,a>>1,b>>1,c>>1,d>>1,get(g,a&1,f1),get(g,c&1,f2))); for(int i = 0;i<n;i++) if((s>>i)&1) (x[i]>0?a-=x[i]:b+=x[i]),(y[i]>0?c-=y[i]:d+=y[i]); } return dp[p][a][b][c][d][f1][f2]=res; } signed main(){ // freopen("T.in","r",stdin); // freopen("T.out","w",stdout); n = read(),m = read(),memset(dp,0x80,sizeof(dp)); for(int i = 0;i<n;i++) x[i] = read(),y[i] = read(); write((dfs(0,0,0,0,0,0,0)+mod-1)%mod); return 0; }
cpp
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
#include<bits/stdc++.h> #define ll long long #define el '\n' #define all(a) a.begin(),a.end() #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template<typename T> using orderedset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const ll N=2e5+5,mod=1e9+7; int dx[]={1,-1,0,0,1,1,-1,-1}; int dy[]={0,0,1,-1,1,-1,-1,1}; ll n,p,k,dp[N][1<<7]; pair<int,vector<int>>v[N]; ll solve(int indx,int mask){ if(indx==n){ if(mask==(1<<p)-1) return 0; return -1e9; } ll &sol=dp[indx][mask]; if(~sol) return sol; sol=solve(indx+1,mask); if(indx-__builtin_popcount(mask)<k) sol=max(sol,solve(indx+1,mask)+v[indx].first); for(int i=0;i<p;i++){ if(mask&(1<<i)) continue; sol=max(sol,solve(indx+1,mask|(1<<i))+v[indx].second[i]); } return sol; } inline void Lessgo() { cin>>n>>p>>k; for(int i=0;i<n;i++) cin>>v[i].first; for(int i=0;i<n;i++){ for(int j=0;j<p;j++){ int x; cin>>x; v[i].second.push_back(x); } } sort(v,v+n,greater<pair<int,vector<int>>>()); ::memset(dp,-1,sizeof dp); cout<<solve(0,0); } int main() { ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); int tc=1; // cin>>tc; while(tc--){ Lessgo(); } }
cpp
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //--------------------------------------------------------------------------------- #define ll long long #define fixed(n) cout << fixed << setprecision(n) #define sz(x) int(x.size()) #define TC int t; cin >> t; while(t--) #define all(s) s.begin(), s.end() #define rall(s) s.rbegin(), s.rend() #define dl "\n" #define Ceil(a, b) ((a / b) + (a % b ? 1 : 0)) #define pi 3.141592 #define OO 2'000'000'000 #define MOD 1'000'000'007 #define EPS 1e-10 using namespace std; using namespace __gnu_pbds; //--------------------------------------------------------------------------------- template <typename K, typename V, typename Comp = std::less<K>> using ordered_map = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>; template <typename K, typename Comp = std::greater<K>> using ordered_set = ordered_map<K, null_type, Comp>; template <typename K, typename V, typename Comp = std::less_equal<K>> using ordered_multimap = tree<K, V, Comp, rb_tree_tag, tree_order_statistics_node_update>; template <typename K, typename Comp = std::less_equal<K>> using ordered_multiset = ordered_multimap<K, null_type, Comp>; // order_of_key(val) count elements smaller than val // *s.find_by_order(idx) element with index idx template<typename T = int > istream& operator >> (istream &in , vector < T > &v){ for(auto &i : v) in >> i ; return in ; } template<typename T = int > ostream& operator << (ostream &out ,vector < T > &v){ for(auto &i : v) out << i << ' ' ; return out ; } //----------------------------------------------------------------------------------------- void ZEDAN() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin) ; freopen("output.txt", "w", stdout) ; #endif } //-----------------------------------------(notes)----------------------------------------- /* */ //-----------------------------------------(function)-------------------------------------- ll n , h , l , r ; vector<ll>v ; vector<vector<ll>>dp ; bool valid(ll t){ return t>=l &&t<=r ; } ll rec(ll i=0 , ll t=0){ if(i>=n) return 0 ; ll &ret = dp[i][t] ; if(~ret) return ret ; return ret = max(valid((t+v[i])%h)+rec(i+1,(t+v[i])%h),valid((t+v[i]-1)%h)+rec(i+1,(t+v[i]-1)%h)) ; } //-----------------------------------------(code here)------------------------------------- void solve(){ cin >> n >> h >> l >> r; v = vector<ll>(n) ; dp = vector<vector<ll>>(n+5,vector<ll>(h+5,-1)) ; cin >> v ; cout << rec() ; } //----------------------------------------------------------------------------------------- int main() { ZEDAN() ; ll t = 1 ; // cin >> t ; while(t--){ solve() ; if(t) cout << dl ; } return 0; }
cpp
1316
F
F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105)  — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105)  — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2 1 2 2 1 2 2 1 OutputCopy500000004 1 500000004 InputCopy4 1 2 3 4 4 1 5 2 5 3 5 4 5 OutputCopy625000011 13 62500020 375000027 62500027 NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212.
[ "data structures", "divide and conquer", "probabilities" ]
#include <iostream> #include <algorithm> #include <iomanip> #include <vector> #include <queue> #include <deque> #include <set> #include <map> #include <tuple> #include <cmath> #include <numeric> #include <functional> #include <cassert> #include <cassert> #include <numeric> #include <type_traits> #ifdef _MSC_VER #include <intrin.h> #endif #include <utility> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { constexpr long long safe_mod(long long x, long long m) { x %= m; if (x < 0) x += m; return x; } struct barrett { unsigned int _m; unsigned long long im; explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {} unsigned int umod() const { return _m; } unsigned int mul(unsigned int a, unsigned int b) const { unsigned long long z = a; z *= b; #ifdef _MSC_VER unsigned long long x; _umul128(z, im, &x); #else unsigned long long x = (unsigned long long)(((unsigned __int128)(z)*im) >> 64); #endif unsigned int v = (unsigned int)(z - x * _m); if (_m <= v) v += _m; return v; } }; constexpr long long pow_mod_constexpr(long long x, long long n, int m) { if (m == 1) return 0; unsigned int _m = (unsigned int)(m); unsigned long long r = 1; unsigned long long y = safe_mod(x, m); while (n) { if (n & 1) r = (r * y) % _m; y = (y * y) % _m; n >>= 1; } return r; } constexpr bool is_prime_constexpr(int n) { if (n <= 1) return false; if (n == 2 || n == 7 || n == 61) return true; if (n % 2 == 0) return false; long long d = n - 1; while (d % 2 == 0) d /= 2; constexpr long long bases[3] = {2, 7, 61}; for (long long a : bases) { long long t = d; long long y = pow_mod_constexpr(a, t, n); while (t != n - 1 && y != 1 && y != n - 1) { y = y * y % n; t <<= 1; } if (y != n - 1 && t % 2 == 0) { return false; } } return true; } template <int n> constexpr bool is_prime = is_prime_constexpr(n); constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) { a = safe_mod(a, b); if (a == 0) return {b, 0}; long long s = b, t = a; long long m0 = 0, m1 = 1; while (t) { long long u = s / t; s -= t * u; m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b auto tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return {s, m0}; } constexpr int primitive_root_constexpr(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int divs[20] = {}; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long long)(i)*i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { bool ok = true; for (int i = 0; i < cnt; i++) { if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } template <int m> constexpr int primitive_root = primitive_root_constexpr(m); unsigned long long floor_sum_unsigned(unsigned long long n, unsigned long long m, unsigned long long a, unsigned long long b) { unsigned long long ans = 0; while (true) { if (a >= m) { ans += n * (n - 1) / 2 * (a / m); a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } unsigned long long y_max = a * n + b; if (y_max < m) break; n = (unsigned long long)(y_max / m); b = (unsigned long long)(y_max % m); std::swap(m, a); } return ans; } } // namespace internal } // namespace atcoder #include <cassert> #include <numeric> #include <type_traits> namespace atcoder { namespace internal { #ifndef _MSC_VER template <class T> using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type; template <class T> using make_unsigned_int128 = typename std::conditional<std::is_same<T, __int128_t>::value, __uint128_t, unsigned __int128>; template <class T> using is_integral = typename std::conditional<std::is_integral<T>::value || is_signed_int128<T>::value || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_signed_int = typename std::conditional<(is_integral<T>::value && std::is_signed<T>::value) || is_signed_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<(is_integral<T>::value && std::is_unsigned<T>::value) || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional< is_signed_int128<T>::value, make_unsigned_int128<T>, typename std::conditional<std::is_signed<T>::value, std::make_unsigned<T>, std::common_type<T>>::type>::type; #else template <class T> using is_integral = typename std::is_integral<T>; template <class T> using is_signed_int = typename std::conditional<is_integral<T>::value && std::is_signed<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<is_integral<T>::value && std::is_unsigned<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional<is_signed_int<T>::value, std::make_unsigned<T>, std::common_type<T>>::type; #endif template <class T> using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>; template <class T> using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>; template <class T> using to_unsigned_t = typename to_unsigned<T>::type; } // namespace internal } // namespace atcoder namespace atcoder { namespace internal { struct modint_base {}; struct static_modint_base : modint_base {}; template <class T> using is_modint = std::is_base_of<modint_base, T>; template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>; } // namespace internal template <int m, std::enable_if_t<(1 <= m)>* = nullptr> struct static_modint : internal::static_modint_base { using mint = static_modint; public: static constexpr int mod() { return m; } static mint raw(int v) { mint x; x._v = v; return x; } static_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> static_modint(T v) { long long x = (long long)(v % (long long)(umod())); if (x < 0) x += umod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> static_modint(T v) { _v = (unsigned int)(v % umod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++*this; return result; } mint operator--(int) { mint result = *this; --*this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v -= rhs._v; if (_v >= umod()) _v += umod(); return *this; } mint& operator*=(const mint& rhs) { unsigned long long z = _v; z *= rhs._v; _v = (unsigned int)(z % umod()); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { if (prime) { assert(_v); return pow(umod() - 2); } else { auto eg = internal::inv_gcd(_v, m); assert(eg.first == 1); return eg.second; } } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static constexpr unsigned int umod() { return m; } static constexpr bool prime = internal::is_prime<m>; }; template <int id> struct dynamic_modint : internal::modint_base { using mint = dynamic_modint; public: static int mod() { return (int)(bt.umod()); } static void set_mod(int m) { assert(1 <= m); bt = internal::barrett(m); } static mint raw(int v) { mint x; x._v = v; return x; } dynamic_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> dynamic_modint(T v) { long long x = (long long)(v % (long long)(mod())); if (x < 0) x += mod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> dynamic_modint(T v) { _v = (unsigned int)(v % mod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++*this; return result; } mint operator--(int) { mint result = *this; --*this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v += mod() - rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator*=(const mint& rhs) { _v = bt.mul(_v, rhs._v); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { auto eg = internal::inv_gcd(_v, mod()); assert(eg.first == 1); return eg.second; } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static internal::barrett bt; static unsigned int umod() { return bt.umod(); } }; template <int id> internal::barrett dynamic_modint<id>::bt(998244353); using modint998244353 = static_modint<998244353>; using modint1000000007 = static_modint<1000000007>; using modint = dynamic_modint<-1>; namespace internal { template <class T> using is_static_modint = std::is_base_of<internal::static_modint_base, T>; template <class T> using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>; template <class> struct is_dynamic_modint : public std::false_type {}; template <int id> struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {}; template <class T> using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>; } // namespace internal } // namespace atcoder #include <algorithm> #include <cassert> #include <vector> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { int ceil_pow2(int n) { int x = 0; while ((1U << x) < (unsigned int)(n)) x++; return x; } constexpr int bsf_constexpr(unsigned int n) { int x = 0; while (!(n & (1 << x))) x++; return x; } int bsf(unsigned int n) { #ifdef _MSC_VER unsigned long index; _BitScanForward(&index, n); return index; #else return __builtin_ctz(n); #endif } } // namespace internal } // namespace atcoder namespace atcoder { template <class S, S (*op)(S, S), S (*e)()> struct segtree { public: segtree() : segtree(0) {} explicit segtree(int n) : segtree(std::vector<S>(n, e())) {} explicit segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) const { assert(0 <= p && p < _n); return d[p + size]; } S prod(int l, int r) const { assert(0 <= l && l <= r && r <= _n); S sml = e(), smr = e(); l += size; r += size; while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() const { return d[1]; } template <bool (*f)(S)> int max_right(int l) const { return max_right(l, [](S x) { return f(x); }); } template <class F> int max_right(int l, F f) const { assert(0 <= l && l <= _n); assert(f(e())); if (l == _n) return _n; l += size; S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!f(op(sm, d[l]))) { while (l < size) { l = (2 * l); if (f(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*f)(S)> int min_left(int r) const { return min_left(r, [](S x) { return f(x); }); } template <class F> int min_left(int r, F f) const { assert(0 <= r && r <= _n); assert(f(e())); if (r == 0) return 0; r += size; S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!f(op(d[r], sm))) { while (r < size) { r = (2 * r + 1); if (f(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } }; } // namespace atcoder #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; template<typename T> vector<vector<T>> vec2d(int n, int m, T v){ return vector<vector<T>>(n, vector<T>(m, v)); } template<typename T> vector<vector<vector<T>>> vec3d(int n, int m, int k, T v){ return vector<vector<vector<T>>>(n, vector<vector<T>>(m, vector<T>(k, v))); } template<typename T> void print_vector(vector<T> v, char delimiter=' '){ if(v.empty()) { cout << endl; return; } for(int i = 0; i+1 < v.size(); i++) cout << v[i] << delimiter; cout << v.back() << endl; } using mint = atcoder::modint1000000007; ostream& operator<<(ostream& os, const mint& m){ os << m.val(); return os; } template<typename T, int N, int M> class Matrix { public: array<array<T, M>, N> dat; Matrix(T val) { for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ dat[i][j] = val; } } } Matrix(array<array<T, M>, N> dat): dat(dat){ } array<T, M>& operator[](int x) { return dat[x]; } }; template<typename T, int N, int M, int K> Matrix<T, N, K> operator*(Matrix<T, N, M> a, Matrix<T, M, K> b){ Matrix<T, N, K> c(T(0)); for(int i = 0; i < N; i++){ for(int j = 0; j < K; j++){ for(int k = 0; k < M; k++){ c.dat[i][j] += a.dat[i][k]*b.dat[k][j]; } } } return c; } mint naive(vector<mint> p){ int n = p.size(); vector<mint> sum(n+1), ans(n+1); for(int i = 0; i < n; i++){ sum[i+1] = sum[i]/2 + p[i]/2; ans[i+1] = ans[i] + sum[i]*p[i]/2; } return ans[n]; } using M = Matrix<mint, 3, 3>; using V = Matrix<mint, 1, 3>; M e_(){ M ans(mint(0)); for(int i = 0; i < 3; i++) ans[i][i] = 1; return ans; } M op(M a, M b){ return a*b; } M I = e_(); M e(){ return I; } using Seg = atcoder::segtree<M, op, e>; const mint inv2 = mint(2).inv(); M f(mint a){ M ans(mint(0)); ans[0][0] = inv2; ans[0][1] = inv2*a; ans[1][1] = 1; ans[2][0] = inv2*a; ans[2][2] = 1; return ans; } using T = tuple<int, int, int>; template<typename T> class Compress{ public: vector<T> data; int offset; Compress(vector<T> data_, int offset=0): offset(offset){ set<T> st; for(T x: data_) st.insert(x); for(T x: st) data.push_back(x); }; int operator[](T x) { auto p = lower_bound(data.begin(), data.end(), x); assert(x == *p); return offset+(p-data.begin()); } T inv(int x){ return data[x-offset]; } int size(){ return data.size(); } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n; cin >> n; vector<mint> p(n); vector<T> vt; for(int i = 0; i < n; i++) { int x; cin >> x; p[i] = x; vt.push_back(T(x, i, 0)); } int q; cin >> q; vector<int> cnt(n);; vector<int> idx(q), x(q); for(int i = 0; i < q; i++){ cin >> idx[i] >> x[i]; idx[i]--; cnt[idx[i]]++; vt.push_back(T(x[i], idx[i], cnt[idx[i]])); } auto cp = Compress<T>(vt); int m = cp.size(); Seg seg(m); cnt.assign(n, 0); for(int i = 0; i < n; i++){ int idx = cp[T(p[i].val(), i, 0)]; seg.set(idx, f(p[i])); } V v(0); v[0][2] = 1; // cout << naive(p) << endl; auto ans = v*seg.all_prod(); cout << ans[0][1] << endl; for(int i = 0; i < q; i++){ int i_prev = cp[T(p[idx[i]].val(), idx[i], cnt[idx[i]])]; cnt[idx[i]]++; int i_next = cp[T(x[i], idx[i], cnt[idx[i]])]; seg.set(i_prev, e()); seg.set(i_next, f(mint(x[i]))); p[idx[i]] = x[i]; auto ans = v*seg.all_prod(); cout << ans[0][1] << endl; } }
cpp
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
#include<bits/stdc++.h> using namespace std; #define N 200001 #define ll long long int main(){ ll n; cin>>n; //maximum possible value that i can get is 2 double x=0.00000; while(n>0){ x+=(double)1/n; n--; } cout<<x<<endl; return 0; }
cpp
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int too=1e9; int x,y,z; cin>>x>>y>>z; int px,py,pz; for(int i=1; i<=10000; i++) { for(int j=i; j<=10000*2; j+=i) { for(int l=j; l<=10000*3; l+=j) { if(abs(x-i)+abs(y-j)+abs(z-l)<too) { too=abs(x-i)+abs(y-j)+abs(z-l); px=i; py=j; pz=l; } } } } printf("%d\n",too); printf("%d %d %d\n",px,py,pz); } 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" ]
/// endless ? #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; #define ll long long #define F first #define S second #define pii pair<int, int> #define all(x) x.begin(), x.end() #define vi vector<int> #define vii vector<pii> #define pb push_back #define pf push_front #define wall cout <<'\n'<< "-------------------------------------" <<'\n'; #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define int ll const ll MAXN = 2e5 + 43; const ll MOD = 1e9 + 7; ///998244353; const ll INF = 1e18 + 19763; const ll LG = 19; ll pw(ll a, ll b){return b == 0 ? 1LL : (pw(a * a%MOD , b / 2)%MOD * (b % 2 == 0 ? 1LL : a))%MOD;} int pref[MAXN]; void solve() { fast int n, bl, flg = 0; cin >> n >> bl; string s; cin >> s; pref[0] = (s[0] == '0' ? 1 : -1); if (pref[0] == bl)flg = 1; for (int i = 1; i < n; i++) { pref[i] = pref[i - 1] + (s[i] == '0' ? 1 : -1); if (pref[i] == bl)flg = 1; } int ans = 0; for (int i = 0; i < n; i++) { int xbal = bl - pref[i]; if (pref[n - 1] == 0)continue; else if (pref[n - 1] < 0) { if (xbal <= 0) { ans += (-xbal % -pref[n - 1] == 0); } } else { if (xbal >= 0) { ans += (xbal % pref[n - 1] == 0); } } } if (bl == 0)ans ++; cout << (pref[n - 1] == 0 && flg ? -1 : ans) << '\n'; } int32_t main () { fast int t = 1; cin >> t; while (t --) { solve(); } } /// Thanks GOD :)
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
#include <bits/stdc++.h> #include <ext/pb_ds/detail/standard_policies.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> #define TIME 1.0*clock()/CLOCKS_PER_SEC #define all(x) x.begin(), x.end() #define ull unsigned long long #define pii pair < int , int > #pragma GCC optimize("Ofast") #define ld long double #define pb push_back #define ll long long #define endl '\n' #define S second #define F first #define sz size #define int ll using namespace std; using namespace __gnu_pbds; template <typename T> using ordered_set = tree <T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; mt19937 gen(chrono::system_clock::now().time_since_epoch().count()); int32_t main() { #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // LOCAL ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; int a[n]; int x = 1; for (int i = 0; i < n; i++) { cin >> a[i]; for (int j = 0; j < i && x != 0; j++) { x = x * abs(a[j] - a[i]) % m; } } cout << x % m; return 0; }
cpp
1288
F
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15 RRB UB 3 2 2 2 1 2 1 1 2 1 1 1 OutputCopy35 BUURRU InputCopy3 1 3 4 5 RRR B 2 1 1 1 3 1 OutputCopy-1 InputCopy3 1 3 4 5 URU B 2 1 1 1 3 1 OutputCopy14 RBB
[ "constructive algorithms", "flows" ]
// LUOGU_RID: 101592253 #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define db double #define ldb long double #define pb push_back #define mp make_pair #define pii pair<int, int> #define FR first #define SE second using namespace std; inline int read() { int x = 0; bool op = 0; char c = getchar(); while(!isdigit(c))op |= (c == '-'), c = getchar(); while(isdigit(c))x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); return op ? -x : x; } const int N = 1e6 + 10; const int INF = 1e9; int n1, n2, m, wr, wb, S, T, s, t; char c1[N], c2[N]; int id[N][2]; int dis[N], vis[N], pre[N], inc[N], in[N], out[N]; int etot = 1; int head[N], to[N], nxt[N], edge[N], flow[N]; void addedge(int u, int v, int f, int w) { to[++etot] = v; flow[etot] = f; edge[etot] = w; nxt[etot] = head[u]; head[u] = etot; return ; } void add(int u, int v, int f, int w) { addedge(u, v, f, w); addedge(v, u, 0, -w); return ; } bool spfa() { for(int i = 0; i <= T; i++)dis[i] = INF; dis[S] = 0; inc[S] = INF; queue<int> q; q.push(S); while(q.empty() == false) { int u = q.front(); q.pop(); vis[u] = false; for(int i = head[u]; i; i = nxt[i]) { int v = to[i], w = edge[i]; if(flow[i] == 0)continue; if(dis[v] > dis[u] + w) { dis[v] = dis[u] + w; pre[v] = i; inc[v] = min(inc[u], flow[i]); if(vis[v] == false) { vis[v] = true; q.push(v); } } } } return dis[T] < INF; } int ans, cnt; void update() { ans += dis[T] * inc[T]; cnt += inc[T]; for(int i = T; i != S; i = to[pre[i] ^ 1]) { // printf("path:%d\n", i); flow[pre[i]] -= inc[T]; flow[pre[i] ^ 1] += inc[T]; } return ; } int main() { n1 = read(); n2 = read(); m = read(); wr = read(); wb = read(); scanf("%s", c1 + 1); scanf("%s", c2 + 1); for(int i = 1; i <= m; i++) { int u = read(), v = read(); add(u, v + n1, 1, wr); id[i][0] = etot; add(v + n1, u, 1, wb); id[i][1] = etot; } s = 0; t = n1 + n2 + 1; S = t + 1; T = t + 2; for(int i = 1; i <= n1; i++) { if(c1[i] == 'B')add(i, t, INF, 0), out[i]++, in[t]++; else if(c1[i] == 'R')add(s, i, INF, 0), in[i]++, out[s]++; else add(s, i, INF, 0), add(i, t, INF, 0); } for(int i = 1; i <= n2; i++) { if(c2[i] == 'B')add(s, i + n1, INF, 0), in[i + n1]++, out[s]++; else if(c2[i] == 'R')add(i + n1, t, INF, 0), out[i + n1]++, in[t]++; else add(s, i + n1, INF, 0), add(i + n1, t, INF, 0); } for(int i = 0; i <= n1 + n2 + 1; i++) { // printf("deg:%d %d %d\n", i, in[i], out[i]); if(in[i] > out[i])add(S, i, in[i] - out[i], 0); else if(in[i] < out[i])add(i, T, out[i] - in[i], 0); } add(t, s, INF, 0); while(spfa())update(); // printf("ans:%d %d\n", cnt, ans); for(int i = head[S]; i; i = nxt[i])if(flow[i])return puts("-1"), 0; printf("%d\n", ans); for(int i = 1; i <= m; i++) { if(flow[id[i][0]])printf("R"); else if(flow[id[i][1]])printf("B"); else printf("U"); } 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 = 443; int n1, n2, m, r, b; string s1, s2; int u[N]; int v[N]; struct edge { int y, c, f, cost; edge() {}; edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {}; }; int bal[N][N]; int s, t, oldS, oldT, V; vector<int> g[N]; vector<edge> e; void add(int x, int y, int c, int cost) { g[x].push_back(e.size()); e.push_back(edge(y, c, 0, cost)); g[y].push_back(e.size()); e.push_back(edge(x, 0, 0, -cost)); } int rem(int num) { return e[num].c - e[num].f; } void add_LR(int x, int y, int l, int r, int cost) { int c = r - l; if(l > 0) { add(s, y, l, cost); add(x, t, l, cost); } if(c > 0) { add(x, y, c, cost); } } int p[N]; int d[N]; int pe[N]; int inq[N]; bool enlarge() { for(int i = 0; i < V; i++) { d[i] = int(1e9); p[i] = -1; pe[i] = -1; inq[i] = 0; } d[s] = 0; queue<int> q; q.push(s); inq[s] = 1; while(!q.empty()) { int k = q.front(); q.pop(); inq[k] = 0; for(auto z : g[k]) { if(!rem(z)) continue; if(d[e[z].y] > d[k] + e[z].cost) { p[e[z].y] = k; pe[e[z].y] = z; d[e[z].y] = d[k] + e[z].cost; if(!inq[e[z].y]) { q.push(e[z].y); inq[e[z].y] = 1; } } } } if(p[t] == -1) return false; int cur = t; while(cur != s) { e[pe[cur]].f++; e[pe[cur] ^ 1].f--; cur = p[cur]; } return true; } void add_edge(int x, int y) { add(x, y + n1, 1, r); add(y + n1, x, 1, b); } void impose_left(int x) { if(s1[x] == 'R') { add_LR(oldS, x, 1, m, 0); } else if(s1[x] == 'B') { add_LR(x, oldT, 1, m, 0); } else { add(oldS, x, m, 0); add(x, oldT, m, 0); } } void impose_right(int x) { if(s2[x] == 'R') { add_LR(x + n1, oldT, 1, m, 0); } else if(s2[x] == 'B') { add_LR(oldS, x + n1, 1, m, 0); } else { add(oldS, x + n1, m, 0); add(x + n1, oldT, m, 0); } } void construct_bal() { for(int i = 0; i < n1; i++) { for(auto z : g[i]) { if(e[z].y >= n1 && e[z].y < n1 + n2) bal[i][e[z].y - n1] += e[z].f; } } } void find_ans() { int res = 0; string w = ""; for(auto x : g[s]) if(rem(x)) { cout << -1 << endl; return; } for(int i = 0; i < m; i++) { if(bal[u[i]][v[i]] > 0) { bal[u[i]][v[i]]--; res += r; w += "R"; } else if(bal[u[i]][v[i]] < 0) { bal[u[i]][v[i]]++; res += b; w += "B"; } else w += "U"; } cout << res << endl << w << endl; } int main() { cin >> n1 >> n2 >> m >> r >> b; cin >> s1; cin >> s2; for(int i = 0; i < m; i++) { cin >> u[i] >> v[i]; u[i]--; v[i]--; } oldS = n1 + n2; oldT = oldS + 1; s = oldT + 1; t = s + 1; V = t + 1; for(int i = 0; i < n1; i++) impose_left(i); for(int i = 0; i < n2; i++) impose_right(i); for(int i = 0; i < m; i++) add_edge(u[i], v[i]); add(oldT, oldS, 100000, 0); while(enlarge()); construct_bal(); find_ans(); }
cpp
1299
D
D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8 1 2 0 2 3 1 2 4 3 2 6 2 3 4 8 3 5 4 5 4 5 5 6 6 OutputCopy2 InputCopy7 9 1 2 0 1 3 1 2 3 9 2 4 3 2 5 4 4 5 7 3 6 6 3 7 7 6 7 8 OutputCopy1 InputCopy4 4 1 2 27 1 3 1 1 4 1 3 4 0 OutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.
[ "bitmasks", "combinatorics", "dfs and similar", "dp", "graphs", "graphs", "math", "trees" ]
#include<bits/stdc++.h> #define I inline #define ll long long #define db double #define lb long db #define N (100000+5) #define M (500+5) #define K (700+5) #define mod 1000000007 #define Mod (mod-1) #define eps (1e-5) #define ui unsigned int #define ull unsigned ll #define Gc() getchar() #define Me(x,y) memset(x,y,sizeof(x)) #define Mc(x,y) memcpy(x,y,sizeof(x)) #define d(x,y) ((k+1)*(x)+(y)) #define R(n) (rnd()%(n)+1) #define Pc(x) putchar(x) #define LB lower_bound #define UB upper_bound #define PB push_back using namespace std;struct Edge{int to,w;};vector<Edge> S[N]; int n,m,W[M][M],H,x,y,z,Pf[N],vis[N],d[N];ui A[M],Q[N];ll ToT,f[M],g[M],T1,T2;map<ui,int> Is,Fl[50]; I ui Merge(ui x,ui y){if((x&y)>1||!x||!y) return 0;ui z=0;for(int i=0;i<=31;i++)if(x>>i&1) for(int j=0;j<=31;j++)y>>j&1&&(z|=1u<<(i^j));return z;} I void dfs(int x,ui w){if(Fl[x].count(w)) return;Fl[x][w]=1;if(x==32){A[Is[w]=++H]=w;return;}dfs(x+1,w);!(w>>x&1)&&(dfs(x+1,Merge(w,1u<<x|1)),0);} I void FC(int x,int La){vis[x]=1;for(Edge i:S[x]){if(vis[i.to])i.to^La&&i.to^1&&d[i.to]<d[x]&&(T1=(i.w^Q[x]^Q[i.to]?Merge(1u<<(i.w^Q[x]^Q[i.to])|1,T1):0));else Q[i.to]=Q[x]^i.w,d[i.to]=d[x]+1,FC(i.to,x);}} int main(){ // freopen("1.in","r",stdin); int i,j,h;dfs(1,1);scanf("%d%d",&n,&m);for(i=1;i<=m;i++) scanf("%d%d%d",&x,&y,&z),S[x].PB((Edge){y,z}),S[y].PB((Edge){x,z}); Me(W,-1);for(i=1;i<=H;i++) for(j=1;j<=H;j++) W[i][j]=((A[i]&A[j])>1?-1:Is[Merge(A[i],A[j])]); f[Is[1]]=1;vis[1]=1;for(Edge i:S[1]) Pf[i.to]=1,Q[i.to]=i.w;for(i=2;i<=n;i++){ if(!Pf[i]) continue;Mc(g,f);for(Edge j:S[i]){if(!Pf[j.to]) continue; T1=1;T2=j.w^Q[i]^Q[j.to];FC(i,1);Pf[i]=Pf[j.to]=0;if(!T1) break;x=Is[T1];for(h=1;h<=H;h++) ~W[h][x]&&(f[W[h][x]]=(f[W[h][x]]+f[h]*2)%mod); T1=(T2?Merge(T1,1u<<T2|1):0);x=Is[T1];for(h=1;h<=H;h++) ~W[h][x]&&(f[W[h][x]]=(f[W[h][x]]+g[h])%mod); }if(Pf[i]){Pf[i]=0;T1=1;FC(i,1);if(T1) for(x=Is[T1],j=1;j<=H;j++) f[W[j][x]]=(f[W[j][x]]+g[j])%mod;} }for(i=1;i<=H;i++) ToT+=f[i];printf("%lld\n",ToT%mod); }
cpp
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
// CF template, version 3.0 #include <bits/stdc++.h> using namespace std; #define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0) #define getTest int t; cin >> t #define eachTest for (int _var=0;_var<t;_var++) #define get(name) int (name); cin >> (name) #define out(o) cout << (o) #define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); } #define sortl(name) sort((name).begin(), (name).end()) #define rev(name) reverse((name).begin(), (name).end()) #define forto(name, var) for (int (var) = 0; (var) < (name); (var)++) #define decision(b) if (b){out("YES");}else{out("NO");} #define int long long int int gcd(int a, int b) { if (a == b) return a; return gcd(max(a, b), max(a, b) % min(a, b)); } /* Segtree: void build(vector<int> &tree, vector<int> &array, int i, int l, int r) { if (l == r) { tree[i] = array[l]; } else { int middle = (l + r) / 2; build(tree, array, i * 2, l, middle); build(tree, array, i * 2 + 1, middle + 1, r); tree[i] = max(tree[i * 2], tree[i * 2 + 1]); } } void set_(vector<int> &tree, int v, int l, int r, int i, int x) { if (l == r) { tree[v] = x; } else { int middle = (l + r) / 2; if (i <= middle) { set_(tree, v * 2, l, middle, i, x); } else { set_(tree, v * 2 + 1, middle + 1, r, i, x); } tree[v] = max(tree[v * 2], tree[v * 2 + 1]); } } int query(vector<int> &tree, int v, int cl, int cr, int l, int r) { if (l == cl && r == cr) { return tree[v]; } if (l > r) return 0; int middle = (cl + cr) / 2; return max( query(tree, v * 2, cl, middle, l, min(r, middle)), query(tree, v * 2 + 1, middle + 1, cr, max(l, middle + 1), r) ); } vector<int> tree(4 * n); build(tree, initial, 1, 0, n-1); // replace initial with name of array set_(tree, 1, 0, n-1, a, b); query(tree, 1, 0, n-1, a, b); // this returns an int data structure can be changed */ signed main() { improvePerformance; getTest; eachTest { get(n); getList(n, nums); int prefix = 0; int suffix = 0; forto(n, i) { if (nums[i] >= i) { prefix++; } else { break; } } forto(n, i) { if (nums[n - i - 1] >= i) { suffix++; } else { break; } } decision(prefix + suffix > n); out("\n"); } }
cpp
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0), ios::sync_with_stdio(0); int t, n, x; cin >> t; while (t--) { cin >> n; int sum = 0, zeros = 0; while (n--) { cin >> x; if (x == 0) zeros++; sum += x; } cout << (zeros + (sum + zeros == 0)) << '\n'; } }
cpp
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
#include <bits/stdc++.h> #define sz(v) (int) (v).size() #define all(v) begin(v), end(v) #define view(v, l, r) begin(v) + l, begin(v) + r + 1 #define dbg(fmt...) fprintf(stderr, fmt) #define fi first #define se second using namespace std; using i64 = long long; using i128 = __int128_t; using u32 = unsigned; using u64 = unsigned long long; using u128 = __uint128_t; using f64 = double; using f128 = long double; template<typename T> bool chmin(T &a, const T &b) { return (b < a) ? a = b, 1 : 0; } template<typename T> bool chmax(T &a, const T &b) { return (b > a) ? a = b, 1 : 0; } constexpr int M = 18; int buc[1 << M], par[1 << M]; int get(int x) { return par[x] == x ? x : par[x] = get(par[x]); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int m = __lg(*max_element(all(a)) - 1) + 1; iota(par, par + (1 << m), 0); int full = (1 << m) - 1; i64 ans = 0; for (auto &x : a) { ++buc[x]; ans -= x; } ++buc[0]; for (int s = full; s; --s) { for (int u = s; ; u = (u - 1) & s) { int v = s ^ u; if (buc[u] && buc[v] && get(u) != get(v)) { ans += (buc[u] + buc[v] - 1ll) * s; buc[u] = buc[v] = 1; par[get(v)] = get(u); } if (!u) { break; } } } cout << ans; }
cpp
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10 codeforces dodivthree OutputCopy5 7 8 4 9 2 2 9 10 3 1 InputCopy7 abaca?b zabbbcc OutputCopy5 6 5 2 3 4 6 7 4 1 2 InputCopy9 bambarbia hellocode OutputCopy0 InputCopy10 code?????? ??????test OutputCopy10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
[ "greedy", "implementation" ]
#include<iostream> #include <bits/stdc++.h> #include <ext/numeric> using namespace std; //using L = __int128; #include<ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using ll = long long; using ull = unsigned long long; using ld = long double; #define nd "\n" #define all(x) (x).begin(), (x).end() #define lol cout <<"i am here"<<nd; #define py cout <<"YES"<<nd; #define pp cout <<"ppppppppppppppppp"<<nd; #define pn cout <<"NO"<<nd; #define popcount(x) __builtin_popcount(x) #define clz(n) __builtin_clz(n)//31 -x const double PI = acos(-1.0); double EPS = 1e-9; #define print2(x , y) cout <<x<<' '<<y<<nd; #define print3(x , y , z) cout <<x<<' '<<y<<' '<<z<<nd; #define watch(x) cout << (#x) << " = " << x << nd; const ll N = 4e5+500 , LOG = 22 , inf = 1e8 , SQ= 550 , mod= 1e9+7;//998244353; template<class container> void print(container v) { for (auto& it : v) cout << it << ' ' ;cout <<endl;} //template <class Type1 , class Type2> ll fp(ll a , ll p){ if(!p) return 1; ll v = fp(a , p/2); v*=v;return p & 1 ? v*a : v; } template <typename T> using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>; ll mul (ll a, ll b){ return ( ( a % mod ) * ( b % mod ) ) % mod; } ll add (ll a , ll b) { return (a + b + mod) % mod; } template< typename T > using min_heap = priority_queue <T , vector <T > , greater < T > > ; void hi(int tc) { ll n; cin >> n; string a , b; cin >> a >> b; map <char , vector <int > > aa , bb; for (int i = 0; i < n; ++i){ aa[a[i]].emplace_back(i); bb[b[i]].emplace_back(i); } vector <pair <int , int > > ans; for (char i = 'a'; i <= 'z'; ++i){ while (!aa[i].empty() && !bb[i].empty()){ ans.emplace_back(aa[i].back() , bb[i].back()); aa[i].pop_back(); bb[i].pop_back(); } char c = '?'; while (!aa[c].empty() && !bb[i].empty()){ ans.emplace_back(aa[c].back() , bb[i].back()); aa[c].pop_back(); bb[i].pop_back(); } while (!bb[c].empty() && !aa[i].empty()){ ans.emplace_back(aa[i].back() , bb[c].back()); aa[i].pop_back(); bb[c].pop_back(); } } char c = '?'; while (!bb[c].empty() && !aa[c].empty()){ ans.emplace_back(aa[c].back() , bb[c].back()); aa[c].pop_back(); bb[c].pop_back(); } cout << (int)ans.size() << endl; for (auto &i : ans) cout << i.first+1 <<" "<<i.second+1<<nd; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int tt = 1 , tc = 0; //cin >> tt; while(tt--) hi(++tc); return 0; }
cpp
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" ]
//Dhiraj's Template #include <bits/stdc++.h> using namespace std; #define int long long #define testcase int t;cin>>t;while(t--) #define forloop(start,size) for(int i=start;i<size;i++) #define all(v) v.begin(),v.end() #define foreachx(v) for(auto&x:v) #define maxofvec(v) *max_element(v.begin(),v.end()) #define minofvec(v) *min_element(v.begin(),v.end()) #define M 1000000007 void D(){ // int a,b,c; // cin>>a>>b>>c; // int count=0; // if(a>0){ // a = a-1; // count++; // } // if(b>0){ // b = b-1; // count++; // } // if(c>0){ // c = c-1; // count++; // } // if(a>0 && b>0){ // a = a-1; // b = b-1; // count++; // } // if(a>0 && c>0){ // a = a-1; // c = c-1; // count++; // } // if(c>0 && b>0){ // c = c-1; // b = b-1; // count++; // } // if(a>0 && b>0 && c>0){ // count++; // } // cout<<count<<endl; int count=0; int arr[3]; forloop(0,3){ cin>>arr[i]; } sort(arr,arr+3); if(arr[0]>0){ count++; arr[0]--; } if(arr[1]>0){ count++; arr[1]--; } if(arr[2]>0){ count++; arr[2]--; } sort(arr,arr+3); if(arr[2]>0 && arr[1]>0){ count++; arr[2]--; arr[1]--; } if(arr[2]>0 && arr[0]>0){ count++; arr[2]--; arr[0]--; } if(arr[0]>0 && arr[1]>0){ count++; arr[0]--; arr[1]--; } if(arr[0]>0 && arr[1]>0 && arr[2]>0){ count++; } cout<<count<<endl; } signed main(){ testcase{ D(); } return 0; }
cpp
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define vec vector #define ar array #define UNIQUE(c) (c).resize(unique(all(c)) - (c).begin()) #define dbg(...) [](const auto&...x){ char c='='; cerr<<#__VA_ARGS__<<" "; ((cerr<<exchange(c,',')<<" "<<x),...); cerr<<endl; }(__VA_ARGS__); const ld PI = 2 * acos(0.0); template<typename T> using minpq = priority_queue<T, vector<T>, greater<T>>; int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 }; int dy[] = { -1, 1, 0, 0, -1, 1, 1, -1 }; // function<returnType(args) name = [&] // work smart not hard // self reflect const ll mod = 1e9 + 7; const int N = 1e5 + 5; ll fact[N]; ll invfact[N]; ll fpow(ll x, ll n) { if (n == 0) return 1; ll u = fpow(x, n / 2); (u *= u) %= mod; if (n & 1) u = u * x % mod; return u; } void calc() { fact[0] = 1; for (ll i = 1; i < N; i++) { fact[i] = fact[i - 1] * i % mod; } invfact[N - 1] = fpow(fact[N - 1], mod - 2); for (ll i = N - 2; i >= 0; i--) { invfact[i] = (i + 1) * invfact[i + 1] % mod; } } ll ncr(ll n, ll r) { if (r > n) return 0; return (fact[n] % mod * invfact[r] % mod * invfact[n - r] % mod) % mod; } void solve() { calc(); ll n, m; cin >> n >> m; cout << ncr(2 * m + n - 1, n - 1) << '\n'; } int main() { cin.tie(0); cin.sync_with_stdio(0); //cout << setprecision(6) << fixed; int T = 1; //cin >> T; int x = T; while (T--) { //cout << "Case #" << x - T << ": "; solve(); } }
cpp
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
#pragma GCC optimize("Ofast","inline","-ffast-math") #pragma GCC target("avx,avx2,fma,mmx,sse2,sse3,sse4") #pragma GCC optimization("unroll-loops") ///for pragma could get a runtime/tle too #include<bits/stdc++.h> using namespace std; #define ll long long #define ff first #define ss second #define pb push_back #define yes "YES"<<endll #define no "NO"<<endll #define sp ' ' #define Case(i) cout<<"Case "<<i<<": " #define endll '\n' #define ub upper_bound #define lb lower_bound #define mod 1000000007 #define M 100005 #define nd node+node #define left st,(st+en)/2,nd #define right (st+en)/2+1,en,nd+1 #define sz(v) (int)v.size() #define mem(x,y) memset(x,y,sizeof(x)) #define uniq(v) v.resize(distance(v.begin(),unique(v.begin(),v.end()))) #define rep(i,n) for(int i=0; i<n; i++) #define reprev(i,n) for(int i=n-1; i>=0; i--) #define repok(i,n,ok) for(int i=0; i<n && ok; i++) #define repn(i,n) for(int i=1; i<=n; i++) #define all(v) v.begin(),v.end() #define esp 0.000001 void fast(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main(){ fast(); // freopen("run_in.txt","r",stdin); // freopen("run_out.txt","w",stdout); int t=1, tc=0; //cin>>t; while(t--){ ll n, m, ans=1, x; cin>>n>>m; vector<int>v(n); rep(i,n) cin>>v[i]; if(n>m){ cout<<0; return 0; } rep(i,n){ for(int j=i+1; j<n; j++) ans = (ans*abs(v[j]-v[i]))%m; } cout<<ans; } }
cpp
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
#include<bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define multiordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> #define lop(i,n) for(ll i=0;i<n;i++) #define lop1(i,n) for(ll i=1;i<=n;i++) #define lopr(i,n) for(ll i=n-1;i>=0;i--) #define ll long long int #define pb push_back #define all(v) v.begin(),v.end() #define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define endl '\n' #define ff first #define ss second #define mem(arr,val) memset(arr,val,sizeof(arr)) #define pii pair<int,int> #define pll pair<ll,ll> #define LCM(a,b) (a/__gcd(a,b))*b #define mii map<int,int> #define mll map<ll,ll> #define ub upper_bound #define lb lower_bound #define sz(x) (ll)x.size() #define ld long double #define pcnt(x) __builtin_popcountll(x) #define yes cout<<"YES"<<endl #define no cout<<"NO"<<endl const long long I1=1e9; const long long I2=1e18; const int32_t M1=1e9+7; const int32_t M2=998244353; ll binpow(ll a, ll b) { ll res=1; while(b>0) { if(b%2==1) res=res*a; a=a*a; b=b/2; } return res; } ll binexp(ll a, ll b, ll mod) { ll res=1; while(b>0) { if(b%2==1) res=((res%mod)*(a%mod))%mod; a=((a%mod)*(a%mod))%mod; b=b/2; } return res; } ll fact(ll n,ll mod) { ll ans=1; for(ll i=2;i<=n;i++) ans=((ans%mod)*(i%mod)+mod)%mod; ans%=mod; return ans; } ll nCr(ll n,ll r,ll mod) { ll ri=binexp(fact(r,mod),mod-2,mod); ll nri=binexp(fact(n-r,mod),mod-2,mod); ll ans=(((fact(n,mod)%mod)*(ri%mod))%mod); ans=(((ans%mod)*(nri%mod))%mod); ans%=mod; ans=(ans+mod)%mod; return ans; } void solve() { ll n; cin>>n; ll arr[n],t[n]; lop(i,n) cin>>arr[i]; lop(i,n) cin>>t[i]; vector<pll> v(n); lop(i,n) v[i]={arr[i],t[i]}; sort(all(v)); multiset<ll> s; ll i=0; ll sum=0; ll c=v[0].ff; ll ans=0; while(i<n) { if(sz(s)==0) { c=v[i].ff; sum=0; } if(v[i].ff==c) { s.insert(v[i].ss); sum+=v[i].ss; i++; } else { sum-=*--s.end(); s.erase(--s.end()); ans+=sum; c++; } } ll a=sz(s)-1; for(auto it:s) { ans+=a*it; a--; } cout<<ans; } int main() { IOS; //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); ll t; t=1; //cin>>t; while(t--) { solve(); } }
cpp
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
// ඞ #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #ifdef LOCAL #include "debug.h" #define dbg(...) debug_out(splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__) #else #define dbg(...) #endif #define int long long #define ALL(v) (v).begin(), (v).end() #define mem(a, x) memset(a , x , sizeof(a)) #define F first #define S second #define pb push_back #define popCnt __builtin_popcountll typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef pair <int, int> pii; typedef vector<pair <int, int>> vpii; typedef vector<vector<char>> vvc; const int mod = 1e9 + 7; const int oo = 0x5f5f5f5f; const long double PI = acos(-1.0L); int Log2 (int x) {return 31 - __builtin_clz(x);} int ceiledLog2 (int x){return Log2(x) + (__builtin_popcount(x) != 1);} ll toLL (int first, int second, int mx){return (1LL*first*mx) + second;} vi Unique(vi x){sort(ALL(x));x.resize(distance(x.begin(),unique(ALL(x))));return x;} template <class T, class U> T GCD (T a, U b) {return (!b ? a : GCD(b, a%b));} template <class T, class U> T LCM (T a, U b) {return ((a/GCD(a, b)) * b);} template <class T> bool isSquare (T n) {T sq = sqrt(n); return (sq*sq)==n;} template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //bool sortBySecond (pii &a, pii &b) {return a.second < b.second;} //asc int ys[] = {-1, -1, 0, 1, 1, 1, 0, -1}; //edges [0, 2, 4, 6] int xs[] = {0, 1, 1, 1, 0, -1, -1, -1}; //-----------------------------------------------------------------------------// int n, z, o; vector<int> a; int dp[100][2][55][55]; int solve(int idx, int last, int usedZ, int usedO) { if (idx == n) return 0; if (~dp[idx][last][usedZ][usedO]) return dp[idx][last][usedZ][usedO]; if (a[idx] == -1) { int ans1=100, ans2=100; if (usedO < o) { ans1 = solve(idx+1, 1, usedZ, usedO+1) + (last != 1); } if (usedZ < z) { ans2 = solve(idx + 1, 0, usedZ+1, usedO) + (last != 0); } return dp[idx][last][usedZ][usedO] = min(ans1, ans2); } return dp[idx][last][usedZ][usedO] = solve(idx + 1, a[idx], usedZ, usedO) + (a[idx] != last); } void run_test () { mem(dp,-1); cin >> n; a = vi(n); z += n/2; o += n/2 + n%2; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] != 0) { a[i] %= 2; z -= (a[i]==0); o -= a[i]; } else a[i] = -1; } dbg(o,z); if (a[0] == -1) { int ans1 = 100,ans2 = 100; if (o) ans1 = solve(1, 1, 0, 1); if (z) ans2 = solve(1, 0, 1, 0); cout << min(ans1,ans2); } else cout << solve(1, a[0], 0, 0); } void initialize(char _mode = 's'); int32_t main() { initialize(); //cout << fixed << setprecision (9); int tc = 1; //cin >> tc; for (int t=1; t <= tc; t++) { //cout << "Case #" << t << ": "; run_test(); } cerr << "$time taken: " << (float) clock() / CLOCKS_PER_SEC << " seconds" << endl; return 0; } void initialize(char _mode){ //s,d,c,x if (_mode == 's' || _mode == 'c'){ ios::sync_with_stdio(false); cin.tie(nullptr); } #ifdef LOCAL if (_mode == 's' || _mode == 'd'){ freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } #endif }
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> #define ll long long using namespace std; int T,a,b,c,d,a1,a2; string s; #define ios std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) int main() { ios; cin >> T; while (T--) { cin >> a >> b >> c >> d; c++; d++; a1 = max((c-1) * b,(a-c) *b); a2 = max((d-1)*a,(b-d)*a); a1 = max(a1, a2); cout << a1 << endl; } return 0; }
cpp
1292
F
F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3 2 6 8 OutputCopy2 InputCopy5 2 3 4 9 12 OutputCopy4 InputCopy4 5 7 2 9 OutputCopy1 NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.
[ "bitmasks", "combinatorics", "dp" ]
#include<bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define rep(i, a, b) for(int i = (a); i <= (b); i ++) #define per(i, a, b) for(int i = (a); i >= (b); i --) #define Ede(i, u) for(int i = head[u]; i; i = e[i].nxt) using namespace std; #define eb emplace_back const int P = 1e9 + 7; inline int plu(int x, int y) {return x + y >= P ? x + y - P : x + y;} inline int del(int x, int y) {return x - y < 0 ? x - y + P : x - y;} inline void add(int &x, int y) {x = plu(x, y);} inline void sub(int &x, int y) {x = del(x, y);} inline int qpow(int a, int b) {int s = 1; for(; b; b >>= 1, a = 1ll * a * a % P) if(b & 1) s = 1ll * s * a % P; return s;} inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') f = (c == '-') ? - 1 : 1, c = getchar(); while(c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x * f; } const int N = 65, M = 1 << 15; int n, a[N], par[N], deg[N], mask[N], f[M], g[M][N], binom[N][N]; vector<int> con[N]; int find(int x) {return x == par[x] ? x : par[x] = find(par[x]);} void fwt(int *f, int n) { for(int o = 2, k = 1; o <= (1 << n); o <<= 1, k <<= 1) for(int i = 0; i < (1 << n); i += o) rep(j, 0, k - 1) add(f[i + j + k], f[i + j]); } int main() { n = read(); rep(i, 1, n) a[i] = read(), par[i] = i; sort(a + 1, a + n + 1); rep(i, 1, n) rep(j, i + 1, n) if(a[j] % a[i] == 0) par[find(j)] = find(i), deg[j] ++; rep(i, 1, n) con[find(i)].eb(i); binom[0][0] = 1; rep(i, 1, n) { binom[i][0] = binom[i][i] = 1; rep(j, 1, i - 1) binom[i][j] = plu(binom[i - 1][j], binom[i - 1][j - 1]); } int ans = 1, sum = 0; rep(i, 1, n) if(con[i].size() > 1) { vector<int> s, t; int cnt = 0; for(int o : con[i]) if(! deg[o]) s.eb(o); else cnt ++, t.eb(o); int len = s.size(); rep(x, 0, (1 << len) - 1) {f[x] = 0; rep(y, 0, cnt) g[x][y] = 0;} for(int o : t) { rep(p, 0, len - 1) if(a[o] % a[s[p]] == 0) mask[o] |= (1 << p); f[mask[o]] ++; } fwt(f, len); g[0][0] = 1; rep(x, 0, (1 << len) - 1) rep(y, 0, cnt) if(g[x][y]) { if(f[x] > y) add(g[x][y + 1], 1ll * g[x][y] * (f[x] - y) % P); for(int o : t) if((mask[o] & x) != mask[o] && (x == 0 || (mask[o] & x))) add(g[x | mask[o]][y + 1], g[x][y]); // cerr << x << ' ' << y << ' ' << g[x][y] << endl; } ans = 1ll * ans * g[(1 << len) - 1][cnt] % P * binom[sum + cnt - 1][cnt - 1] % P; sum += cnt - 1; } printf("%d\n", ans); 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 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>; struct Edge{ int src; int dst; Edge(int _src, int _dst) : src(_src), dst(_dst){} }; using Graph = Vec<Vec<Edge>>; int C[2002]; bool dfs(int v, Graph &g, VVi &ans){ int n = 0; bool aflag = false; bool rflag = true; for (auto e: g[v]){ int v1 = e.dst; rflag &= dfs(v1, g, ans); rep(i,ans[v1].size()){ n++; if (n-1==C[v]){ aflag = true; ans[v].push_back(v+1); n++; } ans[v].push_back(ans[v1][i]); } } if (n==C[v]){ aflag = true; ans[v].push_back(v+1); n++; } //cout << n << endl; return aflag & rflag; } int main(){ cin.tie(0)->sync_with_stdio(0); int n; cin >> n; Vi p(n); int root; rep(i,n) cin >> p[i] >> C[i]; Graph g(n, Vec<Edge>()); rep(i,n){ if(p[i]!=0){ p[i]--; g[p[i]].push_back(Edge(p[i],i)); } else { root = i; } } VVi ans(n); if (dfs(root, g, ans)){ Vi a(n); cout << "YES" << endl; rep(i,n){ a[ans[root][i]-1] = i+1; } rep(i,n) cout << a[i] << " "; cout << endl; } else { cout << "NO" << endl; } }
cpp
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
#include<bits/stdc++.h> #define ll long long int #define pii pair<ll,ll> using namespace std ; void solve() { ll n ; cin>>n ; vector<ll>dp(n,0); map<ll,ll>mp ; vector<ll>v(n,0); for(ll i = 0 ; i < n ; i++){ cin>>v[i]; mp[i-v[i]] += v[i] ; } ll maxi = 0 ; for(auto it : mp) maxi = max(maxi,it.second) ; cout<<maxi<<endl; } int main(){ ios::sync_with_stdio(0); cin.tie(0); // ll T ; // cin>>T ; // while(T--){ solve() ; // } } bool isPowerOfTwo (int x) { return x && (!(x&(x-1))); }
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" ]
// #pragma GCC optimize("O3") // #pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include "complex" using namespace std; using namespace __gnu_pbds; // template <class T> // using o_set = tree<T, int_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key (val): returns the no. of values less than val // find_by_order (k): returns the kth largest element.(0-based) #define int long long typedef pair<int, int> II; typedef vector<II> VII; typedef vector<int> VI; typedef vector<VI> VVI; typedef long long LL; #define PB push_back #define MP make_pair #define F first #define S second #define SZ(a) (int)(a.size()) #define ALL(a) a.begin(), a.end() #define SET(a, b) memset(a, b, sizeof(a)) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define si(n) scanf("%d", &n) #define dout(n) printf("%d\n", n) #define sll(n) scanf("%lld", &n) #define lldout(n) printf("%lld\n", n) #define fast_io \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) #define endl "\n" const long long mod = 1e9 + 7; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); void prec() { } const int N = (int)2e5 + 1; int A[N]; int n; int ans = mod * mod; int calc(int x) { int fans = 0; for (int i = 0; i < n; i++) { if (A[i] <= x) fans += x - A[i]; else { int y = A[i] % x; fans += min(y, x - y); } if (fans >= ans) return ans; } return fans; } int modpow(long long x, unsigned int y, int p) { // calculates x^y int res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if (y & 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } int modmul(int x, int y, int p) { x = x % p, y = y % p; return (__int128)x * y % p; } bool isPrime(int n) { if (n < 2 || n % 6 % 4 != 1) return (n | 1) == 3; int A[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}, s = __builtin_ctzll(n - 1), d = n >> s; for (int a : A) { // ^ count trailing int p = modpow(a % n, d, n), i = s; while (p != 1 && p != n - 1 && a % n && i--) p = modmul(p, p, n); if (p != n - 1 && i != s) return 0; } return 1; } int pollard(int n) { auto f = [n](int x) { return modmul(x, x, n) + 1; }; int x = 0, y = 0, t = 30, prd = 2, i = 1, q; while (t++ % 40 || __gcd(prd, n) == 1) { if (x == y) x = ++i, y = f(x); if ((q = modmul(prd, max(x, y) - min(x, y), n))) prd = q; x = f(x), y = f(f(y)); } return __gcd(prd, n); } vector<int> factor(int n) { if (n == 1) return {}; if (isPrime(n)) return {n}; int x = pollard(n); auto l = factor(x), r = factor(n / x); l.insert(l.end(), ALL(r)); return l; } void solve() { cin >> n; for (int i = 0; i < n; i++) { cin >> A[i]; } ans = calc(2); for (int i = 0; i < 40; i++) { int id = rng() % n; for (int j = 1; j > -2 && A[id] + j > 1; j--) { int x = A[id] + j; // for this x, do something // vector<int> p = factor(x); for (int y = 2; y * y <= x; y++) { if (x % y == 0) { ans = min(ans, calc(y)); while (x % y == 0) { x /= y; } } } if (x > 1) ans = min(ans, calc(x)); } } cout << ans << endl; } signed main() { fast_io; prec(); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int totalTests = 1; // cin >> totalTests; for (int testNo = 1; testNo <= totalTests; testNo++) { // cout << "Case #" << testNo << ": "; solve(); } return 0; }
cpp
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
/* DavitMarg In a honky-tonk, Down in Mexico */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string> #include <cstring> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <random> #include <bitset> #include <stack> #include <cassert> #include <iterator> #define mod 1000000007ll #define LL long long #define LD long double #define MP make_pair #define PB push_back #define all(v) v.begin(), v.end() #define fastIO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; const int N = 500005; LL binpow(LL a, LL n) { if (n == 0) return 1; if (n % 2 == 0) return binpow((a * a) % mod, n / 2); return (a * binpow(a, n - 1)) % mod; } LL prm = 13, p[N], ip[N]; int n,pr[N]; string s; int q; pair<pair<LL, LL>, pair<char, char>> t[N * 4]; LL val(char x) { return (x - '0' + 1ll); } pair<pair<LL, LL>, pair<char,char>> merge(pair<pair<LL, LL>, pair<char,char>> a, pair<pair<LL, LL>, pair<char,char>> b) { if (a.second.second == '1' && b.second.first == '1') { a.first.first += (mod - ((val(a.second.second) * p[a.first.second]) % mod)) % mod; a.first.first %= mod; a.first.second--; a.second.second = '0'; b.first.first += (mod - ((val(b.second.first) * p[1]) % mod)) % mod; b.first.first %= mod; b.first.first *= ip[1]; b.first.first %= mod; b.first.second--; b.second.first = '0'; } if (a.first.second == 0 && b.first.second == 0) return MP(MP(0, 0), MP('0', '0')); if (b.first.second == 0) return a; if (a.first.second == 0) return b; a.first.first += (b.first.first * p[a.first.second]) % mod; a.first.first %= mod; a.first.second += b.first.second; a.second.second = b.second.second; return a; } void build(int v, int l, int r) { int k = 0; if (l == r) { t[v].first.first = p[1] * val(s[l]); t[v].first.second = 1; t[v].second = MP(s[l], s[r]); return; } int m = (l + r) / 2; build(v * 2, l, m); build(v * 2 + 1, m + 1, r); t[v] = merge(t[v * 2], t[v * 2 + 1]); } pair<pair<LL, LL>, pair<char,char>> get(int v, int l, int r, int i, int j) { if (l == i && r == j) return t[v]; int m = (l + r) / 2; if (j <= m) return get(v * 2, l, m, i, j); else if (i >= m + 1) return get(v * 2 + 1, m + 1, r, i, j); return merge( get(v * 2, l, m, i, min(j, m)), get(v * 2 + 1, m + 1, r, max(i, m + 1), j) ); } void solve() { cin >> n >> s >> q; s = "#" + s; p[0] = ip[0] = 1; for (int i = 1; i <= n;i++) { pr[i] = pr[i - 1] + s[i] - '0'; p[i] = (p[i - 1] * prm) % mod; ip[i] = binpow(p[i], mod - 2); } build(1, 1, n); while (q--) { int l, r, len; cin >> l >> r >> len; if (get(1, 1, n, l, l + len - 1).first.first == get(1, 1, n, r, r + len - 1).first.first && (pr[l + len - 1] - pr[l - 1]) == (pr[r + len - 1] - pr[r - 1])) cout << "yes" << endl; else cout << "no" << endl; } } int main() { //fastIO; int T = 1; //cin >> T; while (T--) { solve(); } return 0; } /* */
cpp
1322
E
E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5 1 2 1 2 1 OutputCopy2 1 1 1 1 1 InputCopy6 1 3 2 5 4 6 OutputCopy1 1 2 3 4 5 6 InputCopy6 1 1 2 2 1 1 OutputCopy0 1 1 2 2 1 1 NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00.
[ "data structures" ]
// BEGIN BOILERPLATE CODE #include <bits/stdc++.h> using namespace std; #ifdef KAMIRULEZ const bool kami_loc = true; const long long kami_seed = 69420; #else const bool kami_loc = false; const long long kami_seed = chrono::steady_clock::now().time_since_epoch().count(); #endif const string kami_fi = "kamirulez.inp"; const string kami_fo = "kamirulez.out"; mt19937_64 kami_gen(kami_seed); long long rand_range(long long rmin, long long rmax) { uniform_int_distribution<long long> rdist(rmin, rmax); return rdist(kami_gen); } long double rand_real(long double rmin, long double rmax) { uniform_real_distribution<long double> rdist(rmin, rmax); return rdist(kami_gen); } void file_io(string fi, string fo) { if (fi != "" && (!kami_loc || fi == kami_fi)) { freopen(fi.c_str(), "r", stdin); } if (fo != "" && (!kami_loc || fo == kami_fo)) { freopen(fo.c_str(), "w", stdout); } } void set_up() { if (kami_loc) { file_io(kami_fi, kami_fo); } ios_base::sync_with_stdio(0); cin.tie(0); } void just_do_it(); void just_exec_it() { if (kami_loc) { auto pstart = chrono::steady_clock::now(); just_do_it(); auto pend = chrono::steady_clock::now(); long long ptime = chrono::duration_cast<chrono::milliseconds>(pend - pstart).count(); string bar(50, '='); cout << '\n' << bar << '\n'; cout << "Time: " << ptime << " ms" << '\n'; } else { just_do_it(); } } int main() { set_up(); just_exec_it(); return 0; } // END BOILERPLATE CODE // BEGIN MAIN CODE const int ms = 5e5 + 20; const int inf = 1e9 + 20; int tr[ms << 2]; int cnt[ms]; int a[ms]; pair<int, int> p[ms]; int b[ms]; int res[ms]; int pos; void fix(int &lt, int &rt) { if (lt == 0) { lt = -inf; rt = inf; } else if (b[lt] == 1 && b[rt] == 1) { lt = -inf; rt = inf; } else if (b[lt] == 2 && b[rt] == 1) { rt = (lt + rt) >> 1; } else if (b[lt] == 1 && b[rt] == 2) { lt = ((lt + rt) >> 1) + 1; } } void inter(int &l1, int &r1, int l2, int r2) { if (l1 > r1 || l2 == -inf) { return; } if (l1 <= min(r1, l2 - 1)) { r1 = min(r1, l2 - 1); } else if (max(l1, r2 + 1) <= r1) { l1 = max(l1, r2 + 1); } else { l1 = inf; r1 = -inf; } } void update(int l1, int r1, int l2, int r2, int l3, int r3, int val) { fix(l1, r1); if (l1 == -inf) { return; } b[pos] = 1; fix(l2, r2); fix(l3, r3); b[pos] = 2; inter(l1, r1, l2, r2); inter(l1, r1, l3, r3); for (int i = l1; i <= r1; i++) { if (res[i] != -1) { exit(0); } res[i] = val; } } void update(int cc, int lt, int rt, int px, int pp) { if (lt == rt) { cnt[lt] += pp; tr[cc] = (cnt[lt] ? lt : -inf); return; } int mt = (lt + rt) >> 1; if (px <= mt) { update(cc << 1, lt, mt, px, pp); } else { update(cc << 1 | 1, mt + 1, rt, px, pp); } tr[cc] = max(tr[cc << 1], tr[cc << 1 | 1]); } void just_do_it() { fill_n(tr, ms << 2, -inf); int n, k; cin >> n; k = 1; //cin >> k; set<int> s; //multiset<int> len; for (int i = 1; i <= n; i++) { cin >> a[i]; p[i] = {a[i], i}; b[i] = 1; res[i] = -1; s.insert(i); update(1, 1, n, 1, 1); } int mx = 1; sort(p + 1, p + n + 1, greater<>()); for (int i = 1; i <= n; i++) { int l1 = -1; int r1 = -1; int l2 = -1; int r2 = -1; int l3 = -1; int r3 = -1; int val = p[i].first; pos = p[i].second; auto it = prev(s.upper_bound(pos)); l2 = (*it); if (it != s.begin()) { it--; r1 = l2 - 1; l1 = (*it); it++; } it++; if (it == s.end()) { r2 = n; } else { r2 = (*it) - 1; l3 = r2 + 1; it++; if (it == s.end()) { r3 = n; } else { r3 = (*it) - 1; } } b[pos] = 2; if (l2 == r2 && l2 > 1 && r2 < n) { update(l1, r3, l1, r1, l3, r3, val); //len.erase(len.find(r1 - l1 + 1)); update(1, 1, n, r1 - l1 + 1, -1); s.erase(l2); //len.erase(len.find(r2 - l2 + 1)); update(1, 1, n, r2 - l2 + 1, -1); s.erase(l3); //len.erase(len.find(r3 - l3 + 1)); update(1, 1, n, r3 - l3 + 1, -1); //len.insert(r3 - l1 + 1); update(1, 1, n, r3 - l1 + 1, 1); } else { //len.erase(len.find(r2 - l2 + 1)); update(1, 1, n, r2 - l2 + 1, -1); if (pos > l2) { update(l2, pos - 1, l2, r2, 0, 0, val); //len.insert(pos - l2); update(1, 1, n, pos - l2, 1); } else { s.erase(l2); } if (pos < r2) { update(pos + 1, r2, l2, r2, 0, 0, val); s.insert(pos + 1); //len.insert(r2 - pos); update(1, 1, n, r2 - pos, 1); } if (pos == l2 && l2 > 1) { update(l1, pos, l1, r1, 0, 0, val); //len.erase(len.find(r1 - l1 + 1)); update(1, 1, n, r1 - l1 + 1, -1); //len.insert(pos - l1 + 1); update(1, 1, n, pos - l1 + 1, 1); } else if (pos == r2 && r2 < n) { update(pos, r3, l3, r3, 0, 0, val); s.erase(l3); //len.erase(len.find(r3 - l3 + 1)); update(1, 1, n, r3 - l3 + 1, -1); s.insert(pos); //len.insert(r3 - pos + 1); update(1, 1, n, r3 - pos + 1, 1); } else { update(pos, pos, l2, r2, 0, 0, val); s.insert(pos); //len.insert(1); update(1, 1, n, 1, 1); } } if (val != p[i + 1].first) { //mx = max(mx, *len.rbegin()); mx = max(mx, tr[1]); } } cout << ((mx - 1) >> 1) << '\n'; if (k == 1) { for (int i = 1; i <= n; i++) { cout << res[i] << " "; } } } // END MAIN CODE
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() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int32_t test; cin >> test; int32_t n, tmp; bool check; while (test--) { cin >> n; set <int32_t> st; for (int i = 0; i < n; i++) { cin >> tmp; st.insert(tmp); } if (st.size() == 1) cout << "YES\n"; else { vector <int32_t> scan; for (auto &x : st) scan.push_back(x); check = true; for (int i = 1; i < scan.size() && check; i++) if ((scan[i] - scan[i-1])%2 != 0) check = false; if (check) cout << "YES\n"; else cout << "NO\n"; } } return 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> #include<algorithm> #include<vector> #include<unordered_map> typedef long long ll; using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; int counter=0; int p; cin>>p; for(int i=1;i<n;i++) { int q; cin>>q; if(abs(p-q)%2!=0) { counter=1; } p=q; } if(counter==0) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
cpp
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
#include<bits/stdc++.h> using namespace std; long long n , x , y , z , dp [10004][4] , arr [300005]; vector < int > bt [4]; int grundy ( long long x , int y ) { if ( x < 2e3 ) return dp [x][y]; else { int xx = ( x - 1000 ) % bt [y] . size (); return bt [y][xx]; } } int main() { int t; cin >> t; while ( t -- ) { scanf ( "%lld%lld%lld%lld" , &n , &x , &y , &z ); int xr = 0; for ( int i = 1 ; i <= 2e3 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { int a = max ( i - x , 0ll ); int b = max ( i - y , 0ll ); int c = max ( i - z , 0ll ); vector < int > v; if ( j == 0 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); v . push_back ( dp [c][2] ); } if ( j == 1 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [c][2] ); } if ( j == 2 ) { v . push_back ( dp [a][0] ); v . push_back ( dp [b][1] ); } sort ( v . begin () , v . end () ); v . resize ( unique ( v . begin () , v . end () ) - v . begin () ); dp [i][j] = -1; for ( int z = 0 ; z < v . size () ; z ++ ) { if ( v [z] != z ) { dp [i][j] = z; break; } } if ( dp [i][j] == -1 ) dp [i][j] = v . size (); } } bt [0] . clear (); bt [1] . clear (); bt [2] . clear (); for ( int i = 100 ; i <= 300 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { vector < int > a , b; int x = 1000 , y = i; while ( y -- ) a . push_back ( dp [ x ++ ][j] ); y = i; while ( y -- ) b . push_back ( dp [ x ++ ][j] ); if ( a == b ) bt [j] = a; } } if ( bt [0] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [1] . size () == 0 ) cout << 0 / 0 << endl; if ( bt [2] . size () == 0 ) cout << 0 / 0 << endl; for ( int i = 0 ; i < n ; i ++ ) { scanf ( "%lld" , &arr [i] ); xr ^= grundy ( arr [i] , 0 ); } int ans = 0; for ( int i = 0 ; i < n ; i ++ ) { if ( grundy ( max ( arr [i] - x , 0ll ) , 0 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - y , 0ll ) , 1 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; if ( grundy ( max ( arr [i] - z , 0ll ) , 2 ) == ( xr ^ grundy ( arr [i] , 0 ) ) ) ans ++; } printf ( "%d\n" , ans ); } }
cpp
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(){ ios_base::sync_with_stdio(0); cin.tie(0); string brackets; cin >> brackets; int length = brackets.length(); int left = 0, right = length - 1; vector<int> ans; while (left < right){ while (left < right && brackets[left] == ')'){ left++; } while (left < right && brackets[right] == '('){ right--; } if (left < right){ ans.push_back(left + 1); ans.push_back(right + 1); } left++; right--; } sort(ans.begin(), ans.end()); if (ans.size() > 0){ cout<<1<<"\n"; cout<<ans.size()<<"\n"; for (int index: ans){ cout<<index<<" "; } }else{ cout<<0<<"\n"; } cout<<"\n"; return 0; }
cpp
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #ifndef ATCODER_INTERNAL_BITOP_HPP #define ATCODER_INTERNAL_BITOP_HPP 1 #ifdef _MSC_VER #include <intrin.h> #include<cassert> #endif namespace atcoder { namespace internal { int ceil_pow2(int n) { int x = 0; while ((1U << x) < (unsigned int)(n)) x++; return x; } int bsf(unsigned int n) { #ifdef _MSC_VER unsigned long index; _BitScanForward(&index, n); return index; #else return __builtin_ctz(n); #endif } } } #endif #ifndef ATCODER_INTERNAL_MATH_HPP #define ATCODER_INTERNAL_MATH_HPP 1 #include <utility> namespace atcoder { namespace internal { constexpr long long safe_mod(long long x, long long m) { x %= m; if (x < 0) x += m; return x; } struct barrett { unsigned int _m; unsigned long long im; barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {} unsigned int umod() const { return _m; } unsigned int mul(unsigned int a, unsigned int b) const { unsigned long long z = a; z *= b; #ifdef _MSC_VER unsigned long long x; _umul128(z, im, &x); #else unsigned long long x = (unsigned long long)(((unsigned __int128)(z)*im) >> 64); #endif unsigned int v = (unsigned int)(z - x * _m); if (_m <= v) v += _m; return v; } }; constexpr long long pow_mod_constexpr(long long x, long long n, int m) { if (m == 1) return 0; unsigned int _m = (unsigned int)(m); unsigned long long r = 1; unsigned long long y = safe_mod(x, m); while (n) { if (n & 1) r = (r * y) % _m; y = (y * y) % _m; n >>= 1; } return r; } constexpr bool is_prime_constexpr(int n) { if (n <= 1) return false; if (n == 2 || n == 7 || n == 61) return true; if (n % 2 == 0) return false; long long d = n - 1; while (d % 2 == 0) d /= 2; int v[] = { 2,7,61 }; for (long long a : v) { long long t = d; long long y = pow_mod_constexpr(a, t, n); while (t != n - 1 && y != 1 && y != n - 1) { y = y * y % n; t <<= 1; } if (y != n - 1 && t % 2 == 0) { return false; } } return true; } template <int n> constexpr bool is_prime = is_prime_constexpr(n); constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) { a = safe_mod(a, b); if (a == 0) return { b, 0 }; long long s = b, t = a; long long m0 = 0, m1 = 1; while (t) { long long u = s / t; s -= t * u; m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b auto tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return { s, m0 }; } constexpr int primitive_root_constexpr(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int divs[20] = {}; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long long)(i)*i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { bool ok = true; for (int i = 0; i < cnt; i++) { if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } template <int m> constexpr int primitive_root = primitive_root_constexpr(m); } } #endif #ifndef ATCODER_INTERNAL_QUEUE_HPP #define ATCODER_INTERNAL_QUEUE_HPP 1 #include <vector> namespace atcoder { namespace internal { template <class T> struct simple_queue { std::vector<T> payload; int pos = 0; void reserve(int n) { payload.reserve(n); } int size() const { return int(payload.size()) - pos; } bool empty() const { return pos == int(payload.size()); } void push(const T& t) { payload.push_back(t); } T& front() { return payload[pos]; } void clear() { payload.clear(); pos = 0; } void pop() { pos++; } }; } } #endif #ifndef ATCODER_INTERNAL_SCC_HPP #define ATCODER_INTERNAL_SCC_HPP 1 #include <algorithm> #include <utility> #include <vector> namespace atcoder { namespace internal { template <class E> struct csr { std::vector<int> start; std::vector<E> elist; csr(int n, const std::vector<std::pair<int, E>>& edges) : start(n + 1), elist(edges.size()) { for (auto e : edges) { start[e.first + 1]++; } for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; } auto counter = start; for (auto e : edges) { elist[counter[e.first]++] = e.second; } } }; struct scc_graph { public: scc_graph(int n) : _n(n) {} int num_vertices() { return _n; } void add_edge(int from, int to) { edges.push_back({ from, {to} }); } std::pair<int, std::vector<int>> scc_ids() { auto g = csr<edge>(_n, edges); int now_ord = 0, group_num = 0; std::vector<int> visited, low(_n), ord(_n, -1), ids(_n); visited.reserve(_n); auto dfs = [&](auto self, int v) -> void { low[v] = ord[v] = now_ord++; visited.push_back(v); for (int i = g.start[v]; i < g.start[v + 1]; i++) { auto to = g.elist[i].to; if (ord[to] == -1) { self(self, to); low[v] = std::min(low[v], low[to]); } else { low[v] = std::min(low[v], ord[to]); } } if (low[v] == ord[v]) { while (true) { int u = visited.back(); visited.pop_back(); ord[u] = _n; ids[u] = group_num; if (u == v) break; } group_num++; } }; for (int i = 0; i < _n; i++) { if (ord[i] == -1) dfs(dfs, i); } for (auto& x : ids) { x = group_num - 1 - x; } return { group_num, ids }; } std::vector<std::vector<int>> scc() { auto ids = scc_ids(); int group_num = ids.first; std::vector<int> counts(group_num); for (auto x : ids.second) counts[x]++; std::vector<std::vector<int>> groups(ids.first); for (int i = 0; i < group_num; i++) { groups[i].reserve(counts[i]); } for (int i = 0; i < _n; i++) { groups[ids.second[i]].push_back(i); } return groups; } private: int _n; struct edge { int to; }; std::vector<std::pair<int, edge>> edges; }; } } #endif #ifndef ATCODER_INTERNAL_TYPE_TRAITS_HPP #define ATCODER_INTERNAL_TYPE_TRAITS_HPP 1 #include <cassert> #include <numeric> #include <type_traits> namespace atcoder { namespace internal { #ifndef _MSC_VER template <class T> using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type; template <class T> using make_unsigned_int128 = typename std::conditional<std::is_same<T, __int128_t>::value, __uint128_t, unsigned __int128>; template <class T> using is_integral = typename std::conditional<std::is_integral<T>::value || is_signed_int128<T>::value || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_signed_int = typename std::conditional<(is_integral<T>::value&& std::is_signed<T>::value) || is_signed_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<(is_integral<T>::value&& std::is_unsigned<T>::value) || is_unsigned_int128<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional< is_signed_int128<T>::value, make_unsigned_int128<T>, typename std::conditional<std::is_signed<T>::value, std::make_unsigned<T>, std::common_type<T>>::type>::type; #else template <class T> using is_integral = typename std::is_integral<T>; template <class T> using is_signed_int = typename std::conditional<is_integral<T>::value&& std::is_signed<T>::value, std::true_type, std::false_type>::type; template <class T> using is_unsigned_int = typename std::conditional<is_integral<T>::value&& std::is_unsigned<T>::value, std::true_type, std::false_type>::type; template <class T> using to_unsigned = typename std::conditional<is_signed_int<T>::value, std::make_unsigned<T>, std::common_type<T>>::type; #endif template <class T> using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>; template <class T> using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>; template <class T> using to_unsigned_t = typename to_unsigned<T>::type; } } #endif #ifndef ATCODER_MODINT_HPP #define ATCODER_MODINT_HPP 1 #include <cassert> #include <numeric> #include <type_traits> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { struct modint_base {}; struct static_modint_base : modint_base {}; template <class T> using is_modint = std::is_base_of<modint_base, T>; template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>; } template <int m, std::enable_if_t<(1 <= m)>* = nullptr> struct static_modint : internal::static_modint_base { using mint = static_modint; public: static constexpr int mod() { return m; } static mint raw(int v) { mint x; x._v = v; return x; } static_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> static_modint(T v) { long long x = (long long)(v % (long long)(umod())); if (x < 0) x += umod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> static_modint(T v) { _v = (unsigned int)(v % umod()); } static_modint(bool v) { _v = ((unsigned int)(v) % umod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++* this; return result; } mint operator--(int) { mint result = *this; --* this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v -= rhs._v; if (_v >= umod()) _v += umod(); return *this; } mint& operator*=(const mint& rhs) { unsigned long long z = _v; z *= rhs._v; _v = (unsigned int)(z % umod()); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { if (prime) { assert(_v); return pow(umod() - 2); } else { auto eg = internal::inv_gcd(_v, m); assert(eg.first == 1); return eg.second; } } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static constexpr unsigned int umod() { return m; } static constexpr bool prime = internal::is_prime<m>; }; template <int id> struct dynamic_modint : internal::modint_base { using mint = dynamic_modint; public: static int mod() { return (int)(bt.umod()); } static void set_mod(int m) { assert(1 <= m); bt = internal::barrett(m); } static mint raw(int v) { mint x; x._v = v; return x; } dynamic_modint() : _v(0) {} template <class T, internal::is_signed_int_t<T>* = nullptr> dynamic_modint(T v) { long long x = (long long)(v % (long long)(mod())); if (x < 0) x += mod(); _v = (unsigned int)(x); } template <class T, internal::is_unsigned_int_t<T>* = nullptr> dynamic_modint(T v) { _v = (unsigned int)(v % mod()); } dynamic_modint(bool v) { _v = ((unsigned int)(v) % mod()); } unsigned int val() const { return _v; } mint& operator++() { _v++; if (_v == umod()) _v = 0; return *this; } mint& operator--() { if (_v == 0) _v = umod(); _v--; return *this; } mint operator++(int) { mint result = *this; ++* this; return result; } mint operator--(int) { mint result = *this; --* this; return result; } mint& operator+=(const mint& rhs) { _v += rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator-=(const mint& rhs) { _v += mod() - rhs._v; if (_v >= umod()) _v -= umod(); return *this; } mint& operator*=(const mint& rhs) { _v = bt.mul(_v, rhs._v); return *this; } mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } mint pow(long long n) const { assert(0 <= n); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { auto eg = internal::inv_gcd(_v, mod()); assert(eg.first == 1); return eg.second; } friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; } private: unsigned int _v; static internal::barrett bt; static unsigned int umod() { return bt.umod(); } }; template <int id> internal::barrett dynamic_modint<id>::bt = 998244353; using modint998244353 = static_modint<998244353>; using modint1000000007 = static_modint<1000000007>; using modint = dynamic_modint<-1>; namespace internal { template <class T> using is_static_modint = std::is_base_of<internal::static_modint_base, T>; template <class T> using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>; template <class> struct is_dynamic_modint : public std::false_type {}; template <int id> struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {}; template <class T> using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>; } } #endif #ifndef ATCODER_CONVOLUTION_HPP #define ATCODER_CONVOLUTION_HPP 1 #include <algorithm> #include <array> #include <cassert> #include <type_traits> #include <vector> namespace atcoder { namespace internal { template <class mint, internal::is_static_modint_t<mint>* = nullptr> void butterfly(std::vector<mint>& a) { static constexpr int g = internal::primitive_root<mint::mod()>; int n = int(a.size()); int h = internal::ceil_pow2(n); static bool first = true; static mint sum_e[30]; if (first) { first = false; mint es[30], ies[30]; int cnt2 = bsf(mint::mod() - 1); mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv(); for (int i = cnt2; i >= 2; i--) { // e^(2^i) == 1 es[i - 2] = e; ies[i - 2] = ie; e *= e; ie *= ie; } mint now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_e[i] = es[i] * now; now *= ies[i]; } } for (int ph = 1; ph <= h; ph++) { int w = 1 << (ph - 1), p = 1 << (h - ph); mint now = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { auto l = a[i + offset]; auto r = a[i + offset + p] * now; a[i + offset] = l + r; a[i + offset + p] = l - r; } now *= sum_e[bsf(~(unsigned int)(s))]; } } } template <class mint, internal::is_static_modint_t<mint>* = nullptr> void butterfly_inv(std::vector<mint>& a) { static constexpr int g = internal::primitive_root<mint::mod()>; int n = int(a.size()); int h = internal::ceil_pow2(n); static bool first = true; static mint sum_ie[30]; if (first) { first = false; mint es[30], ies[30]; int cnt2 = bsf(mint::mod() - 1); mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv(); for (int i = cnt2; i >= 2; i--) { // e^(2^i) == 1 es[i - 2] = e; ies[i - 2] = ie; e *= e; ie *= ie; } mint now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_ie[i] = ies[i] * now; now *= es[i]; } } for (int ph = h; ph >= 1; ph--) { int w = 1 << (ph - 1), p = 1 << (h - ph); mint inow = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { auto l = a[i + offset]; auto r = a[i + offset + p]; a[i + offset] = l + r; a[i + offset + p] = (unsigned long long)(mint::mod() + l.val() - r.val()) * inow.val(); } inow *= sum_ie[bsf(~(unsigned int)(s))]; } } } } template <class mint, internal::is_static_modint_t<mint>* = nullptr> std::vector<mint> convolution(std::vector<mint> a, std::vector<mint> b) { int n = int(a.size()), m = int(b.size()); if (!n || !m) return {}; if (std::min(n, m) <= 60) { if (n < m) { std::swap(n, m); std::swap(a, b); } std::vector<mint> ans(n + m - 1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[i + j] += a[i] * b[j]; } } return ans; } int z = 1 << internal::ceil_pow2(n + m - 1); a.resize(z); internal::butterfly(a); b.resize(z); internal::butterfly(b); for (int i = 0; i < z; i++) { a[i] *= b[i]; } internal::butterfly_inv(a); a.resize(n + m - 1); mint iz = mint(z).inv(); for (int i = 0; i < n + m - 1; i++) a[i] *= iz; return a; } template <unsigned int mod = 998244353, class T, std::enable_if_t<internal::is_integral<T>::value>* = nullptr> std::vector<T> convolution(const std::vector<T>& a, const std::vector<T>& b) { int n = int(a.size()), m = int(b.size()); if (!n || !m) return {}; using mint = static_modint<mod>; std::vector<mint> a2(n), b2(m); for (int i = 0; i < n; i++) { a2[i] = mint(a[i]); } for (int i = 0; i < m; i++) { b2[i] = mint(b[i]); } auto c2 = convolution(move(a2), move(b2)); std::vector<T> c(n + m - 1); for (int i = 0; i < n + m - 1; i++) { c[i] = c2[i].val(); } return c; } std::vector<long long> convolution_ll(const std::vector<long long>& a, const std::vector<long long>& b) { int n = int(a.size()), m = int(b.size()); if (!n || !m) return {}; static constexpr unsigned long long MOD1 = 754974721; static constexpr unsigned long long MOD2 = 167772161; static constexpr unsigned long long MOD3 = 469762049; static constexpr unsigned long long M2M3 = MOD2 * MOD3; static constexpr unsigned long long M1M3 = MOD1 * MOD3; static constexpr unsigned long long M1M2 = MOD1 * MOD2; static constexpr unsigned long long M1M2M3 = MOD1 * MOD2 * MOD3; static constexpr unsigned long long i1 = internal::inv_gcd(MOD2 * MOD3, MOD1).second; static constexpr unsigned long long i2 = internal::inv_gcd(MOD1 * MOD3, MOD2).second; static constexpr unsigned long long i3 = internal::inv_gcd(MOD1 * MOD2, MOD3).second; auto c1 = convolution<MOD1>(a, b); auto c2 = convolution<MOD2>(a, b); auto c3 = convolution<MOD3>(a, b); std::vector<long long> c(n + m - 1); for (int i = 0; i < n + m - 1; i++) { unsigned long long x = 0; x += (c1[i] * i1) % MOD1 * M2M3; x += (c2[i] * i2) % MOD2 * M1M3; x += (c3[i] * i3) % MOD3 * M1M2; long long diff = c1[i] - internal::safe_mod((long long)(x), (long long)(MOD1)); if (diff < 0) diff += MOD1; static constexpr unsigned long long offset[5] = { 0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3 }; x -= offset[diff % 5]; c[i] = x; } return c; } } #endif #ifndef ATCODER_DSU_HPP #define ATCODER_DSU_HPP 1 #include <algorithm> #include <cassert> #include <vector> namespace atcoder { struct dsu { public: dsu() : _n(0) {} dsu(int n) : _n(n), parent_or_size(n, -1) {} int merge(int a, int b) { assert(0 <= a && a < _n); assert(0 <= b && b < _n); int x = leader(a), y = leader(b); if (x == y) return x; if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y); parent_or_size[x] += parent_or_size[y]; parent_or_size[y] = x; return x; } bool same(int a, int b) { assert(0 <= a && a < _n); assert(0 <= b && b < _n); return leader(a) == leader(b); } int leader(int a) { assert(0 <= a && a < _n); if (parent_or_size[a] < 0) return a; return parent_or_size[a] = leader(parent_or_size[a]); } int size(int a) { assert(0 <= a && a < _n); return -parent_or_size[leader(a)]; } std::vector<std::vector<int>> groups() { std::vector<int> leader_buf(_n), group_size(_n); for (int i = 0; i < _n; i++) { leader_buf[i] = leader(i); group_size[leader_buf[i]]++; } std::vector<std::vector<int>> result(_n); for (int i = 0; i < _n; i++) { result[i].reserve(group_size[i]); } for (int i = 0; i < _n; i++) { result[leader_buf[i]].push_back(i); } result.erase( std::remove_if(result.begin(), result.end(), [&](const std::vector<int>& v) { return v.empty(); }), result.end()); return result; } private: int _n; std::vector<int> parent_or_size; }; } #endif #ifndef ATCODER_FENWICKTREE_HPP #define ATCODER_FENWICKTREE_HPP 1 #include <cassert> #include <vector> namespace atcoder { template <class T> struct fenwick_tree { using U = internal::to_unsigned_t<T>; public: fenwick_tree() : _n(0) {} fenwick_tree(int n) : _n(n), data(n) {} void add(int p, T x) { assert(0 <= p && p < _n); p++; while (p <= _n) { data[p - 1] += U(x); p += p & -p; } } T sum(int l, int r) { assert(0 <= l && l <= r && r <= _n); return sum(r) - sum(l); } private: int _n; std::vector<U> data; U sum(int r) { U s = 0; while (r > 0) { s += data[r - 1]; r -= r & -r; } return s; } }; } #endif #ifndef ATCODER_LAZYSEGTREE_HPP #define ATCODER_LAZYSEGTREE_HPP 1 #include <algorithm> #include <cassert> #include <iostream> #include <vector> namespace atcoder { template <class S, S(*op)(S, S), S(*e)(), class F, S(*mapping)(F, S), F(*composition)(F, F), F(*id)()> struct lazy_segtree { public: lazy_segtree() : lazy_segtree(0) {} lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {} lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); lz = std::vector<F>(size, id()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); return d[p]; } S prod(int l, int r) { assert(0 <= l && l <= r && r <= _n); if (l == r) return e(); l += size; r += size; for (int i = log; i >= 1; i--) { if (((l >> i) << i) != l) push(l >> i); if (((r >> i) << i) != r) push(r >> i); } S sml = e(), smr = e(); while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() { return d[1]; } void apply(int p, F f) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); d[p] = mapping(f, d[p]); for (int i = 1; i <= log; i++) update(p >> i); } void apply(int l, int r, F f) { assert(0 <= l && l <= r && r <= _n); if (l == r) return; l += size; r += size; for (int i = log; i >= 1; i--) { if (((l >> i) << i) != l) push(l >> i); if (((r >> i) << i) != r) push((r - 1) >> i); } { int l2 = l, r2 = r; while (l < r) { if (l & 1) all_apply(l++, f); if (r & 1) all_apply(--r, f); l >>= 1; r >>= 1; } l = l2; r = r2; } for (int i = 1; i <= log; i++) { if (((l >> i) << i) != l) update(l >> i); if (((r >> i) << i) != r) update((r - 1) >> i); } } template <bool (*g)(S)> int max_right(int l) { return max_right(l, [](S x) { return g(x); }); } template <class G> int max_right(int l, G g) { assert(0 <= l && l <= _n); assert(g(e())); if (l == _n) return _n; l += size; for (int i = log; i >= 1; i--) push(l >> i); S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!g(op(sm, d[l]))) { while (l < size) { push(l); l = (2 * l); if (g(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*g)(S)> int min_left(int r) { return min_left(r, [](S x) { return g(x); }); } template <class G> int min_left(int r, G g) { assert(0 <= r && r <= _n); assert(g(e())); if (r == 0) return 0; r += size; for (int i = log; i >= 1; i--) push((r - 1) >> i); S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!g(op(d[r], sm))) { while (r < size) { push(r); r = (2 * r + 1); if (g(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; std::vector<F> lz; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } void all_apply(int k, F f) { d[k] = mapping(f, d[k]); if (k < size) lz[k] = composition(f, lz[k]); } void push(int k) { all_apply(2 * k, lz[k]); all_apply(2 * k + 1, lz[k]); lz[k] = id(); } }; } #endif #ifndef ATCODER_MATH_HPP #define ATCODER_MATH_HPP 1 #include <algorithm> #include <cassert> #include <tuple> #include <vector> namespace atcoder { long long pow_mod(long long x, long long n, int m) { assert(0 <= n && 1 <= m); if (m == 1) return 0; internal::barrett bt((unsigned int)(m)); unsigned int r = 1, y = (unsigned int)(internal::safe_mod(x, m)); while (n) { if (n & 1) r = bt.mul(r, y); y = bt.mul(y, y); n >>= 1; } return r; } long long inv_mod(long long x, long long m) { assert(1 <= m); auto z = internal::inv_gcd(x, m); assert(z.first == 1); return z.second; } std::pair<long long, long long> crt(const std::vector<long long>& r, const std::vector<long long>& m) { assert(r.size() == m.size()); int n = int(r.size()); long long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert(1 <= m[i]); long long r1 = internal::safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { std::swap(r0, r1); std::swap(m0, m1); } if (m0 % m1 == 0) { if (r0 % m1 != r1) return { 0, 0 }; continue; } long long g, im; std::tie(g, im) = internal::inv_gcd(m0, m1); long long u1 = (m1 / g); if ((r1 - r0) % g) return { 0, 0 }; long long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; } return { r0, m0 }; } long long floor_sum(long long n, long long m, long long a, long long b) { long long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long long y_max = (a * n + b) / m, x_max = (y_max * m - b); if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } } #endif #ifndef ATCODER_MAXFLOW_HPP #define ATCODER_MAXFLOW_HPP 1 #include <algorithm> #include <cassert> #include <limits> #include <queue> #include <vector> namespace atcoder { template <class Cap> struct mf_graph { public: mf_graph() : _n(0) {} mf_graph(int n) : _n(n), g(n) {} int add_edge(int from, int to, Cap cap) { assert(0 <= from && from < _n); assert(0 <= to && to < _n); assert(0 <= cap); int m = int(pos.size()); pos.push_back({ from, int(g[from].size()) }); g[from].push_back(_edge{ to, int(g[to].size()), cap }); g[to].push_back(_edge{ from, int(g[from].size()) - 1, 0 }); return m; } struct edge { int from, to; Cap cap, flow; }; edge get_edge(int i) { int m = int(pos.size()); assert(0 <= i && i < m); auto _e = g[pos[i].first][pos[i].second]; auto _re = g[_e.to][_e.rev]; return edge{ pos[i].first, _e.to, _e.cap + _re.cap, _re.cap }; } std::vector<edge> edges() { int m = int(pos.size()); std::vector<edge> result; for (int i = 0; i < m; i++) { result.push_back(get_edge(i)); } return result; } void change_edge(int i, Cap new_cap, Cap new_flow) { int m = int(pos.size()); assert(0 <= i && i < m); assert(0 <= new_flow && new_flow <= new_cap); auto& _e = g[pos[i].first][pos[i].second]; auto& _re = g[_e.to][_e.rev]; _e.cap = new_cap - new_flow; _re.cap = new_flow; } Cap flow(int s, int t) { return flow(s, t, std::numeric_limits<Cap>::max()); } Cap flow(int s, int t, Cap flow_limit) { assert(0 <= s && s < _n); assert(0 <= t && t < _n); std::vector<int> level(_n), iter(_n); internal::simple_queue<int> que; auto bfs = [&]() { std::fill(level.begin(), level.end(), -1); level[s] = 0; que.clear(); que.push(s); while (!que.empty()) { int v = que.front(); que.pop(); for (auto e : g[v]) { if (e.cap == 0 || level[e.to] >= 0) continue; level[e.to] = level[v] + 1; if (e.to == t) return; que.push(e.to); } } }; auto dfs = [&](auto self, int v, Cap up) { if (v == s) return up; Cap res = 0; int level_v = level[v]; for (int& i = iter[v]; i < int(g[v].size()); i++) { _edge& e = g[v][i]; if (level_v <= level[e.to] || g[e.to][e.rev].cap == 0) continue; Cap d = self(self, e.to, std::min(up - res, g[e.to][e.rev].cap)); if (d <= 0) continue; g[v][i].cap += d; g[e.to][e.rev].cap -= d; res += d; if (res == up) break; } return res; }; Cap flow = 0; while (flow < flow_limit) { bfs(); if (level[t] == -1) break; std::fill(iter.begin(), iter.end(), 0); while (flow < flow_limit) { Cap f = dfs(dfs, t, flow_limit - flow); if (!f) break; flow += f; } } return flow; } std::vector<bool> min_cut(int s) { std::vector<bool> visited(_n); internal::simple_queue<int> que; que.push(s); while (!que.empty()) { int p = que.front(); que.pop(); visited[p] = true; for (auto e : g[p]) { if (e.cap && !visited[e.to]) { visited[e.to] = true; que.push(e.to); } } } return visited; } private: int _n; struct _edge { int to, rev; Cap cap; }; std::vector<std::pair<int, int>> pos; std::vector<std::vector<_edge>> g; }; } #endif #ifndef ATCODER_MINCOSTFLOW_HPP #define ATCODER_MINCOSTFLOW_HPP 1 #include <algorithm> #include <cassert> #include <limits> #include <queue> #include <vector> namespace atcoder { template <class Cap, class Cost> struct mcf_graph { public: mcf_graph() {} mcf_graph(int n) : _n(n), g(n) {} int add_edge(int from, int to, Cap cap, Cost cost) { assert(0 <= from && from < _n); assert(0 <= to && to < _n); int m = int(pos.size()); pos.push_back({ from, int(g[from].size()) }); g[from].push_back(_edge{ to, int(g[to].size()), cap, cost }); g[to].push_back(_edge{ from, int(g[from].size()) - 1, 0, -cost }); return m; } struct edge { int from, to; Cap cap, flow; Cost cost; }; edge get_edge(int i) { int m = int(pos.size()); assert(0 <= i && i < m); auto _e = g[pos[i].first][pos[i].second]; auto _re = g[_e.to][_e.rev]; return edge{ pos[i].first, _e.to, _e.cap + _re.cap, _re.cap, _e.cost, }; } std::vector<edge> edges() { int m = int(pos.size()); std::vector<edge> result(m); for (int i = 0; i < m; i++) { result[i] = get_edge(i); } return result; } std::pair<Cap, Cost> flow(int s, int t) { return flow(s, t, std::numeric_limits<Cap>::max()); } std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) { return slope(s, t, flow_limit).back(); } std::vector<std::pair<Cap, Cost>> slope(int s, int t) { return slope(s, t, std::numeric_limits<Cap>::max()); } std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) { assert(0 <= s && s < _n); assert(0 <= t && t < _n); assert(s != t); std::vector<Cost> dual(_n, 0), dist(_n); std::vector<int> pv(_n), pe(_n); std::vector<bool> vis(_n); auto dual_ref = [&]() { std::fill(dist.begin(), dist.end(), std::numeric_limits<Cost>::max()); std::fill(pv.begin(), pv.end(), -1); std::fill(pe.begin(), pe.end(), -1); std::fill(vis.begin(), vis.end(), false); struct Q { Cost key; int to; bool operator<(Q r) const { return key > r.key; } }; std::priority_queue<Q> que; dist[s] = 0; que.push(Q{ 0, s }); while (!que.empty()) { int v = que.top().to; que.pop(); if (vis[v]) continue; vis[v] = true; if (v == t) break; for (int i = 0; i < int(g[v].size()); i++) { auto e = g[v][i]; if (vis[e.to] || !e.cap) continue; Cost cost = e.cost - dual[e.to] + dual[v]; if (dist[e.to] - dist[v] > cost) { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push(Q{ dist[e.to], e.to }); } } } if (!vis[t]) { return false; } for (int v = 0; v < _n; v++) { if (!vis[v]) continue; dual[v] -= dist[t] - dist[v]; } return true; }; Cap flow = 0; Cost cost = 0, prev_cost = -1; std::vector<std::pair<Cap, Cost>> result; result.push_back({ flow, cost }); while (flow < flow_limit) { if (!dual_ref()) break; Cap c = flow_limit - flow; for (int v = t; v != s; v = pv[v]) { c = std::min(c, g[pv[v]][pe[v]].cap); } for (int v = t; v != s; v = pv[v]) { auto& e = g[pv[v]][pe[v]]; e.cap -= c; g[v][e.rev].cap += c; } Cost d = -dual[s]; flow += c; cost += c * d; if (prev_cost == d) { result.pop_back(); } result.push_back({ flow, cost }); prev_cost = cost; } return result; } private: int _n; struct _edge { int to, rev; Cap cap; Cost cost; }; std::vector<std::pair<int, int>> pos; std::vector<std::vector<_edge>> g; }; } #endif #ifndef ATCODER_SCC_HPP #define ATCODER_SCC_HPP 1 #include <algorithm> #include <cassert> #include <vector> namespace atcoder { struct scc_graph { public: scc_graph() : internal(0) {} scc_graph(int n) : internal(n) {} void add_edge(int from, int to) { int n = internal.num_vertices(); assert(0 <= from && from < n); assert(0 <= to && to < n); internal.add_edge(from, to); } std::vector<std::vector<int>> scc() { return internal.scc(); } private: internal::scc_graph internal; }; } #endif #ifndef ATCODER_SEGTREE_HPP #define ATCODER_SEGTREE_HPP 1 #include <algorithm> #include <cassert> #include <vector> namespace atcoder { template <class S, S(*op)(S, S), S(*e)()> struct segtree { public: segtree() : segtree(0) {} segtree(int n) : segtree(std::vector<S>(n, e())) {} segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) { assert(0 <= p && p < _n); return d[p + size]; } S prod(int l, int r) { assert(0 <= l && l <= r && r <= _n); S sml = e(), smr = e(); l += size; r += size; while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() { return d[1]; } template <bool (*f)(S)> int max_right(int l) { return max_right(l, [](S x) { return f(x); }); } template <class F> int max_right(int l, F f) { assert(0 <= l && l <= _n); assert(f(e())); if (l == _n) return _n; l += size; S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!f(op(sm, d[l]))) { while (l < size) { l = (2 * l); if (f(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*f)(S)> int min_left(int r) { return min_left(r, [](S x) { return f(x); }); } template <class F> int min_left(int r, F f) { assert(0 <= r && r <= _n); assert(f(e())); if (r == 0) return 0; r += size; S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!f(op(d[r], sm))) { while (r < size) { r = (2 * r + 1); if (f(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } }; } #endif #ifndef ATCODER_STRING_HPP #define ATCODER_STRING_HPP 1 #include <algorithm> #include <cassert> #include <numeric> #include <string> #include <vector> namespace atcoder { namespace internal { std::vector<int> sa_naive(const std::vector<int>& s) { int n = int(s.size()); std::vector<int> sa(n); std::iota(sa.begin(), sa.end(), 0); std::sort(sa.begin(), sa.end(), [&](int l, int r) { if (l == r) return false; while (l < n && r < n) { if (s[l] != s[r]) return s[l] < s[r]; l++; r++; } return l == n; }); return sa; } std::vector<int> sa_doubling(const std::vector<int>& s) { int n = int(s.size()); std::vector<int> sa(n), rnk = s, tmp(n); std::iota(sa.begin(), sa.end(), 0); for (int k = 1; k < n; k *= 2) { auto cmp = [&](int x, int y) { if (rnk[x] != rnk[y]) return rnk[x] < rnk[y]; int rx = x + k < n ? rnk[x + k] : -1; int ry = y + k < n ? rnk[y + k] : -1; return rx < ry; }; std::sort(sa.begin(), sa.end(), cmp); tmp[sa[0]] = 0; for (int i = 1; i < n; i++) { tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i - 1], sa[i]) ? 1 : 0); } std::swap(tmp, rnk); } return sa; } template <int THRESHOLD_NAIVE = 10, int THRESHOLD_DOUBLING = 40> std::vector<int> sa_is(const std::vector<int>& s, int upper) { int n = int(s.size()); if (n == 0) return {}; if (n == 1) return { 0 }; if (n == 2) { if (s[0] < s[1]) { return { 0, 1 }; } else { return { 1, 0 }; } } if (n < THRESHOLD_NAIVE) { return sa_naive(s); } if (n < THRESHOLD_DOUBLING) { return sa_doubling(s); } std::vector<int> sa(n); std::vector<bool> ls(n); for (int i = n - 2; i >= 0; i--) { ls[i] = (s[i] == s[i + 1]) ? ls[i + 1] : (s[i] < s[i + 1]); } std::vector<int> sum_l(upper + 1), sum_s(upper + 1); for (int i = 0; i < n; i++) { if (!ls[i]) { sum_s[s[i]]++; } else { sum_l[s[i] + 1]++; } } for (int i = 0; i <= upper; i++) { sum_s[i] += sum_l[i]; if (i < upper) sum_l[i + 1] += sum_s[i]; } auto induce = [&](const std::vector<int>& lms) { std::fill(sa.begin(), sa.end(), -1); std::vector<int> buf(upper + 1); std::copy(sum_s.begin(), sum_s.end(), buf.begin()); for (auto d : lms) { if (d == n) continue; sa[buf[s[d]]++] = d; } std::copy(sum_l.begin(), sum_l.end(), buf.begin()); sa[buf[s[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int v = sa[i]; if (v >= 1 && !ls[v - 1]) { sa[buf[s[v - 1]]++] = v - 1; } } std::copy(sum_l.begin(), sum_l.end(), buf.begin()); for (int i = n - 1; i >= 0; i--) { int v = sa[i]; if (v >= 1 && ls[v - 1]) { sa[--buf[s[v - 1] + 1]] = v - 1; } } }; std::vector<int> lms_map(n + 1, -1); int m = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms_map[i] = m++; } } std::vector<int> lms; lms.reserve(m); for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms.push_back(i); } } induce(lms); if (m) { std::vector<int> sorted_lms; sorted_lms.reserve(m); for (int v : sa) { if (lms_map[v] != -1) sorted_lms.push_back(v); } std::vector<int> rec_s(m); int rec_upper = 0; rec_s[lms_map[sorted_lms[0]]] = 0; for (int i = 1; i < m; i++) { int l = sorted_lms[i - 1], r = sorted_lms[i]; int end_l = (lms_map[l] + 1 < m) ? lms[lms_map[l] + 1] : n; int end_r = (lms_map[r] + 1 < m) ? lms[lms_map[r] + 1] : n; bool same = true; if (end_l - l != end_r - r) { same = false; } else { while (l < end_l) { if (s[l] != s[r]) { break; } l++; r++; } if (l == n || s[l] != s[r]) same = false; } if (!same) rec_upper++; rec_s[lms_map[sorted_lms[i]]] = rec_upper; } auto rec_sa = sa_is<THRESHOLD_NAIVE, THRESHOLD_DOUBLING>(rec_s, rec_upper); for (int i = 0; i < m; i++) { sorted_lms[i] = lms[rec_sa[i]]; } induce(sorted_lms); } return sa; } } std::vector<int> suffix_array(const std::vector<int>& s, int upper) { assert(0 <= upper); for (int d : s) { assert(0 <= d && d <= upper); } auto sa = internal::sa_is(s, upper); return sa; } template <class T> std::vector<int> suffix_array(const std::vector<T>& s) { int n = int(s.size()); std::vector<int> idx(n); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int l, int r) { return s[l] < s[r]; }); std::vector<int> s2(n); int now = 0; for (int i = 0; i < n; i++) { if (i && s[idx[i - 1]] != s[idx[i]]) now++; s2[idx[i]] = now; } return internal::sa_is(s2, now); } std::vector<int> suffix_array(const std::string& s) { int n = int(s.size()); std::vector<int> s2(n); for (int i = 0; i < n; i++) { s2[i] = s[i]; } return internal::sa_is(s2, 255); } template <class T> std::vector<int> lcp_array(const std::vector<T>& s, const std::vector<int>& sa) { int n = int(s.size()); assert(n >= 1); std::vector<int> rnk(n); for (int i = 0; i < n; i++) { rnk[sa[i]] = i; } std::vector<int> lcp(n - 1); int h = 0; for (int i = 0; i < n; i++) { if (h > 0) h--; if (rnk[i] == 0) continue; int j = sa[rnk[i] - 1]; for (; j + h < n && i + h < n; h++) { if (s[j + h] != s[i + h]) break; } lcp[rnk[i] - 1] = h; } return lcp; } std::vector<int> lcp_array(const std::string& s, const std::vector<int>& sa) { int n = int(s.size()); std::vector<int> s2(n); for (int i = 0; i < n; i++) { s2[i] = s[i]; } return lcp_array(s2, sa); } template <class T> std::vector<int> z_algorithm(const std::vector<T>& s) { int n = int(s.size()); if (n == 0) return {}; std::vector<int> z(n); z[0] = 0; for (int i = 1, j = 0; i < n; i++) { int& k = z[i]; k = (j + z[j] <= i) ? 0 : std::min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } std::vector<int> z_algorithm(const std::string& s) { int n = int(s.size()); std::vector<int> s2(n); for (int i = 0; i < n; i++) { s2[i] = s[i]; } return z_algorithm(s2); } } #endif #ifndef ATCODER_TWOSAT_HPP #define ATCODER_TWOSAT_HPP 1 #include <cassert> #include <vector> namespace atcoder { struct two_sat { public: two_sat() : _n(0), scc(0) {} two_sat(int n) : _n(n), _answer(n), scc(2 * n) {} void add_clause(int i, bool f, int j, bool g) { assert(0 <= i && i < _n); assert(0 <= j && j < _n); scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0)); scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0)); } bool satisfiable() { auto id = scc.scc_ids().second; for (int i = 0; i < _n; i++) { if (id[2 * i] == id[2 * i + 1]) return false; _answer[i] = id[2 * i] < id[2 * i + 1]; } return true; } std::vector<bool> answer() { return _answer; } private: int _n; std::vector<bool> _answer; internal::scc_graph scc; }; } #endif #include <iostream> #include <string> #include <cmath> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #include<iomanip> #include<bitset> #define _USE_MATH_DEFINES #include <math.h> #include <functional> #include<complex> #include<cassert> #include<random> using namespace std; using namespace atcoder; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define repi(i, a, b) for (int i = (int)(a); i < (int)(b); i++) typedef long long ll; typedef unsigned long long ull; const ll inf=1e18; using graph = vector<vector<int> > ; using P= pair<ll,ll>; using vi=vector<int>; using vvi=vector<vi>; using vll=vector<ll>; using vvll=vector<vll>; using vp=vector<P>; using vpp=vector<vp>; using mint=modint1000000007; using vm=vector<mint>; using vvm=vector<vm>; //string T="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //string S="abcdefghijklmnopqrstuvwxyz"; //cout << fixed << setprecision(10); //cin.tie(0); ios::sync_with_stdio(false); const double PI = acos(-1); template<class T> bool chmin(T& a, T b) { if (a > b) { a = b; return true; } else return false; } template<class T> bool chmax(T& a, T b) { if (a < b) { a = b; return true; } else return false; } struct edge{ int to; int w; edge(int to,int w) : to(to),w(w){} }; using S = long long; using F = long long; const S INF = 8e18; S op(S a, S b){ return std::min(a, b); } S e(){ return INF; } S mapping(F f, S x){ return f+x; } F composition(F f, F g){ return f+g; } F id(){ return 0; } //g++ cf.cpp -std=c++17 -I . int main(){cin.tie(0);ios::sync_with_stdio(false); int n; cin >> n; vi p(n),a(n); rep(i,n)cin >> p[i],p[i]--; rep(i,n)cin >> a[i]; vector<S> v(n); lazy_segtree<S, op, e, F, mapping, composition, id> seg(v); rep(i,n)seg.apply(p[i],n,a[i]); ll ans=inf; rep(i,n-1){ seg.apply(p[i],n,-a[i]); seg.apply(0,p[i],a[i]); chmin(ans,seg.all_prod()); } chmin(ans,min(a[0],a[n-1])+0ll); cout << ans<< endl; }
cpp
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
#include <bits\stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; vector<unsigned> bs((int)1e5); vector<unsigned> ps(65, 0); while (t--) { unsigned long long n,k; cin >> n >> k; long long sum = 0; unsigned res = 0; for(int i = 0; i < k; ++i) { cin >> bs[i]; sum += bs[i]; ++ps[31 - __builtin_clz(bs[i])]; } if(sum < n) { cout << -1 << '\n'; } else { for(int i = 0; i < 64; ++i) { auto bit = (1ll << i) & n; if(bit == 0) { ps[i+1] += ps[i]/2; } else if(bit != 0 && ps[i] > 0) { --ps[i]; ps[i+1] += ps[i]/2; } else if(bit != 0 && ps[i] == 0) { int j = i; while(ps[j] == 0) ++j; while(j != i) { --ps[j]; ps[j-1] += 2; --j; ++res; } --ps[i]; ps[i+1] += ps[i]/2; } } cout << res << "\n"; } fill(ps.begin(), ps.end(), 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> using namespace std; #define int long long int void solve() { int n; cin >> n; vector<int> a(n); for(int i=0;i<n;i++)cin>>a[i]; vector<int> cnt(30, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < 30; j++) { if (a[i] & (1LL << j)) { cnt[j]++; } } } int pos = 0; for (int j = 29; j >= 0; j--) { if (cnt[j] == 1) { pos = j; j = -1; } } for(int i=0;i<n;i++){ if(a[i]&(1LL<<pos)){ swap(a[i],a[0]); i=n+2; } } for(auto u:a)cout<<u<<" "; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; // cin >> t; while (t--) { solve(); cout << "\n"; } 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> #define fo(i,a,b) for(int i=a;i<=b;++i) #define fd(i,a,b) for(int i=a;i>=b;--i) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) using namespace std; char an[105]; struct cx{ int len,tn[26]; }sp[105]; int tn[105][26],tn1[26],tn2[26]; bool zqr(cx a1,cx a2) { return a1.len<a2.len; } void solve(int l) { if(l==1) { printf("? %d %d\n",1,1);fflush(stdout); string s;cin>>s; an[1]=s[0]; return; } multiset<vector<int> >aa; printf("? %d %d\n",1,l);fflush(stdout); fo(i,1,l*(l+1)>>1) { vector<int> tn(26,0); string s;cin>>s; for(auto xx:s)tn[xx-'a']++; aa.insert(tn); } printf("? %d %d\n",1,l-1);fflush(stdout); fo(i,1,l*(l-1)>>1) { vector<int> tn(26,0); string s;cin>>s; for(auto xx:s)tn[xx-'a']++; aa.erase(aa.find(tn)); } int tot=0; for(auto xx:aa) { tot++; fo(i,0,25)sp[tot].len+=xx[i],sp[tot].tn[i]=xx[i]; } sort(sp+1,sp+tot+1,zqr); fo(i,1,tot) { fo(j,0,25)if(sp[i].tn[j]-sp[i-1].tn[j])an[tot-i+1]=j+'a'; } } int main() { // freopen(".in","r",stdin); // freopen("CF1286C.in","r",stdin); // freopen("CF1286C.out","w",stdout); int n;scanf("%d",&n); if(n==1) { printf("? %d %d\n",1,1);fflush(stdout); string s;cin>>s; printf("! %c",s[0]);fflush(stdout); return 0; } solve(n>>1); printf("? %d %d\n",1,n); fo(i,1,n*(n+1)>>1) { string s;cin>>s; int len=s.size(); for(auto xx:s)tn[len][xx-'a']++; } fo(i,1,n-(n>>1)) { fo(j,0,25)tn1[j]=tn[i][j]-tn[i-1][j]; fo(j,0,25)tn2[j]=tn[i+1][j]-tn[i][j]; fo(j,0,25)if(tn1[j]-tn2[j]) { if(tn1[j]-tn2[j]==2)an[n-i+1]=j+'a'; else if(j+'a'!=an[i])an[n-i+1]=j+'a'; } } printf("! ");fo(i,1,n)putchar(an[i]); return 0; }
cpp
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
// #pragma GCC optimize("O3,unroll-loops") // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> #include <ext/rope> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/hash_policy.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_cxx; using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less_equal<T>, rb_tree_tag,tree_order_statistics_node_update>; using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>; // template <class T> using heapq = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>; template <class T> using heapq = std::priority_queue<T, vector<T>, greater<T>>; #define ll long long #define i128 __int128 #define ld long double #define ui unsigned int #define ull unsigned long long #define pii pair<int, int> #define pll pair<ll, ll> #define pdd pair<ld, ld> #define vi vector<int> #define vvi vector<vector<int>> #define vll vector<ll> #define vvll vector<vector<ll>> #define vpii vector<pii> #define vpll vector<pll> #define lb lower_bound #define ub upper_bound #define pb push_back #define pf push_front #define eb emplace_back #define fi first #define se second #define rep(i, a, b) for(int i = a; i < b; ++i) #define per(i, a, b) for(int i = a; i > b; --i) #define each(x, v) for(auto& x: v) #define len(x) (int)x.size() #define elif else if #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define mst(x, a) memset(x, a, sizeof(x)) #define lowbit(x) (x & (-x)) #define bitcnt(x) (__builtin_popcountll(x)) #define endl "\n" mt19937 rng( chrono::steady_clock::now().time_since_epoch().count() ); #define Ran(a, b) rng() % ( (b) - (a) + 1 ) + (a) struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } size_t operator()(pair<uint64_t,uint64_t> x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x.first + FIXED_RANDOM) ^ (splitmix64(x.second + FIXED_RANDOM) >> 1); } }; const i128 ONE = 1; istream &operator>>(istream &in, i128 &x) { string s; in >> s; bool minus = false; if (s[0] == '-') { minus = true; s.erase(s.begin()); } x = 0; for (auto i : s) { x *= 10; x += i - '0'; } if (minus) x = -x; return in; } ostream &operator<<(ostream &out, i128 x) { string s; bool minus = false; if (x < 0) { minus = true; x = -x; } while (x) { s.push_back(x % 10 + '0'); x /= 10; } if (s.empty()) s = "0"; if (minus) out << '-'; reverse(s.begin(), s.end()); out << s; return out; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const set<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const multiset<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T> ostream &operator<<(ostream &os, const Tree<T> &v) { for(auto it = begin(v); it != end(v); ++it) { if(it == begin(v)) os << *it; else os << " " << *it; } return os; } template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) { os << p.first << " " << p.second; return os; } ll gcd(ll x,ll y) { if(!x) return y; if(!y) return x; int t = __builtin_ctzll(x | y); x >>= __builtin_ctzll(x); do { y >>= __builtin_ctzll(y); if(x > y) swap(x, y); y -= x; } while(y); return x<<t; } ll lcm(ll x, ll y) { return x * y / gcd(x, y); } ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) return x = 1, y = 0, a; ll d = exgcd(b, a % b, x, y); ll t = x; x = y; y = t - a / b * x; return d; } ll max(ll x, ll y) { return x > y ? x : y; } ll min(ll x, ll y) { return x < y ? x : y; } ll Mod(ll x, int mod) { return (x % mod + mod) % mod; } ll pow(ll x, ll y, ll mod){ ll res = 1, cur = x; while (y) { if (y & 1) res = res * cur % mod; cur = ONE * cur * cur % mod; y >>= 1; } return res % mod; } ll probabilityMod(ll x, ll y, ll mod) { return x * pow(y, mod-2, mod) % mod; } vvi getGraph(int n, int m, bool directed = false) { vvi res(n); rep(_, 0, m) { int u, v; cin >> u >> v; u--, v--; res[u].emplace_back(v); if(!directed) res[v].emplace_back(u); } return res; } vector<vpii> getWeightedGraph(int n, int m, bool directed = false) { vector<vpii> res(n); rep(_, 0, m) { int u, v, w; cin >> u >> v >> w; u--, v--; res[u].emplace_back(v, w); if(!directed) res[v].emplace_back(u, w); } return res; } const ll LINF = 0x1fffffffffffffff; const ll MINF = 0x7fffffffffff; const int INF = 0x3fffffff; const int MOD = 1000000007; const int MODD = 998244353; const int N = 2e5 + 10; class SegmentTree { public: struct STNode { STNode () : left(nullptr), right(nullptr), val(0), maxval(0), minval(0), lazy(0), mlazy(LINF) {} STNode* left; STNode* right; ll val; ll maxval; ll minval; ll lazy; ll mlazy; }; STNode* root; SegmentTree() { root = new STNode(); } ~SegmentTree() {} void assign(STNode* node, int l, int r, int start, int end, ll x) { if (l == start && r == end) { node->val = 0; node->maxval = 0; node->minval = 0; node->lazy = 0; node->mlazy = x; return; } pushdown(node); int mid = l+r>>1; if (end <= mid) { assign(node->left, l, mid, start, end, x); } elif (start > mid) { assign(node->right, mid+1, r, start, end, x); } else { assign(node->left, l, mid, start, mid , x); assign(node->right, mid+1, r, mid+1, end, x); } pushup(node, mid-l+1, r-mid); } void add(STNode* node, int l, int r, int start, int end, ll x){ if (l == start && r == end) { node->lazy += x; return; } pushdown(node); int mid = l+r>>1; if (end <= mid) { add(node->left, l, mid, start, end, x); } elif (start > mid) { add(node->right, mid+1, r, start, end, x); } else { add(node->left, l, mid, start, mid , x); add(node->right, mid+1, r, mid+1, end, x); } pushup(node, mid-l+1, r-mid); } ll querySum(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->val + node->lazy * (r-l+1) + \ (node->mlazy == LINF ? 0 : node->mlazy * (r-l+1)); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = querySum(node->left, l, mid, start, end); } elif (start > mid) { res = querySum(node->right, mid+1, r, start, end); } else { res = querySum(node->left, l, mid, start, mid) + querySum(node->right, mid+1, r, mid+1, end); } pushup(node, mid-l+1, r-mid); return res; } ll queryMax(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->maxval + node->lazy + \ (node->mlazy == LINF ? 0 : node->mlazy); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = queryMax(node->left, l, mid, start, end); } elif (start > mid) { res = queryMax(node->right, mid+1, r, start, end); } else { res = max(queryMax(node->left, l, mid, start, mid), queryMax(node->right, mid+1, r, mid+1, end)); } pushup(node, mid-l+1, r-mid); return res; } ll queryMin(STNode* node, int l, int r, int start, int end) { if (l == start && r == end) { return node->minval + node->lazy + \ (node->mlazy == LINF ? 0 : node->mlazy); } pushdown(node); int mid = l+r>>1; ll res; if (end <= mid) { res = queryMin(node->left, l, mid, start, end); } elif (start > mid) { res = queryMin(node->right, mid+1, r, start, end); } else { res = min(queryMin(node->left, l, mid, start, mid), queryMin(node->right, mid+1, r, mid+1, end)); } pushup(node, mid-l+1, r-mid); return res; } void pushdown(STNode* node) { if (node->left == nullptr) { node->left = new STNode(); } if (node->right == nullptr) { node->right = new STNode(); } if (node->mlazy != LINF) { node->left->lazy = 0; node->left->val = 0; node->left->maxval = 0; node->left->minval = 0; node->right->lazy = 0; node->right->val = 0; node->right->maxval = 0; node->right->minval = 0; node->left->mlazy = node->mlazy; node->right->mlazy = node->mlazy; node->mlazy = LINF; } if (node->lazy) { node->left->lazy += node->lazy; node->right->lazy += node->lazy; node->lazy = 0; } } void pushup(STNode* node, int ln, int rn) { node->val = node->left->val + node->left->lazy * ln + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy * ln) + \ node->right->val + node->right->lazy * rn + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy * rn); node->maxval = max(node->left->maxval + node->left->lazy + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy), node->right->maxval + node->right->lazy + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy)); node->minval = min(node->left->minval + node->left->lazy + \ (node->left->mlazy == LINF ? 0 : node->left->mlazy), node->right->minval + node->right->lazy + \ (node->right->mlazy == LINF ? 0 : node->right->mlazy)); } }; void solve() { int n; cin >> n; vi p(n); each(i, p) cin >> i; vi a(n); each(i, a) cin >> i; SegmentTree st; rep(i, 0, n) st.add(st.root, 0, N, p[i], n, a[i]); ll ans = LINF; rep(i, 0, n-1) { st.add(st.root, 0, N, p[i], n, -a[i]); st.add(st.root, 0, N, 0, p[i] - 1, a[i]); ans = min(ans, st.queryMin(st.root, 0, N, 0, n)); } cout << ans << endl; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }
cpp
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
#include <bits/stdc++.h> using namespace std; // #define int long long int void solve() { int n; cin >> n; string s; cin >> s; int u = 0, v = 0; map<pair<int, int>, int> mp; int ans = (n + 5); int l, r; mp[{0, 0}] = 0; for (int i = 0; i < n; i++) { if (s[i] == 'L') u++; else if (s[i] == 'R') u--; else if (s[i] == 'U') v++; else if (s[i] == 'D') v--; pair<int, int> t = {u, v}; // cout<<u<<" "<<v<<" -> "<<i<<"\n"; if (mp.find(t) != mp.end()) { if (ans > (i + 1 - mp[t] + 1)) { ans = (i + 1) - mp[t] + 1; l = mp[t] + 1; r = i + 1; } } mp[{u, v}] = i + 1; } if (ans == (n + 5)) cout << -1; else cout << l << " " << r; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; cin >> t; while (t--) { solve(); cout << "\n"; } return 0; }
cpp
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
#include<bits/stdc++.h> using namespace std; using pl=pair<long long,long long>; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; stack<pl> st; for(int i=0;i<n;i++){ long long x; cin >> x; pl cur={x,1}; while(!st.empty()){ pl tp=st.top(); if(tp.first*cur.second < cur.first*tp.second){break;} st.pop(); cur.first+=tp.first; cur.second+=tp.second; } st.push(cur); } vector<double> res; while(!st.empty()){ pl tp=st.top();st.pop(); double cval=tp.first; cval/=tp.second; for(int i=0;i<tp.second;i++){ res.push_back(cval); } } for(int i=n-1;i>=0;i--){ std::cout << std::fixed; std::cout << std::setprecision(12) << res[i] << "\n"; } return 0; }
cpp
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
#include<bits/stdc++.h> #define nl "\n" #define fi first #define se second #define pi 3.14159 #define ll long long #define odd(a) (a&1) #define even(a) !(a&1) #define Mod 1'000'000'007 #define INF 2'000'000'000 #define sz(x) int(x.size()) #define charToInt(s) (s - '0') #define ull unsigned long long #define number_line iota(all(vec) , 1) #define all(s) s.begin(), s.end() #define rall(v) v.rbegin() , v.rend() #define fixed(n) fixed << setprecision(n) #define Num_of_Digits(n) ((int)log10(n) + 1) #define to_decimal(bin) stoll(bin, nullptr, 2) #define Ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0)) #define Floor(n, m) (((n) / (m)) - ((n) % (m) ? 0 : 1)) #define Upper(s) transform(all(s), s.begin(), ::toupper); #define Lower(s) transform(all(s), s.begin(), ::tolower); #define cout_map(mp) for(auto& [f, s] : mp) cout << f << " " << s << "\n"; // ----- bits------- #define pcnt(n) __builtin_popcount(n) #define pcntll(n) __builtin_popcountll(n) #define clz(n) __builtin_clz(n) // <---100 #define clzll(n) __builtin_clzll(n) #define ctz(n) __builtin_ctz(n) // 0001----> #define ctzll(n) __builtin_ctzll(n) using namespace std; template < typename T = int > istream& operator >> (istream &in, vector < T > & v){ for(auto & x : v) in >> x; return in; } template < typename T = int > ostream& operator << (ostream &out, const vector < T > & v){ for(const T & x : v) out << x << " "; return out; } void esraa() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout); #endif } void solve(){ ll a , b , c; cin >> a >> b >> c; ll x , y , z , mini = 1e18; for(ll i = 1; i <= 20000; i++){ for(ll j = i; j <= 20000; j += i){ for(ll k = j; k <=20000; k += j){ if(abs(a - i) + abs(b - j) + abs(c - k) < mini){ mini = abs(a - i) + abs(b - j) + abs(c - k); x = i , y = j , z = k; } } } } cout << mini << nl; cout << x << " " << y << " " << z << nl; } int main() { esraa(); int t = 1; cin >> t; //cin.ignore(); while(t--) solve(); return 0; }
cpp
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
#include <iostream> #include <string> #include <algorithm> #include <cmath> #include <vector> #include <bits/stdc++.h> int gcd(int a,int b); using namespace std; int main() { short a; cin>>a; short b=a; short z=0; short rem; short newa; vector<short>h; for(short i=2;i<b;i++) { a=b; z++; while(a!=0) { newa=a%i; h.push_back(newa); a=a/i; } } int sum=0; for(short i=0;i<h.size();i++) { sum=sum+h[i]; } int x= gcd(sum,z); cout<<sum/x<<'\/'<<z/x; } int gcd(int a,int b) { while(b) { a=a%b; swap(a,b); } return a; }
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> typedef long long ll; typedef unsigned long long ull; using namespace std; const ll mod = 1e11; const int mm = 1e5 + 10; struct node{ int x,f,s,p; node(){} node(int x,int f,int s,int p):x(x),f(f),s(s),p(p){} friend operator <(node a,node b){ return a.x==b.x?a.p>b.p:a.x<b.x; } }; int a[mm],b[mm],c[mm],d[mm],n; bool check(){ multiset<int>f,s; vector<node>v; for(int i=1;i<=n;i++){ auto x=node(a[i],c[i],d[i],1); auto y=node(b[i],c[i],d[i],0); v.push_back(x); v.push_back(y); } sort(v.begin(),v.end()); for(int i=0;i<2*n;i++){ if(v[i].p){ if(f.size()){ int x=*(--f.end()),y=(*s.begin()); if(x>v[i].s||y<v[i].f)return 0; } f.insert(v[i].f),s.insert(v[i].s); }else f.erase(f.find(v[i].f)),s.erase(s.find(v[i].s)); }return 1; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); cin>>n; for(int i=1;i<=n;i++){ cin>>a[i]>>b[i]>>c[i]>>d[i]; } int flog=check(); swap(a,c),swap(b,d); int bj=check(); if(flog&&bj)cout<<"YES"; else cout<<"NO"; }
cpp
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "greedy" ]
#include <iostream> #include <cstring> #include <algorithm> #include <queue> #include <map> #include <set> #include <vector> #include <cmath> #include <deque> #include <bitset> #include <unordered_map> using namespace std; #define x first #define y second #define mest(x,y) memset(x, y, sizeof x) #define endl "\n" #define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define pb push_back #define ppb pop_back #define INF 0x3f3f3f3f #define ll_INF 0x7f7f7f7f7f7f7f7f #define YES cout<<"YES"<<endl #define NO cout<<"NO"<<endl #define PII pair<int,int> #define PIII pair<int,pair<int,int>> #define int long long int dir[8][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, 1}, {1, 1}, {1, -1}, {-1, -1}}; const int N = 1510; //int h[N], e[N], ne[N], idx; int g[N]; int n, m, k; void solve() { cin >> n; for(int i = 1; i <= n; i ++) cin >> g[i]; unordered_map<int, vector<PII>> mp; for(int i = 1; i <= n; i ++) { int s = 0; for(int j = i; j <= n; j ++) { s += g[j]; mp[s].push_back({i, j}); } } int res = 0; vector<PII> ans; for(auto &q : mp) { vector<PII> w = q.y; sort(w.begin(), w.end(), [&](PII a, PII b){ return a.y < b.y; }); vector<PII> tmp; int ed = w[0].y, s = 1; tmp.push_back(w[0]); for(auto t : w) { int l = t.x, r = t.y; if(l > ed) { s ++; tmp.push_back({l, r}); ed = r; } } if(res < tmp.size()) { res = tmp.size(); ans = tmp; } } cout << res << endl; for(auto t : ans) { cout << t.x << " " << t.y << endl; } } signed main() { int _ = 1; // cin >> _; while(_ --) { solve(); } return 0; }
cpp
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
#include <bits/stdc++.h> #define nl << "\n" #define spc << " " << #define pt cout << using namespace std; typedef long long ll; //#define int long long #define pii pair<int, int> int mod = 1e9 + 7; int MAX = 1e9 + 1; int MIN = -1e9; double eps = 1e-7; bool check(vector<int> arr,int n){ sort(arr.begin(),arr.end()); for(int i=0;i<n;i++){ if(arr[i] != (i+1)) return false; } return true; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,minELem = 0; cin >> n; vector<int> diff(n-1); for(int i=0;i<n-1;i++) cin >> diff[i]; vector<int> perm(n,0); for(int i=1;i<n;i++){ perm[i] = perm[i-1] + diff[i-1]; minELem = min(minELem,perm[i]); } int x = 1-minELem; for(int i=0;i<n;i++) perm[i] += x; if(!check(perm, n)) pt -1 nl; else{ for(int i=0;i<n;i++) pt perm[i] << " "; } }
cpp