contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
code
stringlengths
46
29.6k
821
C
Okabe and Boxes
Okabe and Super Hacker Daru are stacking and removing boxes. There are $n$ boxes numbered from $1$ to $n$. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru $2n$ commands: $n$ of which are to add a box to the top of the stack, and $n$ of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from $1$ to $n$. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack. That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it. Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
It looks like Daru should only reorder the boxes when he has to (i.e. he gets a remove operation on a number which isn't at the top of the stack). The proof is simple: reordering when Daru has more boxes is always not worse than reordering when he has less boxes, because Daru can sort more boxes into the optimal arrangement. Therefore, our greedy algorithm is as follows: simulate all the steps until we need to reorder, and then we resort the stack in ascending order from top to bottom. This has complexity $O(n^{2}$ $log$ $n)$. However, we can speed this up if we note that whenever we reorder boxes, any box currently on the stack can be put in an optimal position and we can pretty much forget about it. So whenever we reorder, we can just clear the stack as well and continue. This gives us $O(n)$ complexity because every element is added and removed exactly once.
[ "data structures", "greedy", "trees" ]
1,500
#include <vector> #include <utility> #include <iostream> #include <cassert> #include <map> #include <climits> #include <deque> #include <algorithm> #include <set> #include <stack> using namespace std; #define ll long long #define REP(i,a) for(int i = 0; i < (a); i++) #define PB push_back #define SZ(a) (a).size() #define MP make_pair #define ALL(a) (a).begin(),(a).end() #define fs first typedef vector<int> vi; typedef pair<int,int> pii; int main() { int n; cin >> n; stack<int> st; int curr=1; int ans = 0; REP(i,2*n){ string str; cin >> str; assert(str[0]=='a' || str[0]=='r'); if(str[0]=='a'){ int x; cin >> x; st.push(x); }else if(str[0]=='r'){ if(!st.empty()){ if(st.top()==curr){ //last thing added is what we need to remove st.pop(); }else{ //last thing we added is NOT what we need to remove ans++; while(!st.empty()) st.pop(); //clears the stack } } curr++; } } cout << ans << endl; }
821
D
Okabe and City
Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren. Okabe's city is represented by a 2D grid of cells. Rows are numbered from $1$ to $n$ from top to bottom, and columns are numbered $1$ to $m$ from left to right. Exactly $k$ cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit. Okabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays $1$ coin, allowing him to walk through some cells not lit initially. Note that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit. Help Okabe find the minimum number of coins he needs to pay to complete his walk!
First, let's make this problem into one on a graph. The important piece of information is the row and column we're on, so we'll create a node like this for every lit cell in the grid. Edges in the graph are 0 between 2 nodes if we can reach the other immediately, or 1 if we can light a row/column to get to it. Now it's a shortest path problem: we need to start from a given node, and with minimum distance, reach another node. Only problem is, number of edges can be large, causing the algorithm to time out. There are a lot of options here to reduce number of transitions. The most elegant one I found is Benq's solution, which I'll describe here. From a given cell, you can visit any adjacent lit cells. In addition, you can visit any lit cell with difference in rows at most 2, and any lit cell with difference in columns at most 2. So from the cell (r,c), you can just loop over all those cells. The only tricky part is asking whether the current lit row/column should be a part of our BFS state. Since we fill the entire row/col and can then visit anything on that row/col, it doesn't matter where we came from. This means that you can temporarily light each row/column at most once during the entire BFS search. So complexity is $O(n + m + k)$, with a log factor somewhere for map or priority queue. Interestingly enough, you can remove the priority queue log factor because the BFS is with weights 0 and 1 only, but it performs slower in practice. You can see the code implementing this approach below. Another approach to this problem was using "virtual nodes". Virtual nodes are an easy way to put transitions between related states while keeping number of edges low. In this problem, we can travel to any lit cell if its row differs by <=2, or its column differs by at most 2, but naively adding edges would cause O(k^2) edges. Instead, for every row, lets make a virtual node. For every lit cell in this row, put an edge between the lit cell and this virtual node with cost 1. We can do something similar for every column. Now, it's easy to see that the shortest path in this graph suffices. A minor detail is that we should divide the answer by 2 since every skipping of a row or column ends up costing 2 units of cost.
[ "dfs and similar", "graphs", "shortest paths" ]
2,200
/*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp>*/ #include <bits/stdc++.h> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; #define FOR(i, a, b) for (int i=a; i<b; i++) #define F0R(i, a) for (int i=0; i<a; i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound const int MOD = 1000000007; double PI = 4*atan(1); int dr[10001], dc[10001]; vi row[10001], col[10001]; priority_queue<pii> todo; vector<pii> lights; int dist[10001]; map<pii,int> label; int xdir[4] = {1,0,-1,0}, ydir[4] = {0,1,0,-1}; int n,m,k; void filrow(int i, int val){ if (i >= 1 && i <= n && dr[i] == 0) { dr[i] = 1; for (int x: row[i]) if (val < dist[x]) { dist[x] = val; todo.push({-dist[x],x}); } } } void filcol(int i, int val) { if (i >= 1 && i <= m && dc[i] == 0) { dc[i] = 1; for (int x: col[i]) if (val < dist[x]) { dist[x] = val; todo.push({-dist[x],x}); } } } void ad(int x, int y, int val) { if (label.find({x,y}) != label.end()) if (dist[label[{x,y}]] > val) { dist[label[{x,y}]] = val; todo.push({-val,label[{x,y}]}); } } int main() { cin >> n >> m >> k; F0R(i,k) { int r,c; cin >> r >> c; lights.pb({r,c}); row[r].pb(i); col[c].pb(i); label[{r,c}] = i; } F0R(i,10001) dist[i] = MOD; if (label.find({n,m}) == label.end()) { filrow(n-1,1); filrow(n,1); filcol(m-1,1); filcol(m,1); } else todo.push({0,label[{n,m}]}); while (todo.size()) { auto a = todo.top(); todo.pop(); a.f = -a.f; if (a.f > dist[a.s]) continue; F0R(i,4) ad(lights[a.s].f+xdir[i],lights[a.s].s+ydir[i],a.f); FOR(i,lights[a.s].f-2,lights[a.s].f+3) filrow(i,a.f+1); FOR(i,lights[a.s].s-2,lights[a.s].s+3) filcol(i,a.f+1); } if (dist[0] != MOD) cout << dist[0]; else cout << -1; }
821
E
Okabe and El Psy Kongroo
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points $(x, y)$ such that $x$ and $y$ are non-negative. Okabe starts at the origin (point $(0, 0)$), and needs to reach the point $(k, 0)$. If Okabe is currently at the point $(x, y)$, in one step he can go to $(x + 1, y + 1)$, $(x + 1, y)$, or $(x + 1, y - 1)$. Additionally, there are $n$ horizontal line segments, the $i$-th of which goes from $x = a_{i}$ to $x = b_{i}$ inclusive, and is at $y = c_{i}$. It is guaranteed that $a_{1} = 0$, $a_{n} ≤ k ≤ b_{n}$, and $a_{i} = b_{i - 1}$ for $2 ≤ i ≤ n$. The $i$-th line segment forces Okabe to walk with $y$-value in the range $0 ≤ y ≤ c_{i}$ when his $x$ value satisfies $a_{i} ≤ x ≤ b_{i}$, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins. Okabe now wants to know how many walks there are from the origin to the point $(k, 0)$ satisfying these conditions, modulo $10^{9} + 7$.
You can get a naive DP solution by computing $f(x, y)$, the number of ways to reach the point $(x, y)$. It's just $f(x - 1, y + 1) + f(x - 1, y) + f(x - 1, y - 1)$, being careful about staying above x axis and under or on any segments. To speed it up, note that the transitions are independent of x. This is screaming matrix multiplication! First, if you don't know the matrix exponentiation technique for speeding up DP, you should learn it from here. Now, let's think of the matrix representation. Since the x dimension is the long one and the y dimension is small, lets store a vector of values $dp$ where $dp_{i}$ is the number of ways to get to a y value of i at the current x value. This will be the initial vector for matrix multiplication. Now, what about the transition matrix? Since our initial vector has length y and we need a matrix to multiply it with to map it to another vector with length y, we need a y by y matrix. Now, if you think about how matrix multiplication works, you come up with an idea like this: put a 1 in the entry (i,j) if from a y value of i we can reach a y value of j (i.e. $|i - j| \le 1$). Don't believe me, multiply some vector times a matrix of this form to see how and why the transition works. You can then build this matrix quickly and then matrix exponentiate for under every segment and multiply by the initial vector, then make the result as the new initial vector for the next segment. You should make sure to remove values from the vector if the next segment is lower, or add values to the vector if the next segment is higher. This gives complexity $O(nh^{3}$ log $w$) where $h = 16$ and $w = k$.
[ "dp", "matrices" ]
2,100
#include <queue> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <complex> #include <fstream> #include <cstring> #include <string> #include <climits> #include <chrono> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <assert.h> using namespace std; //macros typedef long long ll; typedef complex<double> point; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector< vector<int> > vvi; #define FOR(k,a,b) for(int k=(a); k<=(b); ++k) #define REP(k,a) for(int k=0; k<(a);++k) #define SZ(a) int((a).size()) #define ALL(c) (c).begin(),(c).end() #define PB push_back #define MP make_pair #define INF 1000000001 #define INFLONG 1000000000000000000 #define MOD 1000000007 #define MAX 100 #define ITERS 100 #define MAXM 200000 #define MAXN 1000000 #define _gcd __gcd #define EPS 1e-7 #define PI 3.1415926535897932384626 #define ERR -987654321 //multiplies m1 and m2 and stores in m3 vector<vector<long long> > matmul(vector<vector<long long> > m1, vector<vector<long long> > m2, vector<vector<long long> > &m3){ m3.clear(); vector<vector<long long> > ans; REP(i,SZ(m1)){ vector<long long> v; REP(j,SZ(m2[0])){ v.PB(0); } ans.PB(v); } REP(r,SZ(m1)){ REP(c,SZ(m2[0])){ REP(k, SZ(m2)){ ans[r][c] += m1[r][k]*m2[k][c]; ans[r][c]%=MOD; } } } REP(i,SZ(m1)){ vector<long long> cur; REP(j,SZ(m2[0])){ cur.PB(ans[i][j]); } m3.PB(cur); } return m3; } vector<ll> mymul(vector<ll> vec, vector<vector<ll> > mat, vector<ll> &ret){ vector<ll> res; REP(i,SZ(vec)){ ll sum = 0; for(int co = 0; co < SZ(mat); co++){ sum += vec[co]*mat[co][i]; sum%=MOD; } res.PB(sum); } ret.clear(); REP(i,SZ(res)) ret.PB(res[i]); return ret; } void printmat(vector<vector<long long> > matr){ REP(i,SZ(matr)){ REP(j,SZ(matr[i])){ cout << matr[i][j] << " " ; } cout << endl; } } vector<vector<long long> > matexp(vector<vector<long long> > matr, long long n){ vector<vector<long long> > ans; REP(i,SZ(matr)){ vector<long long> v; REP(j,SZ(matr[0])){ v.PB((i==j)); } ans.PB(v); } long long t = n; while(t>0){ if(t%2==0){ matmul(matr,matr,matr); t/=2; } else{ matmul(ans,matr,ans); t--; } } return ans; } int main() { int n; ll k; cin >> n >> k; vector<ll> a1,a2,b; REP(i,n){ ll a1r, a2r, br; cin >> a1r >> a2r >> br; a1.PB(a1r); a2.PB(a2r); b.PB(br); } vector<ll> ans; ans.PB(1); a2[SZ(a2)-1] = k; REP(i,n){ //update ans size while(SZ(ans) < b[i]+1) ans.PB(0); while(SZ(ans) > b[i]+1) ans.erase(prev(ans.end())); vector<vector<ll> > trans; int len = b[i]+1; REP(pr,len){ vector<ll> lol; REP(pro,len){ lol.PB(0); } trans.PB(lol); } REP(co,len){ if(co>0) trans[co-1][co] = 1; trans[co][co] = 1; if(co+1<len) trans[co+1][co] = 1; } mymul(ans,matexp(trans,a2[i]-a1[i]),ans); } cout << ans[0] << endl; }
822
A
I'm bored with life
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers $A$ and $B$ and then calculates the greatest common divisor of integers "$A$ factorial" and "$B$ factorial". Formally the hacker wants to find out GCD$(A!, B!)$. It's well known that the factorial of an integer $x$ is a product of all positive integers less than or equal to $x$. Thus $x! = 1·2·3·...·(x - 1)·x$. For example $4! = 1·2·3·4 = 24$. Recall that GCD$(x, y)$ is the largest positive integer $q$ that divides (without a remainder) both $x$ and $y$. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
Tutorial is not available
[ "implementation", "math", "number theory" ]
800
int a, b; scanf ( "%d%d", &a, &b ); int ans = 1; for ( int j = 1; j <= min( a, b ); j++ ) ans *= j; printf ( "%d\n", ans );
822
B
Crossword solving
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you? Leha has two strings $s$ and $t$. The hacker wants to change the string $s$ at such way, that it can be found in $t$ as a substring. All the changes should be the following: Leha chooses one position in the string $s$ and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string $s$="ab?b" as a result, it will appear in $t$="aabrbb" as a substring. Guaranteed that the length of the string $s$ doesn't exceed the length of the string $t$. Help the hacker to replace in $s$ as few symbols as possible so that the result of the replacements can be found in $t$ as a substring. The symbol "?" should be considered equal to any other symbol.
Let's consider all the positions $i$ $(1 \le i \le m - n + 1)$ that denotes the begining of the occurrence of the string $s$ in the string $t$. Then let's find out how many symbols we should replace if the begining of the occurrence is position $i$. After the considering of all $m - n + 1$ positions the optimal answer will be found. Total complexity is $O(nm)$.
[ "brute force", "implementation", "strings" ]
1,000
const int maxn = 1050; vector < int > ans; vector < int > newAns; char t1[maxn]; char t2[maxn]; int n, m; scanf ( "%d%d\n", &n, &m ); gets( t1 ); gets( t2 ); for ( int j = 0; j < n; j++ ) ans.pb( j ); for ( int j = 0; j < m - n + 1; j++ ) { newAns.clear(); for ( int i = 0; i < n; i++ ) if ( t1[i] != t2[i + j] ) newAns.pb( i ); if ( newAns.size() < ans.size() ) ans = newAns; } int sz = ans.size(); printf( "%d\n", sz ); for ( int j = 0; j < sz; j++ ) printf( "%d ", ans[j] + 1 );
822
C
Hacker, pack your bags!
It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha. So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly $x$ days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that $n$ vouchers left. $i$-th voucher is characterized by three integers $l_{i}$, $r_{i}$, $cost_{i}$ — day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the $i$-th voucher is a value $r_{i} - l_{i} + 1$. At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers $i$ and $j$ $(i ≠ j)$ so that they don't intersect, sum of their durations is \textbf{exactly} $x$ and their total cost is as minimal as possible. Two vouchers $i$ and $j$ don't intersect if only at least one of the following conditions is fulfilled: $r_{i} < l_{j}$ or $r_{j} < l_{i}$. Help Leha to choose the necessary vouchers!
Let's sort all the vouchers by their left border $l_{i}$. Let's consider the vouchers in this sorted order. Now we want to consider $i$-th one. The duration of the $i$-th voucher is $r_{i} - l_{i} + 1$. Consequentally only the vouchers with the duration $x - r_{i} + l_{i} - 1$ can make a couple with the $i$-th one. At the same time you shouldn't forget that the value of this expression may be negative. You should check it. Besides let's find a couple for the $i$-th voucher among all the vouchers $k$ for which $r_{k} < l_{i}$. To implement this solution let's keep an array $bestCost$. $bestCost[j]$ denotes the minimal cost of the voucher with the duration equal to exactly $j$ on the considering prefix (i.e. we should consider only such vouchers $k$ with $r_{k} < l_{i}$ in $bestCost$). Thus, it's enough to consider vouchers in order of increasing of their left borders and update the array $bestCost$. Total complexity is $O(n\log n)$.
[ "binary search", "greedy", "implementation", "sortings" ]
1,600
const int maxn = 200500; const int inf = ( 2e9 ) + 2; vector < pair < pair < int, int >, pair < int, int > > > queries; int bestCost[maxn]; int l[maxn]; int r[maxn]; int cost[maxn]; int solution( int n, int needLen ) { queries.clear(); for ( int j = 0; j < n; j++ ) { queries.pb( mp( mp( l[j], -1 ), mp( r[j], cost[j] ) ) ); queries.pb( mp( mp( r[j], 1 ), mp( l[j], cost[j] ) ) ); } for ( int j = 0; j < maxn; j++ ) bestCost[j] = inf; ll ans = 2LL * inf; sort( queries.begin(), queries.end() ); int sz = queries.size(); for ( int j = 0; j < sz; j++ ) { int type = queries[j].f.s; if ( type == -1 ) { int curLen = queries[j].s.f - queries[j].f.f + 1; if ( curLen <= needLen ) ans = min( ans, 1LL * queries[j].s.s + 1LL * bestCost[needLen - curLen] ); } if ( type == 1 ) { int curLen = queries[j].f.f - queries[j].s.f + 1; bestCost[curLen] = min( bestCost[curLen], queries[j].s.s ); } } return ans >= inf ? -1 : ans; }
822
D
My pretty girl Noora
In Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail. The contest is held in several stages. Suppose that exactly $n$ girls participate in the competition initially. All the participants are divided into equal groups, $x$ participants in each group. Furthermore the number $x$ is chosen arbitrarily, i. e. on every stage number $x$ can be different. Within each group the jury of the contest compares beauty of the girls in the format "each with each". In this way, if group consists of $x$ girls, then $\textstyle{\frac{x(x-1)}{2}}$ comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if $n$ girls were divided into groups, $x$ participants in each group, then exactly $\frac{\mathit{n}}{\mathbb{Z}}$ participants will enter the next stage. The contest continues until there is exactly one girl left who will be "Miss Pavlopolis University" But for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let $f(n)$ be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit $n$ girls to the first stage. The organizers of the competition are insane. They give Noora three integers $t$, $l$ and $r$ and ask the poor girl to calculate the value of the following expression: $t^{0}·f(l) + t^{1}·f(l + 1) + ... + t^{r - l}·f(r)$. However, since the value of this expression can be quite large the organizers ask her to calculate it modulo $10^{9} + 7$. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you.
Suppose we have already calculated $f(2), f(3), ..., f(r)$. Then calculating the value of the expression is easy. Consider process of calculating $f(x)$. Suppose we found optimal answer. Represent this answer as sequence of integers $d_{1}, d_{2}, ..., d_{k}$ - on the first stage we will divide girls into groups of $d_{1}$ participants, on the second stage into groups of $d_{2}$ participants and so on. Let us prove that all $d_{i}$ should be prime. Suppose some $d_{i}$ is a composite number. Then it can be decomposed into two numbers $d_{i} = a \cdot b$. In addition, let $n$ girls are admitted to the $i$-th stage. Then on current $i$-th stage ${\frac{n}{d_{i}}}\cdot{\frac{d_{i}\langle d_{i}-1\rangle}{j}}\equiv{\frac{n\langle d_{i}-1\rangle}{2}}$ comparisons will occur. But if we divide this stage into two new stages, then number of comparisons is ${\frac{n\cdot(a-1)}{2}}+{\frac{n\cdot(b-1)}{2\cdot a}}\leq{\frac{n\cdot(a-1)}{2}}+{\frac{n\cdot(b-1)}{2}}\leq{\frac{n\cdot(a-1)}{2}}\leq{\frac{n\cdot(a-1)}{2}}={\frac{n\cdot(a-1)}{2}}$. So, we proved that all $d_{i}$ should be prime. Then it's easy to write DP which will be calculated by transition from the state to the states given by dividing current state by prime divisors. For solving this task we can use Eratosthenes sieve. Total complexity is same as complexity of Eratosthenes sieve: $O(r\log\log r)$. In addition you can prove the fact that we should split the girls into groups by prime numbers in the order of their increasing. This optimization significantly accelerates the algorithm.
[ "brute force", "dp", "greedy", "math", "number theory" ]
1,800
const int maxn = 5000500; int isPrime[maxn]; ll dp[maxn]; int main() { int t, l, r; scanf ( "%d%d%d", &t, &l, &r ); for ( int j = 2; j < maxn; j++ ) isPrime[j] = j; for ( int j = 2; j * j < maxn; j++ ) if ( isPrime[j] == j ) for ( int i = j * j; i < maxn; i += j ) isPrime[i] = min( j, isPrime[i] ); dp[1] = 0; for ( int j = 2; j < maxn; j++ ) { dp[j] = 1LL * inf * inf; for ( int x = j; x != 1; x /= isPrime[x] ) dp[j] = min( dp[j], 1LL * dp[j / isPrime[x]] + 1LL * j * ( isPrime[x] - 1 ) / 2LL ); } int ans = 0; int cnt = 1; for ( int j = l; j <= r; j++ ) { dp[j] %= base; ans = ( 1LL * ans + 1LL * cnt * dp[j] ) % base; cnt = ( 1LL * cnt * t ) % base; } printf ( "%d\n", ans ); }
822
E
Liar
The first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length $m$ from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, the length of which is equal to the length of the sausage. Leha was very pleased with the gift and immediately ate the sausage. But then he realized that it was a quite tactless act, because the sausage was a souvenir! So the hacker immediately went to the butcher shop. Unfortunately, there was only another sausage of length $n$ in the shop. However Leha was not upset and bought this sausage. After coming home, he decided to cut the purchased sausage into several pieces and number the pieces starting from $1$ from left to right. Then he wants to select several pieces and glue them together so that the obtained sausage is equal to the sausage that Noora gave. But the hacker can glue two pieces together only when the number of the left piece is less than the number of the right piece. Besides he knows that if he glues more than $x$ pieces, Noora will notice that he has falsified souvenir sausage and will be very upset. Of course Leha doesn’t want to upset the girl. The hacker asks you to find out whether he is able to cut the sausage he bought, and then glue some of the pieces so that Noora doesn't notice anything. Formally, you are given two strings $s$ and $t$. The length of the string $s$ is $n$, the length of the string $t$ is $m$. It is required to select several pairwise non-intersecting substrings from $s$, so that their concatenation in the same order as these substrings appear in $s$, is equal to the string $t$. Denote by $f(s, t)$ the minimal number of substrings to be chosen so that their concatenation is equal to the string $t$. If it is impossible to choose such substrings, then $f(s, t) = ∞$. Leha really wants to know whether it’s true that $f(s, t) ≤ x$.
Formally, you were given two strings $s$ and $t$. Also number $x$ was given. You need to determine whether condition $f(s, t) \le x$ is satisfied. $f(s, t)$ is equal to the minimal number of non-intersect substrings of string $s$ which can be concatenated together to get $t$. Substrings should be concatenated in the same order they appear in $s$. Note that for short strings we can use $DP(prefS, prefT) = f(s[1... prefS], t[1... prefT])$. Note that we are not interested in such states in which value of $DP$ is greater than $x$. Also note that we can swap $DP$ value with one parameter to get new DP: $G(prefS, cnt) = prefT$, where $cnt$ - value of old DP, $prefT$ - maximal $prefT$ for which condition is satisfied: $DP(prefS, prefT) = cnt$. $G$ have $|s| \cdot x$ states. But it's not clear how to make transitions to make total complexity smaller. Note that there is only two transitions: $G(p r e f S,c n t)=p r e f T\to G(p r e f S+1,c n t)=p r e f T$ $G(p r e f S,c n t)=p r e f T\to G(p r e f S+l c p,c n t+1)=p r e f T+l c p$ First transition is obviously, because we make prefix longer by one letter, i.e. $s[1... prefS + 1]$ can be split into several parts to get prefix of string $t$, i.e. $t[1... prefT]$. Second transition is not so obviously, but if we take some part from string $s$ to cover string $t$, it's easy to see that it's optimal to take the longest possible part. Length of such longest possible part is $lcp = LongestCommonPrefix(s[prefS + 1... |s|], t[prefT + 1... |t|])$. We can find $lcp$ using suffix array. Total complexity is $O(N\log N+N x)$, where $N = |s| + |t|$. But solutions with complexity $O(N\log^{2}N+N x)$ also passed. Also $lcp$ can be found by binary search with hashes. So the total complexity of such solution is $O(N x\log N)$.
[ "binary search", "dp", "hashing", "string suffix structures" ]
2,400
import java.io.*; import java.util.*; public class Main implements Runnable { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in), 1 << 20); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static long[] unique(long[] arr) { Arrays.sort(arr); int newLen = 0; for (int i = 0; i < arr.length; i++) { if (i + 1 == arr.length || arr[i] != arr[i + 1]) { arr[newLen++] = arr[i]; } } return Arrays.copyOf(arr, newLen); } static class SuffixArray { int[][] classes; String s; int maxH; SuffixArray(String s) { this.s = s; maxH = 0; while ((1 << maxH) <= s.length()) maxH++; classes = new int[maxH][]; for (int h = 0; h < maxH; h++) { classes[h] = new int[s.length()]; } for (int i = 0; i < s.length(); i++) { classes[0][i] = s.charAt(i) - 'a'; } for (int h = 1; h < maxH; h++) { long[] values = new long[s.length() - (1 << h) + 1]; int valuesLen = 0; for (int i = 0; i + (1 << h) <= s.length(); i++) { int leftPart = classes[h - 1][i]; int rightPart = classes[h - 1][i + (1 << (h - 1))]; long curValue = ((long)leftPart << 30) ^ rightPart; values[valuesLen++] = curValue; } values = unique(values); for (int i = 0; i + (1 << h) <= s.length(); i++) { int leftPart = classes[h - 1][i]; int rightPart = classes[h - 1][i + (1 << (h - 1))]; long curValue = ((long)leftPart << 30) ^ rightPart; classes[h][i] = Arrays.binarySearch(values, curValue); } } } int getLCP(int i, int j) { int res = 0; for (int h = maxH - 1; h >= 0; h--) { if (i + (1 << h) <= s.length() && j + (1 << h) <= s.length() && classes[h][i] == classes[h][j]) { res += (1 << h); i += (1 << h); j += (1 << h); } } return res; } } @Override public void run() { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); String s = in.next(); int m = in.nextInt(); String t = in.next(); int x = in.nextInt(); int[][] dp = new int[x + 1][n + 1]; for (int i = 0; i <= x; i++) { for (int j = 0; j <= n; j++) { dp[i][j] = Integer.MIN_VALUE; } } String q = s + "#" + t; SuffixArray sarr = new SuffixArray(q); dp[0][0] = 0; for (int cnt = 0; cnt <= x; cnt++) { for (int prefS = 0; prefS <= n; prefS++) { if (dp[cnt][prefS] == Integer.MIN_VALUE) continue; //System.err.println("cnt = " + cnt + ", prefS = " + prefS + ", value = " + dp[cnt][prefS]); if (prefS + 1 <= n && dp[cnt][prefS + 1] < dp[cnt][prefS]) { dp[cnt][prefS + 1] = dp[cnt][prefS]; } if (cnt + 1 <= x) { int prefT = dp[cnt][prefS]; int lcp = sarr.getLCP(prefS, prefT + n + 1); if (dp[cnt + 1][prefS + lcp] < prefT + lcp) { dp[cnt + 1][prefS + lcp] = prefT + lcp; } } } } boolean ok = false; for (int cnt = 0; cnt <= x; cnt++) { if (dp[cnt][n] == m) { ok = true; } } out.println(ok ? "YES" : "NO"); out.close(); } public static void main(String[] args) { new Thread(null, new Main(), "1", 1L << 28).run(); } }
822
F
Madness
The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study. Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory. Yury Dmitrievich doesn't like Noora, so he always gives the girl the most difficult tasks. So it happened this time. The teacher gives Noora a tree with $n$ vertices. Vertices are numbered with integers from $1$ to $n$. The length of all the edges of this tree is $1$. Noora chooses a set of simple paths that pairwise don't intersect in edges. However each vertex should belong to at least one of the selected path. For each of the selected paths, the following is done: - We choose \textbf{exactly} one edge $(u, v)$ that belongs to the path. - On the selected edge $(u, v)$ there is a point at some selected distance $x$ from the vertex $u$ and at distance $1 - x$ from vertex $v$. But the distance $x$ chosen by Noora arbitrarily, i. e. it can be different for different edges. - One of the vertices $u$ or $v$ is selected. The point will start moving to the selected vertex. Let us explain how the point moves by example. Suppose that the path consists of two edges $(v_{1}, v_{2})$ and $(v_{2}, v_{3})$, the point initially stands on the edge $(v_{1}, v_{2})$ and begins its movement to the vertex $v_{1}$. Then the point will reach $v_{1}$, then "turn around", because the end of the path was reached, further it will move in another direction to vertex $v_{2}$, then to vertex $v_{3}$, then "turn around" again, then move to $v_{2}$ and so on. The speed of the points is $1$ edge per second. For example, for $0.5$ second the point moves to the length of the half of an edge. A stopwatch is placed at each vertex of the tree. The time that the stopwatches indicate at start time is $0$ seconds. Then at the starting moment of time, all points simultaneously start moving from the selected positions to selected directions along the selected paths, and stopwatches are simultaneously started. When one of the points reaches the vertex $v$, the stopwatch at the vertex $v$ is automatically reset, i.e. it starts counting the time from zero. Denote by $res_{v}$ the maximal time that the stopwatch at the vertex $v$ will show if the point movement continues infinitely. Noora is asked to select paths and points on them so that $res_{1}$ is as minimal as possible. If there are several solutions to do this, it is necessary to minimize $res_{2}$, then $res_{3}$, $res_{4}, ..., res_{n}$. Help Noora complete the teacher's task. For the better understanding of the statement, see the explanation for the example.
Firstly let's notice the fact that in the optimal answer each of the paths consists of exactly one edge. Let's choose one particular vertex. Let's the degree of this vertex is $deg$. The most optimal answer for this vertex is $\frac{2}{d e c g}$, because one point make a full loop of the edge in $2$ seconds. Vetrex with the degree $deg$ has exactly $deg$ adjacent edges. Consequentally $deg$ distinct points will visit this vertex. Therefore in the optimal answer we should select all the starting positions and directions in such way that they visit the vertex each $\frac{2}{d e c g}$ seconds. Let us show that we are able to select starting positions and directions so that the answer for every vertex is the optimal one. Let's put points at the moment of time between $0$ and $2$ instead of putting somewhere on the edge. The moment of time between $0$ and $1$ will correspond to the coordinates from $0$ to $1$ in the direction from the vertex and the moment of time between $1$ and $2$ will correspond to the coordinates from $1$ to $0$ in the direction to the vertex. Let's select a root among the tree vertices. Let's consider a case of the root. If there are $deg$ adjacent edges we can put a point at $0.0$ seconds on the first edge, at $\frac{2}{d e c g}$ seconds on the second edge, at $2\cdot{\frac{2}{d e g}}$ on the third edge, ..., at $(d e g-1)\cdot{\frac{2}{d e g}}$ on the edge number $deg$. Run the Depth First Search from the root (or Breadth First Search). Let's consider a case of another vertices. All these vertices will have a particular moment of time for the point in the upper edge. $upEdgeMoment$ denotes this moment. So if the vertex degree is $deg$ then the moments on the lower edges should be equal to $ule{d g E d g e M o m e n t}+{i\cdot\frac{2}{d e g}}$ (here if the value exceeds $2$, we calculate it modulo $2$, i.e. $1.2 + 1.3 = 0.5$), where $i$ is the number of lower edge. The lower edges are numbered from $1$ to $deg - 1$. All in all, we are able to put points on every edge so that the answers for each vertex are the optimal one. Total complexity is $O(n)$.
[ "constructive algorithms", "dfs and similar", "trees" ]
2,500
const int maxn = 105; vector < pair < int, int > > edge[maxn]; int used[maxn]; int from[maxn]; int where[maxn]; ld dist[maxn]; void dfs( int v, ld prevTime ) { used[v] = true; int sz = edge[v].size(); ld bestTime = 2.0L / sz; ld nextTime = prevTime + bestTime; if ( nextTime >= 2.0L ) nextTime -= 2.0L; for ( int j = 0; j < sz; j++ ) { int id = edge[v][j].f; int to = edge[v][j].s; if ( used[to] ) continue; ld toTime; if ( nextTime <= 1.0L ) { from[id] = to; where[id] = v; dist[id] = 1.0L - nextTime; toTime = nextTime + 1.0L; } else { from[id] = v; where[id] = to; dist[id] = 2.0L - nextTime; toTime = nextTime - 1.0L; } dfs( to, toTime ); nextTime = nextTime + bestTime; if ( nextTime >= 2.0L ) nextTime -= 2.0L; } } int main() { int n; scanf ( "%d", &n ); for ( int j = 1; j < n; j++ ) { int u, v; scanf ( "%d%d", &u, &v ); edge[u].pb( mp( j, v ) ); edge[v].pb( mp( j, u ) ); } dfs( 1, 0 ); printf( "%d\n", n - 1 ); for ( int j = 1; j < n; j++ ) { printf( "%d %d %d %d ", 1, j, from[j], where[j] ); cout << fixed << setprecision( 10 ) << dist[j] << endl; } }
825
A
Binary Protocol
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: - Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). - Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.
Let's decode the number digit by digit starting from the leftmost. When you meet '1' in the string, increase the value of the current digit. For '0' print current digit and proceed to the next one. Don't forget to print the last digit when the string is over. Overall complexity: $O(|s|)$.
[ "implementation" ]
1,100
null
825
B
Five-In-a-Row
Alice and Bob play 5-in-a-row game. They have a playing field of size $10 × 10$. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately. Alice wins if some crosses in the field form line of length \textbf{not smaller than 5}. This line can be horizontal, vertical and diagonal.
This one is a pure implementation task. Just check every possible line of length 5. If the current one contains 4 crosses and 1 empty cell then the answer is 'YES'.
[ "brute force", "implementation" ]
1,600
null
825
C
Multi-judge Solving
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty $d$ on Decoforces is as hard as the problem with difficulty $d$ on any other judge). Makes has chosen $n$ problems to solve on Decoforces with difficulties $a_{1}, a_{2}, ..., a_{n}$. He can solve these problems in arbitrary order. Though he can solve problem $i$ with difficulty $a_{i}$ only if he had already solved some problem with difficulty $d\geq{\frac{a_{1}}{2}}$ (no matter on what online judge was it). Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty $k$. With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer $y$ there exist some problem with difficulty $y$ on at least one judge besides Decoforces. Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another. Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.
Obviously sorting the tasks by difficulty will always produce the most optimal order of solving. In that case ability to solve some task $i$ will mean ability to solve any task from $1$ to $i - 1$. Now let's maintain the upper limit of difficulty of problem Makes is able to solve. Right after solving some problem $i$ it will be $2 \cdot max(k, a_{i})$. Initially it's just $2 \cdot k$. Transition from $i$ to $i + 1$ will then look like this. If the upper limit it greater or equal to $a_{i + 1}$ then we solve this problem and update the upper limit. Otherwise we will need some problems from other judges. As our goal is to maximize the upper limit, the most optimal task to solve is the hardest possible. So you should solve task with the difficulty of upper limit and update the limit itself. Keep doing it until upper limit becomes grater or equal to $a_{i + 1}$. You will require no more then $\lceil\log a_{n}\rceil$ tasks from the other judges. By algorithm it's easy to see that by solving task with difficulty $d$ we update upper limit with the value $2 \cdot d$. This function produces such a estimate. Overall complexity: $O(n\cdot\log n+\log\operatorname*{max}a_{i})$.
[ "greedy", "implementation" ]
1,600
null
825
D
Suitable Replacement
You are given two strings $s$ and $t$ consisting of small Latin letters, string $s$ can also contain '?' characters. Suitability of string $s$ is calculated by following metric: Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings $s$, you choose the one with the largest number of \textbf{non-intersecting} occurrences of string $t$. Suitability is this number of occurrences. You should replace all '?' characters with small Latin letters in such a way that the suitability of string $s$ is maximal.
Notice that the order of letters doesn't matter at all, suitability depends only on amount of each letter. Let $f_{i}$ be the possibility that string $t$ will occur in $s$ at least $i$ times after replacing all '?' signs and after some swaps. If $f_{i}$ is true then $f_{i - 1}$ is also true. That leads to binary search over the answer. Let $cntT_{j}$ be the amount of letters $j$ in $t$ and $cntS_{j}$ - the amount of letters $j$ in $s$. $qcnt$ is the number of '?' signs. $f_{i}$ is true if $\sum_{j=^{\prime}\alpha^{\prime}}^{^{\prime}z^{\prime}}(c n t T_{j}\cdot i-m i n(c n t T_{j}\cdot i,c n t S_{j}))\leq q c n t$. If some letter appears in $s$ less times than needed then replace some '?' signs with it. Answer can be restored greedily by replacing '?' signs with the letters needed. Overall complexity: $O(n+A L\cdot\log{n})$, where $AL$ is the size of the alphabet.
[ "binary search", "greedy", "implementation" ]
1,500
null
825
E
Minimal Labels
You are given a directed acyclic graph with $n$ vertices and $m$ edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: - Labels form a valid permutation of length $n$ — an integer sequence such that each integer from $1$ to $n$ appears exactly once in it. - If there exists an edge from vertex $v$ to vertex $u$ then $label_{v}$ should be smaller than $label_{u}$. - Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.
This problem is usually called "Topological labelling". Though it's pretty common problem, we decided that it might be educational to some of participants. Let's set labels in descending order starting from label $N$ to label $1$. Look at first step. Vertex with label $N$ should have out-degree equal to zero. Among all such vertices we should put the label on the one that has the largest index. Ok, but why will this produce the lexicographically smallest labelling? We can prove this by contradiction. Let this vertex be labeled $X$ ($X < N$). Change it to $N$ and renumerate vertices with label $X + 1, ..., N$ to labels $X, ..., N - 1$. Labelling will come lexicographically smaller than it was, this leads to contradiction. So the algorithm comes as following. On step $i$ ($i = N... 1$) we find vertices with out-degree equal to zero, select the one with the largest index, set its label to $i$ and remove this vertex (and all edges connected to it) from the graph. Current minimal out-degree can be maintained with set, for example. Overall complexity: $O((n+m)\cdot\log{n})$.
[ "data structures", "dfs and similar", "graphs", "greedy" ]
2,300
null
825
F
String Compression
Ivan wants to write a letter to his friend. The letter is a string $s$ consisting of lowercase Latin letters. Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string $s$ instead of the string itself. The compressed version of string $s$ is a sequence of strings $c_{1}, s_{1}, c_{2}, s_{2}, ..., c_{k}, s_{k}$, where $c_{i}$ is the decimal representation of number $a_{i}$ (without any leading zeroes) and $s_{i}$ is some string consisting of lowercase Latin letters. If Ivan writes string $s_{1}$ exactly $a_{1}$ times, then string $s_{2}$ exactly $a_{2}$ times, and so on, the result will be string $s$. The length of a compressed version is $|c_{1}| + |s_{1}| + |c_{2}| + |s_{2}|... |c_{k}| + |s_{k}|$. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.
Let $dp[i]$ be the answer for the prefix of $s$ consisting of $i$ first characters. How can we update $dp[j]$ from $dp[i]$ ($i < j$)? Suppose that we try to represent the substring from index $i$ to index $j - 1$ ($0$-indexed) by writing it as some other string $k$ times. Then this string has to be the smallest period of the substring, and $k={\frac{j-i}{T}}$, where $T$ is the length of the smallest period. The smallest period of some string $t$ can be calculated as follows: compute prefix-function for $t$, and if $|t|$ is divisible by $|t| - p_{last}$ ($p_{last}$ is the last value of prefix-function), then the length of the smallest period is $|t| - p_{last}$ (if not, then the length of the smallest period is $|t|$). This allows us to write a solution with complexity $O(|s|^{3})$. To improve it to $O(|s|^{2})$, we can use the fact that when we compute prefix-function for some string, we compute it for every prefix of this string. So to obtain all values of $p_{last}$ we need in our solution, we only need to compute prefix-functions for every suffix of $s$.
[ "dp", "hashing", "string suffix structures", "strings" ]
2,400
null
825
G
Tree Queries
You are given a tree consisting of $n$ vertices (numbered from $1$ to $n$). Initially all vertices are white. You have to process $q$ queries of two different types: - $1$ $x$ — change the color of vertex $x$ to black. It is guaranteed that the first query will be of this type. - $2$ $x$ — for the vertex $x$, find the minimum index $y$ such that the vertex with index $y$ belongs to the simple path from $x$ to some black vertex (a simple path never visits any vertex more than once). For each query of type $2$ print the answer to it. \textbf{Note that the queries are given in modified way}.
After the first query make the vertex that we painted black the root of the tree and for each other vertex calculate the minimum index on the path to the root. This can be done by simple DFS. Then suppose we are painting some vertex $x$ black. In can easily proved that for every vertex $y$ and every vertex $z$ that is on a path form $x$ to the root there exists a path from $y$ to some black vertex coming through $z$. So we have to store the minimum index among all vertices $z$ such that $z$ belongs to the path from the root to some black vertex (it is a global value, let's call it $globalMin$), and the answer to every query of type $2$ is just the minimum of the value we calculated in DFS and $globalMin$. To update $globalMin$ quickly after painting vertex $x$ black, we ascend from $x$ to the root until we arrive to some node that was visited during previous queries (and we stop there because this node and all nodes on the path from it to the root were used to update $globalMin$ in previous queries). This solution works in $O(n)$ time.
[ "dfs and similar", "graphs", "trees" ]
2,500
null
827
A
String Reconstruction
Ivan had string $s$ consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string $s$. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string $s$. Namely, he remembers, that string $t_{i}$ occurs in string $s$ at least $k_{i}$ times or more, he also remembers exactly $k_{i}$ positions where the string $t_{i}$ occurs in string $s$: these positions are $x_{i, 1}, x_{i, 2}, ..., x_{i, ki}$. He remembers $n$ such strings $t_{i}$. You are to reconstruct \textbf{lexicographically minimal} string $s$ such that it fits all the information Ivan remembers. Strings $t_{i}$ and string $s$ consist of small English letters only.
At first let's sort all given string by their positions and also determine the length of the answer string. After that fill the answer string with letters "a" because the answer string must be lexicographically minimal. Let's use variable $prev$ - the minimal index of letter in the answer string which did not already processed. After that we need to iterate through the sorted strings. If the next string ends before $prev$ we skip it. In the other case, we need to impose this string to the answer string beginning from necessary position and write down all letters beginning from $prev$ or from the beginning of impose (depending on which of these values is greater). If the imposing of string ends in position $endPos$ we need to make $prev = endPos + 1$ and move to the next string.
[ "data structures", "greedy", "sortings", "strings" ]
1,700
null
827
B
High Load
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of $n$ nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly $k$ of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Hint: one of the optimal solutions is a star-like tree: one "center" node with $k$ paths with lengths difference at most one. Proof: let the optimal answer be something different from the structure described. If it is a star with $k$ paths, but the lengths differ by more than one, we can shorten the longest one and lengthen the shortest one, and the answer won't become greater. So, doing this operation once or more, we eventually get the described structure, that means that our answer is optimal. If the optimal answer is not a star, let's hang it on one of its centers, and let the diameter be $d$. Then the depths of all leaves are not greater than $\textstyle{\left[{\frac{d}{2}}\right]}$. Suppose there is some edge $e$ from the root that has more than one leaf in its subtree. Let $v$ be some leaf in this subtree, and its depth be $y$. Let's take the path from leaf $v$ all the way up to some vertex with degree more than $2$, and rehang this path to the root. The tree is now more star-like, and we are going to prove that the answer didn't become larger. Obviously, we're only interested in distances between $v$ and other leaves. Moreover, we can see that the current depth of $v$ is smaller than $y$, and the distance between $v$ and other leaves doesn't exceed $y-1+\left[{\frac{d}{2}}\right]\leq2\left[{\frac{d}{2}}\right]-1\leq d$. It is proved now.
[ "constructive algorithms", "greedy", "implementation", "trees" ]
1,800
null
827
C
DNA Evolution
Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string $s$ initially. Evolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand "AAGC": the second nucleotide can change to "T" so that the resulting DNA strand is "ATGC". Scientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows: - Let the infection be represented as a string $e$, and let scientists be interested in DNA strand segment starting from position $l$ to position $r$, inclusive. - Prefix of the string $eee...$ (i.e. the string that consists of infinitely many repeats of string $e$) is written under the string $s$ from position $l$ to position $r$, inclusive. - The value of impact is the number of positions where letter of string $s$ coincided with the letter written under it. Being a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists!
Note that there are only $4$ different characters and queries' lengths are only up to $10$. How does this help? Let's make $4$ arrays of length $|s|$ for each of the possible letters, putting $1$ where the letter in $s$ is that letter, and $0$ otherwise. We can update these arrays easily with update queries. Consider a letter in a query string $e$. It appears equidistantly in the string we write down under the string $s$. Thus, we should count the number of ones (in one of our four arrays) at positions which indices form an arithmetic progression, and bounded by some segment (the query segment $[l, r]$). This sounds hard, but we can note that the difference between the indices (i.e. the common difference of the arithmetic progression) is not larger than $10$. Thus, we can store $10$ copies of each of four arrays we created above. For the $x$-th copy of some letter, we reorder the elements so that first we put all positions $p$ for which $p\bmod x\equiv0$, then all positions $p$ for which $p\bmod x\equiv1$, and so on. This will make possible to change each query on an arithmetic progression to a sum query on a segment. Thus, we can just sum up answers for each letter in string $e$.
[ "data structures", "strings" ]
2,100
null
827
D
Best Edge Weight
You are given a connected weighted graph with $n$ vertices and $m$ edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id $i$. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the other weights. You are to determine this maximum weight described above for each edge. You should calculate the answer for each edge independently, it means there can't be two edges with changed weights at the same time.
Hint 1: Find some MST in the initial graph and name it $M$. Now there are edges of two types: in the tree, and not in the tree. Process them in a different way. Hint 2: For edges not in the MST, the answer is the maximum weight of MST edges on the path between the edge's ends, minus one. Proof: Consider the edge $E$ such that it doesn't appear in our MST and its weight is $W$ and consider the maximum weight of MST edges on the path between the edge's ends is $MX$. It's obvious that if $W \ge MX$ there is an MST such that $E$ will not appear in that (at least it will not appear in $M$). Now let's prove that if $W = MX - 1$ it will appear in any MST. Consider an MST like $OM$ that $E$ does not appear in that, let's prove $M$ was not an MST and it's a contradiction. Let ends of $E$ be $v, u$. Look, consider the path between $v, u$ in $M$, there is an edge with weight $MX$ in this path but there isn't any edge in $OM$ with weight greater than or equal to $MX$. So $M$ is not an MST because when we build an MST we sort edges by their weight and add them greedily (Kruskal's algorithm). Hint 3: For an edge $E$ in the MST, let non-MST edges such that MST path between their ends go through $E$ be bad edges, the answer is the minimum weight of bad edges, minus one. Proof: Let the minimum weight of bad edges be $CW$ and weight of $E$ be $W$. It is obvious that if $W \ge CW$ there is an MST such that $E$ will not appear in that. Now if $W < CW$ so we will check $E$ before bad edges and we will add it. The remaining part is easy: for non-MST edges, one can just query the maximum on a tree path with binary lifts or whatever other structure on a tree. For MST edges, we can do the same, but in the other direction, like range queries, or even easier with centroid decomposition, HLD or using sets and the smaller-to-larger optimization. Thanks Arpa for the proofs!
[ "data structures", "dfs and similar", "graphs", "trees" ]
2,700
null
827
E
Rusty String
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length $n$ and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written. Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to? A period of a string is such an integer $d$ from $1$ to the length of the string that if we put the string shifted by $d$ positions to the right on itself, then all overlapping letters coincide. For example, $3$ and $5$ are periods of "VKKVK".
Let $s_{i}$ is symbol number $i$ from the given string. Statement: $k$ can be period of string $s$ when if and only if there are no two indices $i$ and $j$ for which $s_{i}\neq s_{j},s_{i}\neq?\gamma,s_{j}\neq7,t{\mathrm{~}}\mathrm{~}\mathrm{mod}\;k=j\mathrm{~mod}\;k$. Evidence: Necessity: Let it is not true. Then for any letter fill of omissions such paint $i$ and $j$ will left that $s_{i} \neq s_{j}, s_{i} \neq ?, s_{j} \neq ?$ and this contradicts the definition of the period. Adequacy: Let fill omissions with constructive algorithm in a way that string after that is having a period $k$. Let's look on some remainder of division on $k$. There are two options. In the first option there are no such $i$ that $i$ gives needed remainder by divide on $k$ and $s_{i} \neq ?$. Then let fill all positions with such remainder with symbol "V". In the second option there are $i$ such that $i$ gives this remainder by division on $k$ and $s_{i} \neq ?$. Let fill all positions with this remainder symbol $s_{i}$. Now in all positions with equal remainder by division on $k$ in string stand equal symbols and it means that string has period $k$. Let's call a pair indices $i$ and $j$ contradictory, if $s_{i} \neq s_{j}, s_{i} \neq ?$ and $s_{j} \neq ?$, then the string has period $k$ if and only if there are no contradictory pair $i$ and $j$ for which $|i - j|$ is divisible by $k$. This is a direct consequence of the statement proved above. Let's learn how to search for all such numbers $x$ that there is contradictory pair $i$ and $j$ that $i - j = x$. Let $A$ - the set of positions, where stand "V", and $B$ - the set of such positions $i$ that $s_{n - i} = K$. So our task reduced to finding such all possible numbers that it is representable as the sum of a number from $A$ and a number from $B$. Let's look on polynomials $P(x) = a_{1}x^{1} + a_{2}x^{2} + ..., Q(x) = b_{1}x^{1} + b_{2}x^{2} + ...$, where $a_{i}$ equals to $1$, if $i$ can be found in $A$ or $0$, otherwise. Similarly for set $B$ and $b_{i}$. Let's look on $P(x) * Q(x)$. Coefficient at $x^{i}$ is equal to $1$ if and only if when $i$ can be represented in sum of a number from $A$ and a number from $B$. It is correct because coefficient at $x^{i}$ equals to $\sum_{j=0}^{i}a_{j}b_{i-j}$. But $a_{j}b_{i - j} \ge 0$ and equals to $1$ if and only if when $a_{j} = 1$ and $b_{i - j} = 1$, and it means that $j\in A,(i-j)\in B$, but $j + (i - j) = i$. Polynomials can be multiplied with help of Fast Fourier transform, so this part of solution works in $O(nlogn)$. It is only left to learn how to check that $k$ is a period of string. It can be done in $O({\frac{n}{k}})$, with check all numbers like $ik \le n$. Totally it works in $\sum_{i=1}^{n}O(\frac{n}{k})=O(n l o g n)$. So, all solution works in $O(nlogn)$.
[ "fft", "math", "strings" ]
2,700
null
827
F
Dirty Arkady's Kitchen
Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during some time interval. The lengths of all passages are equal and Arkady makes through them in one second. For security reasons, Arkady can never stop, also, he can't change direction while going through a passage. In other words, if he starts walking in some passage, he should reach its end and immediately leave the end. Today Arkady needs to quickly reach important place $n$ from place $1$. He plans to exit the place $1$ at time moment $0$ and reach the place $n$ as early as he can. Please find the minimum time he should spend on his way.
Let's consider undirected edge$(u;v)$ as two directed edges $(u;v)$ and $(v;u)$. Let Arkady came to the vertex $u$ in moment of time $t$. Then he can come to $v$ in moments of time $t + 1, t + 3, ...$ until the edge is existing. We will expand each directed edge: on one of them we can come in even moments of time and leave in odd; on the other edge we can come in odd moments of time and leave in even. So, each of the edges from initial graph has turned in 4 edges of the new graph. Let's calculate for each edge $dp_{i}$ - the minimal moment of time when we can come on the edge $i$. Let's count this values with help of sorting of events like "edge appeared". For each vertex and parity we will remember the edge for which we can appear in this vertex in moments of time with such a parity which will disappear later than others. When the event of appearing edge became we need to check if it is possible in this moment of time come to the beginning of this edge. If it is possible then $dp_{i} = l_{i}$, where $l_{i}$ - the minimal moment of time when it is possible to come to the beginning of the edge to go through this edge. Every time when some vertex became reachable with needed parity we say that value of $dp$ is equals to this time for all edges which wait in this vertex this parity. Totally each edge will processed no more than two times, so totally solution works in $O(nlogn)$.
[ "data structures", "dp", "graphs", "shortest paths" ]
3,200
null
828
A
Restaurant Tables
In a small restaurant there are $a$ tables for one person and $b$ tables for two persons. It it known that $n$ groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group. If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group. You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.
We need to store three values: $a$ - the number of free tables for one person, $b$ - the number of free tables for two persons and $c$ - the number of tables for two persons occupied by single person. If the next group consisting of $2$ persons and there are no free tables for two persons (i. e. $b = = 0$) the restaurant denies service to this group and we need to add $2$ to the answer. In the other case, we need subtract one from $b$ and move to the next group. If the next group consisting of $1$ person and there is free table for one person (i. e. $a > 0$) we need to subtract one from $a$ and move to the next group. In the other case, if there is free table for two persons you need to put person for this table, subtract one from $b$ and add one to $c$. If there are no free tables but $c > 0$ we need to subtract one form $c$. If no one from the described conditions did not met the restaurant denies service to this group consisting of one person and we need to add one to the answer and move to the next group.
[ "implementation" ]
1,200
null
828
B
Black Square
Polycarp has a checkered sheet of paper of size $n × m$. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.
If there are no black cells on the field it is enough to paint any one cell. In the other case, we need to calculate $4$ values: $minX$ - the index of upper row with black cell; $maxX$ - the index of bottom row with black cell; $minY$ - the index of leftmost column with black cell; $maxY$ - the index of rightmost column with black cell. After that we can get the length of square side which should be obtained after repainting. Let this side equals to $len$ and $len = max(maxX - minX + 1, maxY - minY + 1)$. If $len$ more than $n$ or $len$ more than $m$ there is no solution. Else, the answer is equals to $len \cdot len - cnt$, where $len \cdot len$ is the number of cells in the resulting square and $cnt$ is the number of black cells on the initial field. The value $cnt$ can be calculated in one iteration through the given field.
[ "implementation" ]
1,300
null
830
A
Office Keys
There are $n$ people and $k$ keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the minimum time needed for all $n$ people to get to the office with keys. Assume that people move a unit distance per $1$ second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.
To solve this problem you need to understand the fact that all keys which people will take is continuous sequence of length $n$ in sorted array of keys. At first let's sort all keys in increasing order of their positions. Then brute which of the keys will take a leftmost person. Let it will be $i$-th key. Then the second person from the left will take the key $i + 1$, third - $(i + 2)$ and etc. So, we can determine the time after which all people can reach the office with keys if the sequence of keys beginning from $i$-th key. Now we need to update the answer with this value and move to the next position $i + 1$.
[ "binary search", "brute force", "dp", "greedy", "sortings" ]
1,800
null
830
B
Cards Sorting
Vasily has a deck of cards consisting of $n$ cards. There is an integer on each of the cards, this integer is between $1$ and $100 000$, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is. You are to determine the total number of times Vasily takes the top card from the deck.
First note that operation "put a card under the deck" is the same as "stark viewing from the beginning when you reach the end", and do not move cards anywhere. Then, let's proceed all cards with equal numbers on them at once. It's obvious that Vasily puts them away one after another. Let's denote the position where he was when he put the last card less than $x$ be position $p$ in the deck. Two cases are possible. If all cards equal to $x$ are after position $p$, then he looks all the cards until he takes the last card with $x$, and puts away all cards equal to $x$; Otherwise there is a card with $x$ that is before $p$. In this case Valisy looks at all cards from $p$ to the end, and after that - at all cards from the beginning of the deck to the last card with $x$ that is before $p$. It's easy to process both cases if we keep for each $x$ positions of all cards with $x$ from the top to the bottom of the deck. Aside of this we need any data structure that is capable of computing sum on a segment and changing a single value (we can store $1$ for a position with a card in the deck, and $0$ is the card is already put away). We can use segment tree or Fenwick tree for example.
[ "data structures", "implementation", "sortings" ]
1,600
null
830
C
Bamboo Partition
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are $n$ bamboos in a row, and the $i$-th from the left is $a_{i}$ meters high. Vladimir has just planted $n$ bamboos in a row, each of which has height $0$ meters right now, but they grow $1$ meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing. Vladimir wants to check the bamboos each $d$ days (i.e. $d$ days after he planted, then after $2d$ days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than $k$ meters. What is the maximum value $d$ he can choose so that he can achieve what he wants without cutting off more than $k$ meters of bamboo?
First fact: The problem is asking to maximize $d$ such that: $\textstyle\sum_{i=1}^{n}(d\lceil{\frac{a_{i}}{d}}\rceil-a_{i})\leq k$. $\textstyle{\sum_{i=1}^{n}(d\left[{\frac{a_{i}}{d}}\right]-a_{i})\leq k\Rightarrow d\sum_{i=1}^{n}\left[{\frac{a_{i}}{d}}\right]\leq k+\sum_{i=1}^{n}a_{i}}$. Let $C=k+\textstyle\sum_{i=1}^{n}a_{i}$, then $d\sum_{i=1}^{n}\left[{\frac{a_{i}}{d}}\right]\leq C$. Second fact: Number of possible values for $\left[{\frac{a}{b}}\right]$ is $O({\sqrt{a}})$. For $x$, let $A=\lfloor{\sqrt{x}}\rfloor$ these values are $1... A$ and $\left[{\begin{array}{l}{x}\\ {1}\end{array}}\right]\cdot\cdot\cdot\left[{\frac{x}{A}}\right]$. So there is at most $O(n\cdot{\sqrt{m a x_{i=1}^{n}a_{i}}})$ segments for $d$ such that $\textstyle\sum_{i=1}^{n}\left|{\frac{a_{i}}{d}}\right|$ will not change. Now generate all possible values and sort them, and for each segment check if there is a $d$ in that segment satisfying the condition and update the answer. My solution. Thanks Arpa for this editorial!
[ "brute force", "data structures", "implementation", "math", "number theory", "sortings", "two pointers" ]
2,300
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e2 + 17, maxsq = sqrt(1e9); const ll inf = 1e12; int n, a[maxn], sz; ll C, seg[maxn * 2 * maxsq]; int ceil(int n, int r){ return (n + r - 1) / r; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> C; seg[sz++] = 1; for(int i = 0; i < n; i++){ cin >> a[i]; for(int j = 1; j * j <= a[i]; j++) seg[sz++] = j, seg[sz++] = ceil(a[i], j); C += a[i]; } seg[sz++] = inf; sort(seg, seg + sz); sz = unique(seg, seg + sz) - seg; ll ans = 0; for(int i = 0; i < sz - 1; i++){ int l = seg[i], r = seg[i + 1]; ll cur = 0; for(int j = 0; j < n; j++) cur += ceil(a[j], l); ll d = C / cur; if(l <= d && ans < d) ans = d; } cout << ans << '\n'; return 0; }
830
D
Singer House
It is known that passages in Singer house are complex and intertwined. Let's define a Singer $k$-house as a graph built by the following process: take complete binary tree of height $k$ and add edges from each vertex to all its successors, if they are not yet present. \begin{center} {\small Singer $4$-house} \end{center} Count the number of non-empty paths in Singer $k$-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo $10^{9} + 7$.
Hint: Compute dp[k][c] "what is the number of sets of $c$ non-intersecting paths in $k$-house?" Yes, it works. The answer is dp[k][1]. $dp_{1, 0} = dp_{1, 1} = 1$. For updating $dp_{i}$ from $dp_{i - 1}$ for each $L, R(1 \le L, R \le 2^{i - 1})$ Let $X = dp_{i - 1, L} \cdot dp_{i - 1, R}$: Take the root, and make itself a new path $\longrightarrow\bigcup$ $dp_{i, L + R + 1} + = X$. Don't take the root $\longrightarrow\bigcup$ $dp_{i, L + R} + = X$. Take the root, and connect it to a path in the left child $\longrightarrow$ $dp_{i, L + R} + = X \cdot L \cdot 2$. Take the root, and connect it to a path in the right child $\longrightarrow\bigcup$ $dp_{i, L + R} + = X \cdot R \cdot 2$. Take the root, and it combines two paths $\longrightarrow\bigcup$ $dp_{i, L + R - 1} + = X \cdot C(L + R, 2) \cdot 2$. Now the important fact is because we need $dp_{k, 1}$ we only need first $k$ values of $dp_{i}$. So the complexity is $O(k^{3})$. Thanks Arpa for this editorial!
[ "combinatorics", "dp", "graphs", "trees" ]
2,800
null
830
E
Perpetual Motion Machine
Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way. Each element has one controller that can be set to any non-negative real value. If a controller is set on some value $x$, then the controller consumes $x^{2}$ energy units per second. At the same time, any two elements connected by a wire produce $y·z$ energy units per second, where $y$ and $z$ are the values set on their controllers. Petr has only a limited number of wires, so he has already built some scheme of elements and wires, and is now interested if it's possible to set the controllers in such a way that the system produces \textbf{at least as much} power as it consumes, and at least one controller is set on the value different from $0$. Help him check this, and if it's possible, find the required \textbf{integer} values that should be set. It is guaranteed that if there exist controllers' settings satisfying the above conditions, then there exist required integer values not greater than $10^{6}$.
By default, all vertices contain $0$. We will solve problem in few steps, getting answer for our question in different cases. Graph contains cycle. In this case, solution exists, all vertices of cycle contain $1$, sum would be $0$. Graph contains vertex with degree more than $3$. Solution exists, this vertex has $2$ and its neighbours $1$. Sum will be $2^{2} + deg(v) - 2 * deg(v) \le 0$ when $deg(v) \ge 4$. Graph contains more than one vertex of degree $3$. In this case we can reduce to previous case: we put $2$ in the between these vertices and ones in other neighboors. Doing this, we "contract" path between vertices to one with the number $2$ and obtain vertex of degree $4$. Graph contains just one vertex of degree $3$. It is the most complicated point in our solution. We just state this and prove it later.Statement: There is only one vertex with degree $3$, with 'tails' of sizes $p - 1$, $q - 1$ and $r - 1$ (length of the tail = how many vertices lay on it). In this case expression can take only non-positive values if $\textstyle{\frac{1}{p}}+{\frac{1}{q}}+{\frac{1}{r}}\leq1$. Statement: There is only one vertex with degree $3$, with 'tails' of sizes $p - 1$, $q - 1$ and $r - 1$ (length of the tail = how many vertices lay on it). In this case expression can take only non-positive values if $\textstyle{\frac{1}{p}}+{\frac{1}{q}}+{\frac{1}{r}}\leq1$. All graph's vertices have degree less than $3$. This case can be easily reduced to previous one, having $p = 1$. We are going to prove this by two ways. First way: Let's look on tail, sized $k$, having form of the bamboo. Numbers in vertices are $a_{i}$ and have sum $A$. We are going to minimize $A$. As one can see, $2A = 2a_{1}^{2} - 2a_{1}a_{2} + 2a_{2}^{2} - 2a_{2}a_{3} + ... - 2a_{k - 1}a_{k} + 2a_{k}^{2} = a_{1}^{2} + (a_{2} - a_{1})^{2} + (a_{3} - a_{2})^{2} + ... + (a_{k} - a_{k - 1}^{2}) + a_{k}^{2}$ Let $a_{k} = S$, $d_{1} = a_{1}$, $d_{2} = a_{2} - a_{1}$, $d_{3} = a_{3} - a_{2}$, ..., $d_{k} = a_{k} - a_{k - 1}$. Then $2A = d_{1}^{2} + d_{2}^{2} + ... + d_{k}^{2} + S^{2}$ While $\sum_{i=1}^{k}d_{i}=a_{1}+\sum_{i=2}^{k}a_{i}-a_{i-1}=a_{k}=S$ We will use induction for proof. Base ($n = 1$) is evident. Step $n \rightarrow n + 1$: $f(x)={\frac{(S-x)^{2}}{n}}+x^{2}$ - optimal sum of squares if one of $n + 1$ numbers is $x$. We shall minmize this function. This is nearly equal to derivative being zero. $-2^{\underline{{{S}}}-x}+2x=0\Rightarrow S-(n+1)x=0\Rightarrow x={\frac{S}{n+1}}$, what we wanted to prove. Now we get back to construction where are three tails of sizes $p$, $q$ and $r$ are connected to 3-degree vertex. Number in 3-degree vertex is $S$, value of the whole graph is $D$, and values of tails are $A$, $B$ and $C$. $(2A - S^{2}) + (2B - S^{2}) + (2C - S^{2}) = 2D + S^{2}$. If we fix $S$, when, as it was shown before optimal values of tails are i$2A-S^{2}={\frac{s^{2}}{p}}$, $2B-S^{2}={\frac{S^{2}}{q}}$, $2C-S^{2}={\frac{S^{2}}{r}}$. We have $(\textstyle{\frac{1}{p}}+\textstyle{\frac{1}{q}}+{\frac{1}{r}}-1)S^{2}=2D$. It means that $D \le 0$ can be only if $\textstyle{\frac{1}{p}}+{\frac{1}{q}}+{\frac{1}{r}}\leq1$. Second way: Let the tail of size $p$ have numbers in vertices $x_{1}, x_{2}, ... x_{p - 1}$ counting from the leaf, size $q$ - $y_{1}, y_{2}, ... y_{q - 1}$, size $r$ - $z_{1}, z_{2}, ... z_{r - 1}$. Root we will define as $v = x_{p} = y_{q} = z_{r}$. Let $A_{x} = x_{1}^{2} + x_{2}^{2} + ... + x_{p - 1}^{2} - x_{1x}_{2} - ... - x_{p - 2}x_{p - 1} - x_{p - 1}v,$ $A_{y} = y_{1}^{2} + y_{2}^{2} + ... + y_{q - 1}^{2} - y_{1y}_{2} - ... - y_{q - 2}y_{q - 1} - y_{q - 1}v,$ $A_{z} = z_{1}^{2} + z_{2}^{2} + ... + z_{r - 1}^{2} - z_{1z}_{2} - ... - z_{r - 2}z_{r - 1} - z_{r - 1}v.$ We want to compute $S = v^{2} + A_{x} + A_{y} + A_{z}$. One can see that $2A_{x}=\sum_{i=1}^{p-1}\frac{i+1}{i}(x_{i}-\frac{i}{i+1}x_{i+1})^{2}-\frac{p-1}{p}v^{2}=F(x)-\frac{p-1}{p}v^{2},$ $2A_{y}=\sum_{i=1}^{q-1}\frac{i+1}{i}(y_{i}-\frac{i}{i+1}y_{i+1})^{2}-\frac{q-1}{q}v^{2}=F(y)-\frac{q-1}{q}v^{2},$ $2A_{z}=\sum_{i=1}^{r-1}\frac{i+1}{i}(z_{i}-\frac{i}{i+1}z_{i+1})^{2}-\frac{r-1}{r}v^{2}=F(z)-\frac{r-1}{r}v^{2}.$ Actually, if we calculate this expression, we will have $2A_{x}=2x_{1}^{2}-2x_{1}x_{2}+{\frac{1}{2}}x_{2}^{2}+{\frac{3}{2}}x_{3}^{2}-2x_{2}x_{3}+{\frac{2}{3}}x_{3}^{2}+\dots\dots-2x_{p-1}x_{p}+{\frac{p-1}{p}}x_{p}-{\frac{p-1}{p}}x_{p}+\cdots+x_{r}x_{p}+\sum_{p}^{p-1}x_{p}-\sum_{p}+\cdots$ Each term with $x_{i}^{2}$ features once on both adjacent terms and gives the sum $\d\L_{i}^{\underline{{\varepsilon}}-1}x_{i}^{\underline{{\varepsilon}}}+\displaystyle{\frac{i+1}{i}}x_{i}^{\underline{{\varepsilon}}}=\displaystyle{\frac{2i}{i}}x_{i}^{2}=2x_{i}^{2}$ When, $2S=F(x)+F(y)+F(z)-{\frac{p-1}{p}}v^{2}-{\frac{q-1}{q}}v^{2}-{\frac{r-1}{r}}v^{2}+2v^{2}$ $F(x)+F(y)+F(z)+\left({\frac{1}{p}}+{\frac{1}{q}}+{\frac{1}{r}}-1\right)v^{2}.$ Because all $F \ge 0$, we should have other expression not greater than zero. However, $v \neq 0$, because in this case for having all squares zero all numbers would be zero. Because of this, $\textstyle{\frac{1}{p}}+{\frac{1}{q}}+{\frac{1}{r}}\leq1$. Conclusion: Necessity of this criterion is proved. Sufficiency can be seen from definition $F$ in the second proof - we should put arithmetic progressions on all tails. In case of graph having form of bamboo, we have $1+{\frac{1}{q}}+{\frac{1}{r}}-1\leq0$, equal to $\textstyle{\frac{1}{q}}+{\frac{1}{r}}\leq0$ while $q, r \ge 1$, what is obviously impossible. So answer is always <<NO>>. All mentioned above is made with few depth-first searches, so complexity of this solution is $O(V + E)$.
[ "constructive algorithms", "dp", "graphs", "implementation", "math", "trees" ]
3,100
null
831
A
Unimodal Array
Array of integers is unimodal, if: - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arrays are unimodal: $[5, 7, 11, 11, 2, 1]$, $[4, 4, 2]$, $[7]$, but the following three are not unimodal: $[5, 5, 6, 6, 1]$, $[1, 2, 1, 2]$, $[4, 5, 5, 6]$. Write a program that checks if an array is unimodal.
Let use two variables $pos_{1}$ and $pos_{2}$. Initially $pos_{1} = 0$ and $pos_{2} = n - 1$. After that we need to iterate through the given array from the left to the right and increase $pos_{1}$ until the next element is strictly more than previous. After that we need to iterate through the given array from the right to the left and decrease $pos_{2}$ until $a[pos_{2} - 1] > a[pos_{2}]$. Now it is left only to check that all elements between positions $pos_{1}$ and $pos_{2}$ are equal to each other. If it is true the answer is "YES", otherwise, the answer is "NO".
[ "implementation" ]
1,000
null
831
B
Keyboard Layouts
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with $26$ letters which coincides with English alphabet. You are given two strings consisting of $26$ distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout. Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.
At first we need to support the correspondence of letters on keyboards. For example, it can be done with help of $map < char, char >$. Let's call it $conformity$. Let the first layout equals to $s_{1}$ and the second - $s_{2}$. Now we need to iterate through the first string and make $conformity[s_{1}[i]] = s_{2}[i]$. Also we need to make $conformity[toupper(s_{1}[i])] = toupper(s_{2}[i])$, where function $toupper(c)$ gives the lowercase letter $c$ to the corresponding uppercase letter. After that simply iterate through the given text. Let the current symbol is $c$. If $c$ is a digit we need to print it. Otherwise, $c$ is a letter, so we need to print $conformity[c]$.
[ "implementation", "strings" ]
800
null
831
C
Jury Marks
Polycarp watched TV-show where $k$ jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the $i$-th jury member gave $a_{i}$ points. Polycarp does not remember how many points the participant had before this $k$ marks were given, but he remembers that among the scores announced after each of the $k$ judges rated the participant there were $n$ ($n ≤ k$) values $b_{1}, b_{2}, ..., b_{n}$ (it is guaranteed that all values $b_{j}$ are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. $n < k$. Note that the initial score wasn't announced. Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
At first let's calculate an array $sum$ where $sum[i]$ equals to sum of the first $i$ jury points. Now consider the value $b_{1}$. Let the initial score equals to $x$. Here we need to iterate by $m$ from $1$ to $k$ - how many members of jury rated the participant until Polycarp remembered $b_{1}$. Then $x = b_{1} - sum[m]$. Insert each initial scores in $set$. So, we got all possible initial participant scores. After that it is left only to check correctness of each initial score. Let the another candidate on initial score equals to $d$. We need to put in set $points$ all values $d + sum[i]$ for all $i$ from $1$ to $k$. After that we need to check that all elements of array $b$ can be find in $points$. If it is true the participant could has initial score $d$ points, so we need to increase the answer on one.
[ "brute force", "constructive algorithms" ]
1,700
null
832
A
Sasha and Sticks
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws $n$ sticks in a row. After that the players take turns crossing out exactly $k$ sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than $k$ sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
Note, that it's not important from which side sticks are being crossing out. Players will make summary $\left\lfloor{\frac{22}{k}}\right\rfloor$ turns. If this number is odd, Sasha made $1$ more turn than Lena and won. Otherwise, Sasha and Lena made same number of turns and Sasha didn't win.
[ "games", "math" ]
800
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 17, lg = 17; ll n, k; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; cout << ((n / k) & 1 ? "YES" : "NO") << '\n'; return 0; }
832
B
Petya and Exam
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs \textbf{no more than once} in the pattern. Also, $n$ query strings are given, it is required to determine for each of them if the pattern matches it or not. Everything seemed easy to Petya, but then he discovered that \textbf{the special pattern characters differ from their usual meaning}. A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string. The good letters are given to Petya. All the others are bad.
If pattern doesn't contain "*", to match pattern, it's neccesary that string's size is equal to pattern size , all letters in pattern match with the letters in string, and in the positions on which pattern contains "?", the string contains good characters. If pattern contains "*", split it into two strings: $p_{1}$ contains all characters before "*" and $p_{2}$ after it. Note, that string doesn't match pattern, if it's size is less than $|p_{1}| + |p_{2}|$. Split the string into three: $s_{1}$ is prefix of size $|p_{1}|$, $s_{2}$ is suffix of size $|p_{2}|$, and $s_{3}$ is the remaining substring. The string mathes pattern, if $s_{1}$ matches $p_{1}$, $s_{2}$ matches $p_{2}$ and $s_{3}$ contains only bad characters. Obviously, that we can make all checks in time of $O(|s|)$. Final asymptotics is $O(\sum_{i=1}^{n}|s|)$.
[ "implementation", "strings" ]
1,600
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 17, z = 26; int n; bool good[z]; string goods, pat; bool mat(string pat, string s){ if(pat.size() != s.size()) return 0; for(int i = 0; i < s.size(); i++) if(pat[i] != '?'){ if(s[i] != pat[i]) return 0; } else if(!good[s[i] - 'a']) return 0; return 1; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> goods >> pat >> n; for(auto c : goods) good[c - 'a'] = 1; auto p = pat.find('*'); for(string s; n--; ){ cin >> s; if(s.size() < pat.size() - 1) cout << "NO" << '\n'; else if(p == string :: npos) cout << (mat(pat, s) ? "YES" : "NO") << '\n'; else{ bool ok = 1; ok &= mat(pat.substr(0, p), s.substr(0, p)); reverse(pat.begin(), pat.end()); reverse(s.begin(), s.end()); p = pat.size() - p - 1; ok &= mat(pat.substr(0, p), s.substr(0, p)); reverse(pat.begin(), pat.end()); reverse(s.begin(), s.end()); p = pat.size() - p - 1; for(int i = p; i < s.size() - (pat.size() - p - 1); i++) ok &= !good[ s[i] - 'a' ]; cout << (ok ? "YES" : "NO") << '\n'; } } return 0; }
832
C
Strange Radiation
$n$ people are standing on a coordinate axis in points with positive integer coordinates strictly less than $10^{6}$. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed $s$: one to the right, and one to the left. Of course, the speed $s$ is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point $0$, and there is a person that has run through point $10^{6}$, is as small as possible. In other words, find the minimum time moment $t$ such that there is a point you can place the bomb to so that at time moment $t$ some person has run through $0$, and some person has run through point $10^{6}$.
We'll use binary search by answer. Obviously, that answer is always less than $10^{6}$ and more than $0$. We denote the answer for $t$ at current iteration. For each person, running left, we have to find positions of bomb, at which he will have time to reach the point $0$ in time $t$. Let $d$ be the distance between the person and point $0$ and $d_{1}$ be the distance, which passed the person before he caught up with the ray. If ${\frac{d}{v_{i}}}\leq l$, we can place bomb in every point. Otherwise, we can place bomb in point $x$, ${\begin{array}{c}{{\left\{{\frac{d_{1}}{v_{i}}}+{\frac{d-d_{1}}{v_{i}+s}}\leq t,}}\\ {{\left\{x\geq d,}}\\ {{x=\left(d-d_{1}\right)+{\frac{d_{1}\cdot s}{v_{i}}}}\end{array}}$ Before the meeting with the ray, person ran a distance of $d_{1}$ at a speed of $v_{i}$, after the meeting he ran a distance of $d - d_{1}$ at a speed of $v_{i} + s$. We require the total time be no more than $t$. We need the person to be caught by rays, so bomb have to have coordinate more than person's initial coordinate. We know that rays and person met at the point of $d - d_{1}$ at the moment of $\frac{d_{1}}{v_{i}}$. Rays moves at the speed of $s$. It means they started moving at the point of $(d-d_{1})+{\frac{d_{1}\cdot s}{v_{i}}}$. Note that solutions of this system form a segment on the coordinate line. For persons, running right, the reasoning is similar. We find all the segments for persons, runnig left, and persons, running right. If some point with the whole coordinate belongs to segment for person, running left and person, running right, we move right border of binary search and left border otherwise. To find this point we can use scanline or prefix sums. Let the binary search make $it$ iterations. Than final asymptotics is $O(n \cdot log n \cdot it)$, if we use scanline, or $O((n + max_{x}) \cdot it)$ if we use prefix sums.
[ "binary search", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int OPEN = 1; const int CLOSE = -1; struct tsob { int x, t, id; }; inline bool operator<(const tsob &a, const tsob &b) { if (a.x != b.x) return a.x < b.x; return a.t == OPEN && b.t == CLOSE; } const int maxn = 100005; const int DR = 1000000; int curb[2]; vector<tsob> sobs; int x[maxn], v[maxn], dir[maxn], dist[maxn]; int n, s; bool can(ld t) { sobs.clear(); curb[0] = 0; curb[1] = 0; for (int i = 0; i < n; i++) { if (dist[i] <= (ll)v[i] * t) { curb[dir[i]]++; } else if (dist[i] <= (ll)(v[i] + s) * t) { // A * r + B = 0 ld A = (ld)1 / (s - v[i]) - (ld)v[i] / (s - v[i]) / (s + v[i]); ld B = (ld)dist[i] / (s + v[i]) - t; ld r = -B / A; if (dir[i] == 0) { sobs.pb({x[i], OPEN, dir[i]}); sobs.pb({lround(min((ld)DR + 1, floor(x[i] + r))), CLOSE, dir[i]}); } else { sobs.pb({lround(max((ld)-1.0, ceil(x[i] - r))), OPEN, dir[i]}); sobs.pb({x[i], CLOSE, dir[i]}); } } } if (curb[0] > 0 && curb[1] > 0) return true; sort(all(sobs)); for (auto t : sobs) { curb[t.id] += t.t; if (curb[0] > 0 && curb[1] > 0) return true; } return false; } int main() { scanf("%d%d", &n, &s); for (int i = 0; i < n; i++) { scanf("%d%d%d", &x[i], &v[i], &dir[i]); dir[i]--; if (dir[i] == 0) dist[i] = x[i]; else dist[i] = DR - x[i]; } ld l = 0; ld r = 1e6; for (int IT = 0; IT < 50; IT++) { ld m = (l + r) / 2; if (can(m)) r = m; else l = m; } cout.precision(20); cout << (double)(l + r) / 2 << endl; return 0; }
832
D
Misha, Grisha and Underground
Misha and Grisha are funny boys, so they like to use new underground. The underground has $n$ stations connected with $n - 1$ routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station $s$ to station $f$ by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including $s$ and $f$). After that on the same day at evening Grisha will ride from station $t$ to station $f$ by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean. The boys have already chosen three stations $a$, $b$ and $c$ for each of several following days, one of them should be station $s$ on that day, another should be station $f$, and the remaining should be station $t$. They became interested how they should choose these stations $s$, $f$, $t$ so that the number Grisha will count is as large as possible. They asked you for help.
Let vertex $1$ be the root of the tree. For each vertex $i$ we calculate value $h_{i}$ - distance to the root. Now we can represent way $v_{1}$ $\to$ $v_{2}$ as two ways $v_{1}$ $\to$ $lca(v_{1}, v_{2})$ and $lca(v_{1}, v_{2})$ $\to$ $v_{2}$. Note that number of edges in the interseption of two such ways $v_{1}$ $\to$ $v_{2}$ and $u_{1}$ $\to$ $u_{2}$, $h_{v1} \le h_{v2}$, $h_{u1} \le h_{u2}$ is $max(0, h_{lca(u2, v2)} - max(h_{v1}, h_{u1}))$. We can calculate $lca$ in $O(log n)$, using binary lifting, or in $O(1)$, using $\mathrm{SParSe~table}$. Using the formula we can easy calculate answer for fixed $s$, $f$ and $t$. To answer the query, we consider all possible permutations of $a$, $b$ and $c$, there are only $3!$. Final asymptotics is $O(n \cdot log n + q \cdot log n)$ or $O(n + q)$, depending on the $lca$ search algorithm.
[ "dfs and similar", "graphs", "trees" ]
1,900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 17, lg = 17; int n, q, par[maxn][lg], h[maxn], ver[3]; vector<int> g[maxn]; void dfs(int v = 0){ for(int i = 1; i < lg; i++) par[v][i] = par[ par[v][i - 1] ][i - 1]; for(auto u : g[v]){ h[u] = h[v] + 1; par[u][0] = v; dfs(u); } } int lca(int v, int u){ if(h[v] > h[u]) swap(v, u); for(int i = 0; i < lg; i++) if(h[u] - h[v] >> i & 1) u = par[u][i]; for(int i = lg - 1; i >= 0; i--) if(par[v][i] != par[u][i]) v = par[v][i], u = par[u][i]; return v == u ? v : par[v][0]; } int calc(int f, int s, int t){ int ans = 0; bool is1 = lca(f, s) == f, is2 = lca(f, t) == f; if(is1 != is2) return 1; if(is1) ans = max(ans, h[ lca(s, t) ] - h[ f ]); else if(lca(f, s) != lca(f, t)) ans = max(ans, h[ f ] - max(h[ lca(f, s) ], h[ lca(f, t) ])); else ans = max(ans, h[ f ] + h[ lca(s, t) ] - 2 * h[ lca(f, t) ]); return ans + 1; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> q; for(int i = 1, p; i < n; i++){ cin >> p, p--; g[p].push_back(i); } dfs(); while(q--){ for(int i = 0; i < 3; i++) cin >> ver[i], ver[i]--; cout << max({calc(ver[0], ver[1], ver[2]), calc(ver[1], ver[0], ver[2]), calc(ver[2], ver[1], ver[0])}) << '\n'; } return 0; }
832
E
Vasya and Shifts
Vasya has a set of $4n$ strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into $n$ groups of $4$ equal strings each. Vasya also has one special string $a$ of the same length, consisting of letters "a" only. Vasya wants to obtain from string $a$ some fixed string $b$, in order to do this, he can use the strings from his set in any order. When he uses some string $x$, each of the letters in string $a$ replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string $x$. Within this process the next letter in alphabet after "e" is "a". For example, if some letter in $a$ equals "b", and the letter on the same position in $x$ equals "c", then the letter in $a$ becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in $a$ equals "e", and on the same position in $x$ is "d", then the letter in $a$ becomes "c". For example, if the string $a$ equals "abcde", and string $x$ equals "baddc", then $a$ becomes "bbabb". A used string disappears, but Vasya can use equal strings several times. Vasya wants to know for $q$ given strings $b$, how many ways there are to obtain from the string $a$ string $b$ using the given set of $4n$ strings? Two ways are different if the number of strings used from some group of $4$ strings is different. Help Vasya compute the answers for these questions modulo $10^{9} + 7$.
The first thing to notice is that the problem can be reduced to a matrix form. To do this quite easily, we note that if we denote $x_{i}$ as the number of times we apply the $i$-th row, then we will get the matrix, we will have exactly $n$ columns ($x_{i}$) and $m$ rows. That is, $A_{ij}$ will match the $i$-th symbol in the $j$-th row. Now we get the usual system of linear equations. Note that we have a restriction on $x_{i}$, $\forall i:x_{i}\leq4$, that is, we are interested in the number of SLE solutions, modulo $5$. Then for each query it would be possible to find the number of solutions using the Gauss algorithm (0 or $5^{n - rk(A)}$), but this solution will take $O(n^{3} \cdot q)$ time, which does not fit under restrictions. One of the optimizations for improving the algorithm is to bring the matrix $A$ to a triangular matrix form (find the rank) and memorize the transformations. Then for each query string we could apply these transformations, then the algorithm will work $O(n^{3} + q \cdot n^{2})$, which is already past Time Limit.
[ "matrices" ]
2,600
#include <bits/stdc++.h> using namespace std; #define ll long long #define ABS(x) ((x) < 0 ? -(x) : (x)) const int N = 500, MODM = 1e9 + 7; int matr_divide[5][5]; ll bin_pow(ll a, ll b, ll pp) { if (b == 0) return 1; if (b == 1) return a % pp; if (b & 1) return a * bin_pow(a, b - 1, pp) % pp; ll x = bin_pow(a, b / 2, pp) % pp; return x * x % pp; } void ini() { for (int a = 0; a < 5; ++a) for (int b = 0; b < 5; ++b) { matr_divide[a][b] = a * bin_pow(b, 3, 5) % 5; } } ll get_independent(vector<vector<short int>> &matrix, int q = 0) { int n = matrix.size(); int m = matrix[0].size() - q; vector<int> where(m, -1); for (int col = 0, row = 0; row < n && col < m; ++col) { int cur = row; for (int i = row; i < n; ++i) if (matrix[i][col] > matrix[cur][col]) cur = i; if (!matrix[cur][col]) continue; for (int j = col; j < m + q; ++j) swap(matrix[row][j], matrix[cur][j]); where[col] = cur; for (int i = 0; i < n; ++i) { if (i != row) { ll tmp = matr_divide[matrix[i][col]][matrix[row][col]]; for (int j = col; j < m + q; ++j) { matrix[i][j] -= matrix[row][j] * tmp % 5; if (matrix[i][j] < 0) matrix[i][j] += 5; } } } ++row; } ll ans = 0; for (int i = 0; i < m; ++i) if (where[i] == -1) ++ans; return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ini(); int n, q, m; cin >> n >> m; vector<vector<short int>> mas; mas.resize(m); for (int i = 0; i < m; ++i) mas[i].assign(n, 0); for (int i = 0; i < n; ++i) { string s; cin >> s; for (int j = 0; j < s.size(); ++j) { mas[j][i] = (s[j] - 'a') % 5; } } cin >> q; for (int i = 0; i < m; ++i) { mas[i].resize(n + q); } // vector<vector<short int>> mm = {{2, 1, 3}, {0, 0, 0}, {1, 3, 3}, {1, 3, 2}, {3, 2, 1}, {1, 3, 1}}; for (int index = 0; index < q; ++index) { string query; cin >> query; vector<int> now; for (int j = 0; j < query.size(); ++j) { mas[j][n + index] = (query[j] - 'a') % 5; } } int ind_pow = get_independent(mas, q); ll ans = bin_pow(5, ind_pow, MODM); int max_i = -1; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mas[i][j]) max_i = max(max_i, i); for (int i = 0; i < q; ++i) { int ind_col = n + i; int last = -1; for (int j = 0; j < m; ++j) { if (mas[j][ind_col]) last = j; if (last > max_i) break; } if (last > max_i) cout << 0 << "\n"; else cout << ans << "\n"; } return 0; }
833
A
The Meaningless Game
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number $k$ is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by $k^{2}$, and the loser's score is multiplied by $k$. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all $n$ games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Prequisites: none (maybe binary search). Let $S$ denote the product of the set of numbers said by Slastyona, and $P$ denote the product of the set of numbers barked by Pushok (in case one of the sets is empty the corresponding product is assumed to be equal to one). Then, we can reformulate the problem in a following way: we need to find such $S$ and $P$ that the following holds: $\binom{S^{2}\cdot P=a}{P^{2}\cdot S=b}$ We can already see a slow way to solve the problem. It is based on assumption that if $a \le b$, then $S \le P$ and $S^{3} \le 10^{9}$, so we can just enumerate all possible values of $S$. Unfortunately, we have as much as $350000$ games. So we need to find a more efficient solution. Note that $ab = S^{3} \cdot P^{3}$, and $S\cdot P={\dot{\sqrt{a b}}}$ (let us denote the cubic root as $X$). We can then easily find the required values: $\begin{array}{c}{{\left\{S={\frac{a}{X}}}}\\ {{P={\frac{b}{X}}}}\end{array}\right.$ We only need to check whether $ab$ is a perfect cube and $\lambda{\sqrt{a b}}$ divides $a$ and $b$. Time complexity: $O(1)$ (or $O(log(ab))$ if binary search was used to find the cubic root).
[ "math", "number theory" ]
1,700
#include <cmath> #include <cstdio> using namespace std; typedef long long ll; const int MAXR = 1000005; ll cubic_root(ll x) { ll l = 0, r = MAXR; while (l != r) { ll m = (l + r + 1) / 2; if (m * m * m > x) r = m - 1; else l = m; } return l; } int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { ll a, b; scanf("%I64d %I64d", &a, &b); ll x = cubic_root(a * b); if (x * x * x != a * b) puts("No"); else if (a % x == 0 && b % x == 0) puts("Yes"); else puts("No"); } return 0; }
833
B
The Bakery
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery. Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more \textbf{distinct} cake types a box contains (let's denote this number as the value of the box), the higher price it has. She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of $n$ cakes the oven is going to bake today. Slastyona has to pack exactly $k$ boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one \textbf{right after another} (in other words, she has to put in a box a continuous segment of cakes). Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Prerequisites: dp + segment trees All authors' solutions are based on the following dp idea: let's calculate $dp(k, n)$ - the maximum cost we can obtain if we assign the first $n$ cakes to $k$ boxes. For $k = 1$ the answer is equal to the number of distinct values on a prefix. For $k > 1$ the answer can be deduced as follows (here $c(i, n)$ denotes the number of distinct elements in range $(i, n)$): $dp(k, n) = max_{1 \le i < n}dp(k - 1, i - 1) + c(i, n)$ There are two possible approaches. Solution I: Imagine we're trying to compute the $k$-th dp layer and our currect position is $i$, maintaining a max segment tree with the sum $dp(k - 1, j) + c(j + 1, i)$ in $j$-th cell where $0 \le j < i$. The answer for $dp(k, n)$ is just a prefix query. How do we move $i$ the right? Let's denote $i$-th cake type as $y$. Notice that the $i$ $ \rightarrow $ $i + 1$ transition increases the segment tree values for all cells $j$ such that there's no $y$ in range $[j + 1, i]$ by one (since we've added a new distinct element). More formal, we increase all $j$'s between the previous position of $y$ plus one (or the beginning of the array if we haven't marked $y$ before) to $i$. Hence we got a lazy update segment tree and a simple $prev[i]$ precalc. There's a single $O(\log(n))$ for both updating and computing a single $dp(k, n)$ and a total complexity of $O(n k\log(n))$. Solution II: Many tried this approach and failed. Albeit we didn't focus on cutting this solution much, it still required several optimizations to pass. Let's denote the leftmost $i$ such that $dp(k - 1, i)$ gives the optimal answer for $dp(n, k)$ as $opt(k, n)$. We claim that $opt(k, n) \le opt(k, n + 1))$ (this one is a left as an exercise to the reader). With with assumption it is the right time for applying divide & conquer dp optimization (here persistent segment tree is used for counting the number of distinct cakes in a range, which is a well-known application of it; the divide and conquer technique is described here, for example: codeforces.com/blog/entry/8219). There are $O(n\log(n))$ relaxes in a single dp layer, each of those is processed in $O(\log(n))$. With a total of $k$ layers we get the overall complexity of $O(n k\log^{2}(n))$.
[ "binary search", "data structures", "divide and conquer", "dp", "two pointers" ]
2,200
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #include <math.h> #include <queue> using namespace std; #define N 35005 #define M 55 #define F 200 mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define fornv(i, n) for (int i = n - 1; i >= 0; i--) #define pii pair<int, int> #define forlr(i, l, r) for (int i = l; i <= r; i++) #define forlrv(i, l, r) for (int i = r; i >= l; i--) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define mp make_pair typedef long long ll; typedef unsigned long long ull; const long double eps = 1e-9; const int inf = 2e9; const int mod = 1e9 + 7; const ll infinity = 2 * 1e18; #define p p2 #define endl '\n' int t[4 * N], d[4 * N], w[N]; int dp[M][N]; int n, k; void build(int k, int u, int l, int r) { if (l == r - 1) return void(t[u] = dp[k][l]); int m = (l + r) / 2; build(k, 2 * u + 1, l, m); build(k, 2 * u + 2, m, r); } void push(int u, int len) { if (!d[u]) return; t[u] += d[u]; if (len > 1) d[2 * u + 1] += d[u], d[2 * u + 2] += d[u]; d[u] = 0; } void update(int u, int l, int r, int L, int R) { push(u, r - l); if (l == L && r == R) { d[u]++; push(u, r - l); return; } int m = (l + r) / 2; if (L < m) update(2 * u + 1, l, m, L, min(m, R)); else push(2 * u + 1, m - l); if (R > m) update(2 * u + 2, m, r, max(L, m), R); else push(2 * u + 2, r - m); t[u] = max(t[2 * u + 1], t[2 * u + 2]); } int get(int u, int l, int r, int L, int R) { if (L >= R) return 0; push(u, r - l); if (l == L && r == R) return t[u]; int m = (l + r) / 2, ans = 0; if (L < m) ans = max(ans, get(2 * u + 1, l, m, L, min(m, R))); else push(2 * u + 1, m - l); if (R > m) ans = max(ans, get(2 * u + 2, m, r, max(L, m), R)); else push(2 * u + 2, r - m); return ans; } int p[N]; map<int, int> last; void solve(int k) { fill_n(t, 4 * N, 0), fill_n(d, 4 * N, 0); build(k - 1, 0, 0, n); forn(i, n) { if (p[i] < i) update(0, 0, n, p[i], i); dp[k][i] = max(dp[k - 1][i], get(0, 0, n, 0, i)); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; forn(i, n) cin >> w[i]; forn(i, n) { p[i] = -1; if (last.count(w[i])) p[i] = last[w[i]]; else p[i] = 0; last[w[i]] = i; } set<int> s; forn(i, n) { s.insert(w[i]); dp[1][i] = s.size(); } for (int i = 2; i <= k; i++) solve(i); cout << dp[k][n - 1] << endl; }
833
C
Ever-Hungry Krakozyabra
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner. Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail. For example, if Krakozyabra is to have the number $57040$ for dinner, its inedible tail would be the number $457$. Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from $L$ to $R$, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.
Prerequisites: Combinatorics or strong faith :) At first we might assume (without loss of generality) that both left and right bounds are strictly less than $10^{18}$ (otherwise we just append $1$ to the list of unedible tails) and hence consider only numbers with no more than 18 decimal digits. Notice that there are not than many numbers without leading zeros: they are no more than $\textstyle{\binom{18+9}{9}}$ (the number of solutions to $c_{1} + c_{2} + ... + c_{n} \le 18$, where $c_{i}$ - the number of $i$-s in a number). To be precise, there are only $4686824$ such numbers in range $1$ $ \rightarrow $ $10^{18}$. Thus we might simply brute all such numbers and for a fixed candidate (let's denote it as $A$), whether it is possible (using some additional zeros if neccessary) to form the number $A'$ from the range $[L, R]$. How do we check it rapidly? Let's represent $L$ and $R$ as vectors of length $n$ (we might add some leading zeros to $L$ if neccessary), and $A$ - as an array $num$ (with possible additional zeros). We will brute it in the following way: $go(pos, l_{flag}, r_{flag})$, which keeps out current position and indicates whether the currently obtained number is equal to the corresponding prefix of $L$ / $R$. Several cases to consider: If $(pos = n)$, we return true. If $(l_{flag} = 1)$ and $(r_{flag} = 1)$, we strictly follow the prefixes of $L$ and $R$. There are two deeper cases: If $L(pos) = R(pos)$, the only way out is to place $L(pos)$, decrease the number of corresponding digits in $num$ and proceed to $go(pos + 1, 1, 1)$. Else if $L(pos) < R(pos)$, we have to check if there's an element in $[L(pos) + 1, R(pos) - 1]$. It's obvious that the answer is true in this case (since after we get right between $L$ and $R$ we can assign the suffix whichever way we want). Otherwise we first consider the possibility of placing $L(pos)$ and proceeding to $go(pos + 1, 1, 0)$ or placing $R(pos)$ and proceeding to $go(pos + 1, 0, 1)$. If nothing returns true, the answer is false; If only left flag is active $(l_{flag} = 1)$, we need a random digit from the suffix $[L(pos) + 1, 9]$. If we find it - the answer is true. If no - we try $L(pos)$ and $go(pos + 1, 1, 0)$ or return false. A lone right flag is processed in a simular way with the only difference that we try the $[0, R(pos) - 1]$ prefix or $R(pos)$ and $go(pos + 1, 0, 1)$. At a first glance it seems that out bruteforce will end up being $O(2^{n})$. But an easy observation shows that there can be no more that two separate branches here. The total bruteforce complexity is $O(10 \cdot n)$. Complexity: $O\left(\!\,\!(stackrel{(K\setminus\emptyset)}{\mathfrak{g}})\cdot K\right)$, where $K$ stands for the maximum number length.
[ "brute force", "combinatorics", "greedy", "math" ]
2,700
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #include <math.h> #include <queue> using namespace std; #define N 200005 #define M 20 #define F 200 mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define fornv(i, n) for (int i = n - 1; i >= 0; i--) #define pii pair<int, int> #define forlr(i, l, r) for (int i = l; i <= r; i++) #define forlrv(i, l, r) for (int i = r; i >= l; i--) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define mp make_pair typedef long long ll; typedef unsigned long long ull; const long double eps = 1e-9; const int inf = 2e9; const int mod = 1e9 + 7; const ll infinity = 2 * 1e18; #define p p2 #define endl '\n' vector<int> L, R; int n; int ans = 0; int num[10]; int keep[10]; inline bool any(int l, int r) { if (l > r) return false; for (int i = l; i <= r; i++) if (num[i]) return true; return false; } bool dfs(int pos, bool lf, bool rf) { if (pos == n) return true; int l = L[pos], r = R[pos]; if (lf & rf) { if (l == r) { if (num[l]) { num[l]--; if (dfs(pos + 1, 1, 1)) return true; num[l]++; } return false; } if (any(l + 1, r - 1)) return true; if (num[l]) { num[l]--; if (dfs(pos + 1, 1, 0)) return true; num[l]++; } if (num[r]) { num[r]--; if (dfs(pos + 1, 0, 1)) return true; num[r]++; } return false; } else if (lf) { if (any(l + 1, 9)) return true; if (num[l]) { num[l]--; if (dfs(pos + 1, 1, 0)) return true; num[l]++; } return false; } else if (rf) { if (any(0, r - 1)) return true; if (num[r]) { num[r]--; if (dfs(pos + 1, 0, 1)) return true; num[r]++; } return false; } return false; } void go(int n, int sum) { if (n == 10) { memcpy(num, keep, sizeof keep); num[0] += sum; if (dfs(0, 1, 1)) ans++; return; } for (int i = 0; i <= sum; i++) { keep[n] = i; go(n + 1, sum - i); } } int main() { ll l, r; cin >> l >> r; if (l == r) { cout << 1; return 0; } ll sh_l = l, sh_r = r; for (; l; l /= 10) L.push_back(l % 10); for (; r; r /= 10) R.push_back(r % 10); n = R.size(); while (L.size() < n) L.push_back(0); reverse(L.begin(), L.end()); reverse(R.begin(), R.end()); go(1, n); cout << ans << endl; }
833
D
Red-Black Cobweb
Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb. The cobweb is a set of $n$ nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread connects a node to itself, and between any two nodes there is a unique sequence of threads connecting them. Slastyona decided to study some special qualities of the cobweb. She noticed that each of the threads has a value of clamminess $x$. However, Slastyona is mostly interested in jelliness of the cobweb. Consider those of the shortest paths between each pair of nodes on which the numbers of red and black threads differ at most twice. For each such path compute the product of the clamminess of threads on the path.The jelliness of the cobweb is the product of all obtained values among all paths. Those paths that differ by direction only are counted only once. Of course, this number can be huge, so Slastyona asks you to compute the jelliness of the given cobweb and print the answer modulo $10^{9} + 7$.
Prequisites: centroid decomposition, segment tree / BIT / treap, modulo division Analogically to the vast variety of problems where we are to find some information about all the paths of the tree at once, we can use centroid decomposition as a basis. Let us fix some centroid and some path consisting of $r$ red and $b$ black vertices (let us denote it as a pair $(r, b)$). For this path, we need to somehow obtain (and do it fast!) information about all augmenting paths - such pairs $(r', b')$ that $2 \cdot min(r + r', b + b') \ge max(r + r', b + b')$. Let us simplify a problem for a little while: let's assume we are only interested in finding such paths $(r', b')$ that $2 \cdot (r + r') \ge (b + b')$. If we rewrite the inequality as $(2 \cdot r - b) \ge (b' - 2 \cdot r')$, we can clearly see that the paths we are interested in comprise the suffix of some tree with nodes having indices $2 \cdot x - y$. Unfortunately, this bound is not enough. We need to discard all the paths that satisfy not only this condition, but also have a red part which is too long, i.e. those having $2 \cdot (b + b') < (r + r')$. With the same trick we the inequality turns into $2 \cdot b - r < r' - 2 \cdot b'$, describing some prefix of a $x - 2 \cdot y$ tree. We should maintain $size$ and $product$ of clamminesses for all subtrees. Then the problem of calculating the contribution of a fixed path reduces to quering these two trees. More precisely, for a $(r, b)$ path with clamminess $x$ looks as follows. Denote $suffix(2 \cdot r - b)$ as $(size, product)$ for the first tree, and $prefix(2 \cdot b - r)$ as the corresponding pair for the second one. Then the first pair gives us the positive contribution of ($product \cdot x^{size}$) whereas the second pair gives the same amount of negative contribution (in terms of the second tree this time). The only thing left is to divide them modulo $1e9 + 7$. We might get a little bit more tricky and use modulo givision only when we process all paths from this centroid; this will give us the total complexity of $O(n\log^{2}(n)+n\log(M))$, where $M = 1e9 + 7$.
[ "data structures", "divide and conquer", "implementation", "trees" ]
2,800
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #include <math.h> #include <queue> using namespace std; #define N 200005 #define M 20 #define F 200 mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define fornv(i, n) for (int i = n - 1; i >= 0; i--) #define pii pair<int, int> #define forlr(i, l, r) for (int i = l; i <= r; i++) #define forlrv(i, l, r) for (int i = r; i >= l; i--) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define mp make_pair typedef long long ll; typedef unsigned long long ull; const long double eps = 1e-9; const int inf = 2e9; const int mod = 1e9 + 7; const ll infinity = 2 * 1e18; #define p p2 #define endl '\n' int mul(int a, int b) { return (a * 1LL * b) % mod; } int mpow(int x, int p) { return (!p ? 1 : mul(mpow(mul(x, x), p / 2), (p & 1) ? x : 1)); } int divide(int a, int b) { return mul(a, mpow(b, mod - 2)); } class tree { private: struct node { node *l = nullptr, *r = nullptr; int y = gen(), size = 1, value, w, x, s = 1; node(int x, int w) : x(x), w(w), value(w) {} }; typedef node * treap; typedef pair<treap, treap> ptt; treap root = nullptr; pair<int, int> values(treap t) { if (!t) return mp(0, 1); return mp(t->size, t->value); } treap mend(treap t) { if (t) { pair<int, int> l_values = values(t->l), r_values = values(t->r); t->size = l_values.first + r_values.first + t->s; t->value = mul(mul(l_values.second, r_values.second), t->w); } return t; } ptt split(treap t, int x) // >= x goes to the right { if (!t) return mp(t, t); if (x <= t->x) { ptt p = split(t->l, x); t->l = p.second; return mp(p.first, mend(t)); } else { ptt p = split(t->r, x); t->r = p.first; return mp(mend(t), p.second); } } treap merge(treap u, treap v) { if (!u) return v; if (!v) return u; if (u->y > v->y) { u->r = merge(u->r, v); return mend(u); } else { v->l = merge(u, v->l); return mend(v); } } public: tree() {} void insert(int x, int w) { ptt p = split(root, x); ptt q = split(p.second, x + 1); if (!q.first) root = merge(merge(p.first, new node(x, w)), p.second); else { q.first->s++; q.first->w = mul(q.first->w, w); q.first = mend(q.first); root = merge(merge(p.first, q.first), q.second); } } pair<int, int> range(int x, bool flag) // 0 = [-inf, x), 1 = [x, +inf) { ptt p = split(root, x); pair<int, int> rv = values(flag ? p.second : p.first); root = merge(p.first, p.second); return rv; } void clear() { root = nullptr; } }; namespace cd { struct edge { int to, w; bool color; // 1 = black, 0 = white }; struct path { int product, w_count, b_count; }; ll ans = 1; vector<edge> g[N]; int n, lv[N]; void add_edge(int u, int v, int w, bool color) { g[u].push_back({ v, w, color }); g[v].push_back({ u, w, color }); } int dfs(int u, int s, int &center, int e = -1) { int sz = 1; for (auto v : g[u]) if (lv[v.to] == -1 && v.to != e) sz += dfs(v.to, s, center, u); if (center == -1 && (2 * sz >= s || e == -1)) center = u; return sz; } vector<path> data; void calc(int u, int w_count = 0, int b_count = 0, int product = 1, int e = -1) { data.push_back({ product, w_count, b_count }); for (auto v : g[u]) if (lv[v.to] == -1 && v.to != e) calc(v.to, w_count + !v.color, b_count + v.color, mul(product, v.w), u); } void cdc(int u, int s, int level = 0, int e = -1) { int center = -1; dfs(u, s, center); lv[center] = level; tree prefix = tree(), suffix = tree(); int pos = 1, neg = 1; for (auto v : g[center]) if (lv[v.to] == -1) { data.clear(); calc(v.to, !v.color, v.color, v.w); for (auto v : data) { // (size, value) pair<int, int> positive = suffix.range(v.b_count - 2 * v.w_count, true); pair<int, int> negative = prefix.range(v.w_count - 2 * v.b_count, false); // *= dp_positive * product ^ size_positive // /= dp_negative * product ^ size_negative // -> dp_positive / dp_negative * product ^ (size_positive - size_negative) //pair<int, int> combine = mp(positive.first - negative.first, divide(positive.second, negative.second)); pos = mul(pos, positive.second), neg = mul(neg, negative.second); ans = mul(ans, mpow(v.product, positive.first - negative.first)); if (min(v.w_count, v.b_count) * 2 >= max(v.w_count, v.b_count)) ans = mul(ans, v.product); } for (auto v : data) { suffix.insert(2 * v.w_count - v.b_count, v.product); prefix.insert(2 * v.b_count - v.w_count, v.product); } } ans = mul(ans, divide(pos, neg)); for (auto v : g[center]) if (lv[v.to] == -1) cdc(v.to, s / 2, level + 1, center); } ll run() { fill_n(lv, N, -1); cdc(1, n); return ans; } } int main() { scanf("%d", &cd::n); int u, v, w; int color; forn(i, cd::n - 1) { scanf("%d %d %d %d", &u, &v, &w, &color); cd::add_edge(u, v, w, color); } printf("%I64d\n", cd::run()); }
833
E
Caramel Clouds
It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has $m$ seedlings, and the $j$-th seedling needs at least $k_{j}$ minutes of sunlight to grow up. Most of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the $i$-th of which will appear at time moment (minute) $l_{i}$ and disappear at time moment $r_{i}$. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun. Slastyona wants to grow up her muffins as fast as possible. She has exactly $C$ candies, which is the main currency in Sweetland. One can dispel any cloud by paying $c_{i}$ candies. However, in order to comply with Sweetland's Department of Meteorology regulations, \textbf{one can't dispel more than two clouds}. Slastyona hasn't decided yet which of the $m$ seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently. The seedlings start to grow at time moment $0$.
Prequisites: scanline. The key idea is that only minutes which are covered by no more than two clouds can contribute to the answer. Let us demonstrate how to solve the problem for a fixed $k$ using scanline. Let's create $2 \cdot n$ events: for the start and the end of each cloud. We will then go through all the events in ascending order of their coordinates, maintaining the following values: the set of active clouds $open$; the count of sunny (from the beginning!) minutes $free$; the array $single(i)$, which denotes the number of minutes covered solely by cloud $i$; the variable $top$ - the largest number of sunny minutes we can obtain on a given prefix by deleting no more than two clouds; the sparse table $cross$, whose element $(a, b)$ holds the number of minutes of sunny minutes covered solely by $a$ and $b$; and finally, the array $opt(i)$ - the optimal number of sunny minutes we can obtain if we dispel $i$-th cloud as one of the selected ones. We will also construct a treap (or BIT/segment tree if we want to), where each leaf has the index in form of the pair $cost(i), i$, keeping best index relative to $single(i)$ in the subtree in each node. So, let us assume we are now considering some event with the coordinate $x$, which is going to add some segment with length $len$. If $open$ is empty, it's enough to just increase $free$ by $len$. If $open$ contains exactly two elements (let's denote them as $a$ and $b$), we need to increase $cross[a, b]$ by $len$ and try to update $opt(a)$ via using $b$ and $opt(b)$ via using $a$ if it's possible (i.e. if the sum of costs does not exceed the budget). The case when $open$ only one element is the most interesting. We have to try to increase both $single(a)$ and $opt(a)$ by len consequently. What clouds may optima have also updated for? Obviously, for every cloud which cost allows us to dispel it together the cloud $a$. But it's only necessary to update $opt$ only for cloud with maximal $single(x)$ (don't forget to delete $a$ from the tree) on range $[0..C - cost(a)]$. Why? We leave this as an excercise for the reader. After that, we will either need to remove the start of the cloud from $open$ if we are dealing with a closing event, or to put it into $open$ otherwise. Along with aforementioned operations we can also update the variable $top$. It's not that hard to observe that if $free + top \ge k$, the answer would be some point of the last segment: we can find it as $x - (free + top) - k$. It's also worth noting that if we are to order all the queries in the non-descending order, the answers would be ordered the same way. We can then process them in one go. Time complexity: $O(n\log(n)+m\log(m))$.
[ "data structures", "dp", "sortings" ]
3,400
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #include <math.h> #include <queue> using namespace std; #define N 300005 #define M 5000005 #define F 200 mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define fornv(i, n) for (int i = n - 1; i >= 0; i--) #define pii pair<int, int> #define forlr(i, l, r) for (int i = l; i <= r; i++) #define forlrv(i, l, r) for (int i = r; i >= l; i--) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define mp make_pair typedef long long ll; typedef unsigned long long ull; const long double eps = 1e-9; const int inf = 1e9; const int mod = 1e9 + 7; const ll infinity = 2 * 1e18; #define p p2 #define endl '\n' struct cloud { int l, r, c; }; cloud cl[N]; int n, C, m; struct event { int x, t, i; bool operator < (const event &other) { if (x != other.x) return x < other.x; if (t != other.t) return t < other.t; return i < other.i; } }; int single[N], opt[N]; map<int, int> cross[N]; class tree { private: struct node { node *l = nullptr, *r = nullptr; int y = gen(), dp = -1; pii x = mp(0, 0); node(pii x) : x(x), dp(x.second) {} }; typedef node * treap; typedef pair<treap, treap> ptt; treap root = nullptr; int choose(int u, int v) { if (u == -1) return v; if (v == -1) return u; return (single[u] > single[v]) ? u : v; } int dp(treap t) { return (t ? t->dp : -1); } treap mend(treap t) { if (!t) return t; t->dp = choose(t->x.second, choose(dp(t->l), dp(t->r))); return t; } ptt split(treap t, pii x) // >= x goes to the right { if (!t) return mp(t, t); if (x <= t->x) { ptt p = split(t->l, x); t->l = p.second; return mp(p.first, mend(t)); } else { ptt p = split(t->r, x); t->r = p.first; return mp(mend(t), p.second); } } treap merge(treap u, treap v) { if (!u) return v; if (!v) return u; if (u->y > v->y) { u->r = merge(u->r, v); return mend(u); } else { v->l = merge(u, v->l); return mend(v); } } public: tree() {} void insert(int i) { ptt p = split(root, mp(cl[i].c, i)); root = merge(merge(p.first, new node(mp(cl[i].c, i))), p.second); } void erase(int i) { ptt p = split(root, mp(cl[i].c, i)); ptt q = split(p.second, mp(cl[i].c, i + 1)); root = merge(p.first, q.second); } int go(int c) { ptt p = split(root, mp(c + 1, -1)); int ret = dp(p.first); root = merge(p.first, p.second); return ret; } }; pii q[N]; int ans[N]; void solve() { if (!n) { forn(i, m) ans[q[i].second] = q[i].first; return; } vector<event> e; forn(i, n) { auto &y = cl[i]; e.push_back({ y.l, 0, i }); e.push_back({ y.r, 1, i }); } sort(e.begin(), e.end()); int last = 0, free = 0, j = 0; int top = 0; set<int> open; tree root = tree(); for (auto v : e) { if (open.size() == 0) free += v.x - last; else if (open.size() == 1 && cl[*open.begin()].c <= C) { int a = *open.begin(); root.erase(a); single[a] += v.x - last; opt[a] += v.x - last; top = max(top, opt[a]); int chosen = root.go(C - cl[a].c); if (chosen != -1) { int u = single[a] + single[chosen] + (cross[a].count(chosen) ? cross[a][chosen] : 0); opt[a] = max(opt[a], u); top = max(top, opt[a]); } root.insert(a); } else if (open.size() == 2) { int a = *open.begin(), b = *open.rbegin(); if (cl[a].c + cl[b].c <= C) { cross[a][b] += v.x - last, cross[b][a] += v.x - last; opt[a] = max(opt[a], single[a] + single[b] + cross[a][b]); opt[b] = max(opt[b], single[a] + single[b] + cross[a][b]); top = max(top, max(opt[a], opt[b])); } } for (; j < m && top + free >= q[j].first; j++) ans[q[j].second] = (v.x - (top + free - q[j].first)); last = v.x; if (v.t) open.erase(v.i); else open.insert(v.i); } for (; j < m; j++) ans[q[j].second] = e.back().x - (top + free - q[j].first); } int main() { //ios_base::sync_with_stdio(0); //cin.tie(0); int k; scanf("%d %d", &n, &C); int l, r, c; forn(i, n) { scanf("%d %d %d", &l, &r, &c); cl[i] = { l, r, c }; } int y; scanf("%d", &m); forn(i, m) { scanf("%d", &y); q[i] = mp(y, i); } sort(q, q + m); solve(); forn(i, m) printf("%d\n", ans[i]); }
834
A
The Useless Toy
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one): After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in. Slastyona managed to have spinner rotating for exactly $n$ seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.
Prequisites: none. The sole fact that the spinner has four positions, which are repeated periodically, leads us to the following observations that are easily verifiable: first thing is that no matter what the direction was, when $k$ is even we're going to get the same ending position; secondly, if we replace $n$ by $n{\mathrm{~mod~}}4$, the resulting problem would have the same answer (basically we have removed full rotations of the spinner from consideration). Thus, if $n{\mathrm{~mod~}}2=0$, the answer is "undefined". Otherwise, we have to find the aforementioned remainder and find the direction of the spin, which is pretty straightforward. Time complexity: $O(1)$.
[ "implementation" ]
900
DIRS = ['v', '<', '^', '>'] a, b = map(DIRS.index, input().split()) n = int(input()) delta = (b - a + 4) % 4 if delta == 0 or delta == 2: print('undefined') elif delta == n % 4: print('cw') else: print('ccw')
834
B
The Festive Evening
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are $k$ such guards in the castle, so if there are more than $k$ opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than $k$ doors were opened.
Prerequisites: none. This problem is solved with two linear sweeps. In the first one, we determine the last position for each letter. In the second one, we just model the process: we mark the letter as active when we stumble upon it for the first time, and as inactive when we reach the last position for this letter. If there are more than $k$ letters active at some specific point of time, we output "YES". Otherwise, we output "NO". Time complexity: $O(n)$.
[ "data structures", "implementation" ]
1,100
#include <iostream> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; unordered_map<char, int> last_pos; unordered_set<char> active; int main() { int n, k; string s; cin >> n >> k >> s; for (int i = 0; i < n; i++) { last_pos[s[i]] = i; } for (int i = 0; i < n; i++) { active.insert(s[i]); if (active.size() > k) { cout << "YES" << endl; return 0; } if (last_pos[s[i]] == i) active.erase(s[i]); } cout << "NO" << endl; return 0; }
835
A
Key races
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of $s$ characters. The first participant types one character in $v_{1}$ milliseconds and has ping $t_{1}$ milliseconds. The second participant types one character in $v_{2}$ milliseconds and has ping $t_{2}$ milliseconds. If connection ping (delay) is $t$ milliseconds, the competition passes for a participant as follows: - Exactly after $t$ milliseconds after the start of the competition the participant receives the text to be entered. - Right after that he starts to type it. - Exactly $t$ milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw. Given the length of the text and the information about participants, determine the result of the game.
Information on the success of the first participant will come in $2 \cdot t_{1} + v_{1} \cdot s$ milliseconds, of the second participant - in $2 \cdot t_{2} + v_{2} \cdot s$ milliseconds. We need to compare these numbers and print the answer depending on the comparison result.
[ "math" ]
800
s, v1, v2, t1, t2 = map(int, input().split()) q1 = 2 * t1 + s * v1 q2 = 2 * t2 + s * v2 if q1 < q2: print('First') elif q1 > q2: print('Second') else: print('Friendship')
835
B
The number on the board
Some natural number was written on the board. Its sum of digits was not less than $k$. But you were distracted a bit, and someone changed this number to $n$, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers can differ.
Let's rephrase the problem a little. Suppose that we initially have a number $n$ and we need to make a number from it with the sum of digits at least $k$, changing as fewer digits as possible. Obviously, it is optimal to replace the digit with $9$. When we replace digit $d$ with $9$, we increase the sum by $9 - d$. It means it's optimal to replace the minimal digit. Let $cnt_{i}$ be the number of occurrences of the digit $i$ in $n$. While the sum is less than $k$ we will repeat this Find minimal $i$ that $cnt_{i} > 0$. Decrease $cnt_{i}$ by $1$. Increase the answer by $1$. Increase the sum by $9 - i$ It's not hard to prove, that algorithm makes as less replaces as possible. Alogithm works in $O(\log_{10}n)$ time and $O(1)$ additional memory.
[ "greedy" ]
1,100
k = int(input()) n = input() digits = [] for c in n: digits.append(ord(c) - ord('0')) digits.sort() cur = sum(digits) ans = 0 for d in digits: if cur < k: cur += 9 - d ans += 1 print(ans)
835
C
Star sky
The Cartesian coordinate system is set in the sky. There you can see $n$ stars, the $i$-th has coordinates ($x_{i}$, $y_{i}$), a maximum brightness $c$, equal for all stars, and an initial brightness $s_{i}$ ($0 ≤ s_{i} ≤ c$). Over time the stars twinkle. At moment $0$ the $i$-th star has brightness $s_{i}$. Let at moment $t$ some star has brightness $x$. Then at moment $(t + 1)$ this star will have brightness $x + 1$, if $x + 1 ≤ c$, and $0$, otherwise. You want to look at the sky $q$ times. In the $i$-th time you will look at the moment $t_{i}$ and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates ($x_{1i}$, $y_{1i}$) and the upper right — ($x_{2i}$, $y_{2i}$). For each view, you want to know the total brightness of the stars lying in the viewed rectangle. A star lies in a rectangle if it lies on its border or lies strictly inside it.
The brightness of the $i$-th star in moment $t$ is $(s_{i}+t_{i})~\mathrm{mod}~(c+1)$, where $\mathrm{mod}$ is modulo operator. Let's precalc for each $p = 0...C$, $x = 1...100$, $y = 1...100$ $cnt[p][x][y]$ - the number of stars with the initial brightness $p$ in the rectangle ($1$; $1$)-($x$; $y$). It is calculated like calcuating of partial sums: $cnt[p][x][y] = cnt[p][x - 1][y] + cnt[p][x][y - 1] - cnt[p][x - 1][y - 1] + (the number of stars in the point (x;y) with the initial brightness p)$. Then the total brightness of stars at the $i$-th view is $\sum_{p=0}^{c}\big((p+t_{i})\,\bmod\,\big(c+1\big)\big)\star\mathrm{amount}\big(p,x_{1i},y_{1i},x_{2i},y_{2i}\big)$, where $\operatorname{amount}(p,x_{1},y_{1},x_{2},y_{2})$ is the number of stars with the initial brightness $p$ in the given rectangle. This number can be calculated using array $\mathrm{cnt}$, using the inclusion-exclusion principle: $amount(p, x_{1}, y_{1}, x_{2}, y_{2}) = cnt[p][x_{2}][y_{2}] - cnt[p][x_{1} - 1][y_{2}] - cnt[p][x2][y_{1} - 1] + cnt[p][x_{1} - 1][y_{1} - 1]$. Let $X$ is the maximum coordinate. Time complexity: $O(n + qc + cX^{2})$. Memory complexity: $O(cX^{2})$.
[ "dp", "implementation" ]
1,600
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { new Solution().run(); } } class Solution { final int MAX_CORD = 100; Scanner in; BufferedWriter out; int n, q, c; int cnt[][][]; int get(int t, int x1, int y1, int x2, int y2) { int res = 0; for (int i = 0; i <= c; i++) { int brightness = (i + t) % (c + 1); int amount = cnt[i][x2][y2] - cnt[i][x1 - 1][y2] - cnt[i][x2][y1 - 1] + cnt[i][x1 - 1][y1 - 1]; res += amount * brightness; } return res; } void run() throws IOException { in = new Scanner(System.in); out = new BufferedWriter(new OutputStreamWriter(System.out)); n = in.nextInt(); q = in.nextInt(); c = in.nextInt(); cnt = new int[c + 1][MAX_CORD + 1][MAX_CORD + 1]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); int s = in.nextInt(); cnt[s][x][y]++; } for (int p = 0; p <= c; p++) { for (int i = 1; i <= MAX_CORD; i++) { for (int j = 1; j <= MAX_CORD; j++) { cnt[p][i][j] += cnt[p][i - 1][j] + cnt[p][i][j - 1] - cnt[p][i - 1][j - 1]; } } } for (int i = 0; i < q; i++) { int t = in.nextInt(); int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); out.write(get(t, x1, y1, x2, y2) + "\n"); } out.flush(); } }
835
D
Palindromic characteristics
Palindromic characteristics of string $s$ with length $|s|$ is a sequence of $|s|$ integers, where $k$-th number is the total number of non-empty substrings of $s$ which are $k$-palindromes. A string is $1$-palindrome if and only if it reads the same backward as forward. A string is $k$-palindrome ($k > 1$) if and only if: - Its left half equals to its right half. - Its left and right halfs are non-empty ($k - 1$)-palindromes. The left half of string $t$ is its prefix of length $⌊|t| / 2⌋$, and right half — the suffix of the same length. $⌊|t| / 2⌋$ denotes the length of string $t$ divided by $2$, rounded down. Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.
Observation I. If the string is $k$-palindrome, then it is ($k - 1$)-palindrome. Observation II. The string is $k$-palindrome if and only if the both following conditions are true: It is a palindrome. It's left half is non-empty ($k - 1$)-palindrome. Solution. Let's calculate the following dp. $dp[l][r]$ is the maximum $k$ such that the substring built from characters from $l$ to $r$ is $k$-palindrome. The dynamics is calculated in the order of non-decreasing of substring lengths. The values for $l = r$ and $l = r - 1$ are computed trivially. Let $r - l > 1$. Then, if $s[l] \neq s[r]$ or $dp[l + 1][r - 1] = 0$, $dp[l][r] = 0$. Otherwise $dp[l][r] = dp[l][m] + 1$, where $m=\left\lceil{\frac{l+r}{2}}\right\rceil-1$. When we have dp values, we can calculate $cnt[k]$ - the number of substrings, which dp value is $k$. Then the number of substrings that are $k$-palindromes is $a n s[k]=\sum_{i=k}^{\mathrm{sl}}c n t[i]$. The solution works in $O(|s|^{2})$ time and uses $O(|s|^{2})$ memory. Also, you could notice that the string can be no more than $\left|\log_{2}\left|s\right|$-palindrome, and solve the problem in $O(|s|^{2}\log|s|)$ time, reducing the memory usage to $O(|s|)$.
[ "brute force", "dp", "hashing", "strings" ]
1,900
s = input() n = len(s) dp = [[0 for i in range(n - le + 1)] for le in range(n + 1)] ans = [0 for i in range(n + 1)] for le in range(1, n + 1): for l in range(0, n - le + 1): r = l + le if s[l] != s[r - 1]: continue if le == 1: dp[1][l] = 1 ans[1] += 1 elif le == 2: ans[2] += 1 dp[2][l] = 2 elif dp[le - 2][l + 1]: v = 1 m = (l + r) // 2 st = m + 1 if le & 1 else m le2 = m - l q = dp[le2][l] if q: v = q + 1 ans[v] += 1 dp[le][l] = v for i in range(n - 1, 0, -1): ans[i] += ans[i + 1] print(*ans[1:])
835
E
The penguin's game
Pay attention: this problem is interactive. Penguin Xoriy came up with a new game recently. He has $n$ icicles numbered from $1$ to $n$. Each icicle has a temperature — an integer from $1$ to $10^{9}$. \textbf{Exactly two} of these icicles are special: their temperature is $y$, while a temperature of all the others is $x ≠ y$. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than \textbf{19} questions. You are to find the special icicles.
The solution can be separated into several parts. I. Finding the parity of the number of special icicles in the given subset using 1 question. Consider the following cases: Subset's size is even, the number of special icicles in it is even. Then the answer to such question is $0$. Subset's size is even, the number of special icicles in it is odd. Then the answer to such question is $x\oplus y$. Subset's size is odd, the number of special icicles in it is even. Then the answer to such question is $x$. Subset's size is odd, the number of special icicles in it is odd. Then the answer to such question is $y$. $x, y \ge 1$ and $x \neq y$, so the numbers $0$, $x$, $y$, $x\oplus y$ are pairwise distinct. Therefore, we can find the parity of the number of special icicles on the given subset using 1 question. II. The solution for the problem for the only one special icicle. Suppose we have $n$ icicles, and one of them is special. Then you can find it using $\lceil\log_{2}n\rceil$ questions. The algorithm is to use binary search over the minimum prefix that contains the special icicle. III. The solution of our problem. Each integer $n \le 1000$ can be written using no more than $\lfloor\log_{2}n\rfloor+1$ bits. Iterate over the bits from $0$ to $\lfloor\log_{2}n\rfloor$. Ask a question about the icicles that have $1$ in their numbers in the fixed bit. After that, we can determine if the numbers of the special icicles differ in this bit. Really, the bits differ if this subset's size is odd, and don't differ otherwise. Obviously, we will find at least one bit, where their numbers differ. Let $A$ is the subset of the icicles that have $1$ in this bit, and $B$ is the complement set. Let $m$ is the size of the smallest from these subsets. Then $m\leq{\frac{n}{2}}$. Let's solve the problem for the only one special icicle for the smallest of these subsets. Then it's easy to get the number of the other icicle: we know the number of the first icicle and we know in which bits the numbers differ and in which don't. This solution uses 19 question. It can be proven that in the given constraints you can't solve this problem in less than 19 questions.
[ "binary search", "constructive algorithms", "interactive" ]
2,400
#include <bits/stdc++.h> using namespace std; int n, x, y; int ask(const vector<int> &a) { if (a.empty()) { return 0; } cout << "? "; cout << a.size() << " "; for (int el : a) { cout << el << " "; } cout << endl; int res; cin >> res; return res; } int solve(const vector<int> &a) { int left = 0; int right = (int) a.size(); while (right - left > 1) { int mid = (left + right) / 2; vector<int> b; for (int i = left; i < mid; i++) { b.push_back(a[i]); } int cur = ask(b); if (cur == y || cur == (x ^ y)) { right = mid; } else { left = mid; } } return a[left]; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> x >> y; int diff = 0; int diff_bit = -1; for (int bit = 0; bit <= 9; bit++) { vector<int> a; for (int i = 1; i <= n; i++) { if (i & (1 << bit)) { a.push_back(i); } } int cur = ask(a); if (cur == y || cur == (x ^ y)) { diff |= (1 << bit); diff_bit = bit; } } assert(diff > 0 && diff_bit != -1); vector<int> a, b; for (int i = 1; i <= n; i++) { if (i & (1 << diff_bit)) { a.push_back(i); } else { b.push_back(i); } } if (a.size() > b.size()) { swap(a, b); } int pos1 = solve(a); int pos2 = pos1 ^ diff; if (pos1 > pos2) { swap(pos1, pos2); } cout << "! " << pos1 << " " << pos2 << endl; return 0; }
835
F
Roads in the Kingdom
In the Kingdom K., there are $n$ towns numbered with integers from $1$ to $n$. The towns are connected by $n$ bi-directional roads numbered with integers from $1$ to $n$. The $i$-th road connects the towns $u_{i}$ and $v_{i}$ and its length is $l_{i}$. There is no more than one road between two towns. Also, there are no roads that connect the towns with itself. Let's call the inconvenience of the roads the maximum of the shortest distances between all pairs of towns. Because of lack of money, it was decided to close down one of the roads so that after its removal it is still possible to reach any town from any other. You have to find the minimum possible inconvenience of the roads after closing down one of the roads.
Observation I. The given graph is a cycle with hanged trees. So, we can remove the edge only from the cycle, the resulting graph will be a tree. Observation II. We can minimize the distances only between the pairs of vertexes such that path between them goes through the cycle's edges. Let's say that these pairs are interesting. Solution. Let's find the cycle using dfs. Let its length be $k$. Let's number the vertices in it from $1$ to $k$ in round order. We will try to remove edges between $1$ and $2$, $2$ and $3$, ..., $1$ and $k$ and calculate the maximum distance between the interesting pairs. We need to pre-compute the following: $d_{i}$ - the maximum depth of the tree hanged to the $i$-th vertex of the cycle. $w_{i}$ - the length of the edge between the $i$-th vertex of the cycle and the next in the round order. $pref_diam_{i}$ - the maximum distance between the interesting pairs such that their vertexes are in the trees hanged to the vertexes $1$, $2$, ..., $i$ of the cycle. $suff_diam_{i}$ - the maximum distance between the interesting pairs such that their vertexes are in the trees hanged to the vertexes $i$, $i + 1$, ..., $k$ of the cycle. $pref_far_{i}$ - the maximum distance from the first vertex of the cycle to the vertexes that are in the trees hanged to the vertexes $1$, $2$, ..., $i$ of the cycle. $suff_far_{i}$ - the maximum distance from the first vertex of the cycle to the vertexes that are in the trees hanged to the vertexes $i$, $i + 1$, ..., $k$ of the cycle. Also $suff_diam_{k + 1} = suff_far_{k + 1} = - \infty $. These pre-computations can be done in linear time. If we delete the edge between the $i$-th vertex of the cycle and the next in the round order, then the maximum distance between the interesting pairs is $max(pref_far[i] + suff_far[i + 1], pref_diam[i], suff_diam[i + 1])$. After we found the optimal edge to remove, we remove it and find the diameter of the resulting tree. It can be done with 2 dfs'es. Let vertex $v$ be the farest from $1$. Let vertex $u$ be the farest from $v$. It's easy to prove that the path between $u$ and $v$ is the diameter. Time complexity: $O(n)$. Memory complexity: $O(n)$.
[ "dfs and similar", "dp", "graphs", "trees" ]
2,500
#include <iostream> #include <vector> #include <cassert> #include <algorithm> using namespace std; const int N = (int) 2e5 + 2; const long long INF = (long long) 1e18 + 123; int n; vector<pair<int, int>> g[N]; vector<int> cycle; int color[N]; bool vis[N]; long long depth[N], weight[N]; long long pref_diam[N], suff_diam[N]; long long pref_far[N], suff_far[N]; int dfs(int v, int from = -1) { static int cycle_start = -1; color[v] = 1; for (auto &e : g[v]) { int u = e.first; if (u == from) { continue; } if (color[u] == 1) { cycle.push_back(v); cycle_start = u; return 1; } else if (color[u] == 0) { int res = dfs(u, v); if (res == -1) { return -1; } if (res == 1) { cycle.push_back(v); if (v == cycle_start) { return -1; } return 1; } } } color[v] = 2; return 0; } pair<long long, int> farest(int v, pair<int, int> deny = {-1, -1}) { pair<long long, int> ans = {0, v}; vis[v] = 1; for (auto &e : g[v]) { int u = e.first; if (deny == make_pair(u, v) || deny == make_pair(v, u) || vis[u]) { continue; } auto tmp = farest(u, deny); tmp.first += e.second; ans = max(ans, tmp); } return ans; } long long get_diam(pair<int, int> deny) { fill(vis, vis + n + 1, 0); auto tmp = farest(1, deny); fill(vis, vis + n + 1, 0); return farest(tmp.second, deny).first; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { int u, v, l; scanf("%d%d%d", &u, &v, &l); g[u].push_back({v, l}); g[v].push_back({u, l}); } dfs(1); int k = (int) cycle.size(); assert(k >= 3); for (int v : cycle) { vis[v] = 1; } for (int i = 0; i < k; i++) { depth[i] = farest(cycle[i]).first; } cycle.push_back(cycle[0]); for (int i = 0; i < k; i++) { int v = cycle[i]; int u = cycle[i + 1]; for (auto &e : g[v]) { if (e.first == u) { weight[i] = e.second; } } } pref_diam[0] = depth[0]; pref_far[0] = depth[0]; long long cur_len = 0; long long cur_far = -INF; for (int i = 1; i < k; i++) { cur_len += weight[i - 1]; cur_far = max(cur_far, depth[i - 1]) + weight[i - 1]; assert(cur_far >= 0); pref_far[i] = max(pref_far[i - 1], cur_len + depth[i]); pref_diam[i] = max(pref_diam[i - 1], cur_far + depth[i]); } suff_diam[k] = -INF; suff_far[k] = -INF; cur_len = 0; cur_far = -INF; for (int i = k - 1; i > 0; i--) { cur_len += weight[i]; cur_far = max(cur_far, depth[i + 1]) + weight[i]; assert(cur_far >= 0); suff_far[i] = max(suff_far[i + 1], cur_len + depth[i]); suff_diam[i] = max(suff_diam[i + 1], cur_far + depth[i]); } pair<long long, int> ans = {INF, -1}; for (int i = 0; i < k; i++) { long long cur = max(pref_far[i] + suff_far[i + 1], max(pref_diam[i], suff_diam[i + 1])); if (cur < ans.first) { ans = {cur, i}; } } assert(ans.second != -1); cout << get_diam({cycle[ans.second], cycle[ans.second + 1]}) << "\n"; return 0; }
837
A
Text Volume
You are given a text of single-space separated words, consisting of small and capital Latin letters. Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text. Calculate the volume of the given text.
Maintain the amount of capital letters taken by going from left to right, make it zero when you meet space. Overall complexity: $O(n)$.
[ "implementation" ]
800
null
837
B
Flag of Berland
The flag of Berland is such rectangular field $n × m$ that satisfies following conditions: - Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. - Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has \textbf{exactly one color}. - Each color should be used in \textbf{exactly one stripe}. You are given a field $n × m$, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
There are lots of ways to check correctness. For example, you can keep boolean array with already used colors, check stripes naively and mark the color used if the stripe has single color. If all the colors are used in the end then the answer is YES. Overall complexity: $O(n \cdot m)$.
[ "brute force", "implementation" ]
1,600
null
837
C
Two Seals
One very important person has a piece of paper in the form of a rectangle $a × b$. Also, he has $n$ seals. Each seal leaves an impression on the paper in the form of a rectangle of the size $x_{i} × y_{i}$. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees). A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
If you can place two rectangles in some way (without rotations), then it's always possible to move one of them to the top left corner and stick the other either to the bottom of the first (and push it all the way to the left) or to the right of it (and push it all the way to the top). Now let's try all possible reorderings and rotations for every pair of seals. If there is at least one correct reordering then update the answer. Overall complexity: $O(8 \cdot n^{2})$.
[ "brute force", "implementation" ]
1,500
null
837
D
Round Subset
Let's call the roundness of the number the number of zeros to which it ends. You have an array of $n$ numbers. You need to choose a subset of exactly $k$ numbers so that the roundness of the product of the selected numbers will be maximum possible.
Let's use dynamic programming to solve this task. Obviously, the roundness of the number is determined by minimum of powers of 2 and 5 in the number. Let $pw5_{i}$ be the maximal power of 5 in the number and $pw2_{i}$ be the maximal power of 2. Let $dp[i][j][l]$ be the maximum amount of twos we can collect by checking first $i$ numbers, taking $j$ of them with total power of five equal to $l$. It is usually called "the knapsack problem". There are two types of transitions. You can either take current element or skip it: $dp[i + 1][j + 1][l + pw5_{i}] = max(dp[i + 1][j + 1][l + pw5_{i}], dp[i][j][l] + pw2_{i})$ $dp[i + 1][j][l] = max(dp[i + 1][j][l], dp[i][j][l])$ The answer will be maximum of $min(i, dp[n][k][i])$ for every $i$. Also keeping this many states can cause ML, the first dimension should be stored in two layers and recalced on the fly. Overall complexity: $O(n^{3}\cdot\log10^{18})$.
[ "dp", "math" ]
2,100
null
837
E
Vasya's Function
Vasya is studying number theory. He has denoted a function $f(a, b)$ such that: - $f(a, 0) = 0$; - $f(a, b) = 1 + f(a, b - gcd(a, b))$, where $gcd(a, b)$ is the greatest common divisor of $a$ and $b$. Vasya has two numbers $x$ and $y$, and he wants to calculate $f(x, y)$. He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.
One important fact is that when we subtract $gcd(x, y)$ from $y$, new $gcd(x, y)$ will be divisible by old $gcd(x, y)$. And, of course, $x$ is always divisible by $gcd(x, y)$. Let's factorize $x$. Consider the moment when $gcd(x, y)$ changes. If we denote old value of $gcd(x, y)$ by $g$, the new value of $gcd(x, y)$ will be divisible by some $k \cdot g$, where $k$ is a prime divisor of $x$. Let's check all prime divisors of $x$ and for each of these divisors find the number of times we need to subtract $g$ from $y$ to get $gcd(x, y)$ divisible by $k \cdot g$; that is just $\frac{y-|\frac{r_{0}}{g}\rangle k\;g}$ (don't forget that $x$ also has to be divisible by $k \cdot g$). Among all prime divisors of $x$ pick one with the minimum required number of operations (let this number of operations be $m$), add $m$ to answer, subtract $m \cdot g$ from $y$ and repeat the process.
[ "binary search", "implementation", "math" ]
2,100
null
837
F
Prefix Sums
Consider the function $p(x)$, where $x$ is an array of $m$ integers, which returns an array $y$ consisting of $m + 1$ integers such that $y_{i}$ is equal to the sum of first $i$ elements of array $x$ ($0 ≤ i ≤ m$). You have an infinite sequence of arrays $A^{0}, A^{1}, A^{2}...$, where $A^{0}$ is given in the input, and for each $i ≥ 1$ $A^{i} = p(A^{i - 1})$. Also you have a positive integer $k$. You have to find minimum possible $i$ such that $A^{i}$ contains a number which is larger or equal than $k$.
Let's delete all zeroes from the beginning of the array; they won't affect the answer. Also we will return an array of $m$ elements when calculating prefix sums (sum of zero elements becomes a zero in the beginning of the array, and so has to be removed). If the size of array is at least $10$, then we will get $k$ after calculating only a few prefix sums, so we can use simple iteration. So now we have to obtain the solution in case array has less than $10$ elements. If we remove zeroes from the beginning of each array, then $p(A) = A \cdot T$, where $T$ is a matrix $m \times m$, $T_{i, j} = 1$ if $i \le j$, otherwise $T_{i, j} = 0$. Then we can use matrix exponentiation to check whether $A^{i}$ contains a number which is equal to or greater than $k$, and we can use binary search to find the answer. To avoid overflows, each time we get a number greater than $k$, we can set it to $k$.
[ "binary search", "brute force", "combinatorics", "math", "matrices" ]
2,400
null
837
G
Functions On The Segments
You have an array $f$ of $n$ functions.The function $f_{i}(x)$ ($1 ≤ i ≤ n$) is characterized by parameters: $x_{1}, x_{2}, y_{1}, a, b, y_{2}$ and take values: - $y_{1}$, if $x ≤ x_{1}$. - $a·x + b$, if $x_{1} < x ≤ x_{2}$. - $y_{2}$, if $x > x_{2}$. There are $m$ queries. Each query is determined by numbers $l$, $r$ and $x$. For a query with number $i$ ($1 ≤ i ≤ m$), you need to calculate the sum of all $f_{j}(x_{i})$ where $l ≤ j ≤ r$. The value of $x_{i}$ is calculated as follows: $x_{i} = (x + last)$ mod $10^{9}$, where $last$ is the answer to the query with number $i - 1$. The value of $last$ equals $0$ if $i = 1$.
Let's build a data structure that allows us to find sum of functions on some prefix. The answer to the query can be obviously obtained using two answers on prefixes. We will use some persistent data structure that handles prefix sum queries - persistent segment tree, for example. We will actually use two different structures: let the sum of functions in some point $x_{0}$ be $x_{0} \cdot k + m$; one structure will allow us to find $k$, and another one will allow us to find $m$. Obviously, for prefix of length $0$ both $k$ and $m$ are equal to $0$. Then when we advance from prefix of length $i$ to prefix of length $i + 1$, we do the following: in the structure that handles $k$ we add $k_{i}$ in position $x_{i, 1} + 1$ and add $( - k_{i})$ in position $x_{i, 2} + 1$, so it is added only on segment $[x_{1} + 1, x_{2}]$. The same approach can be used to find $m$: add $y_{i, 1}$ in position $0$, add $m_{i} - y_{i, 1}$ in position $x_{i, 1} + 1$ and add $y_{i, 2} - m_{i}$ in position $x_{i, 2} + 1$. And to get the value in point $x_{0}$ on some prefix, we just make a prefix sum query to the corresponding structure.
[ "data structures" ]
2,500
null
838
A
Binary Blocks
You are given an image, that can be represented with a $2$-d $n$ by $m$ grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer $k > 1$ and split the image into $k$ by $k$ blocks. If $n$ and $m$ are not divisible by $k$, the image is padded with only zeros on the right and bottom so that they are divisible by $k$. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some $k$. More specifically, the steps are to first choose $k$, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this $k$. The image must be compressible in that state.
Let's define function $onesInRect(sx, sy, ex, ey)$ as number of ones in rectangle with top-left $(sx, sy)$ and down-right $(ex - 1, ey - 1)$ (0-based). Let $ps_{i, j}$ the number of ones in rectangle with top-left $(0, 0)$ and down-right $(i - 1, j - 1)$ (0-based). $ps_{i, j} = ps_{i - 1, j} + ps_{i, j - 1} - ps_{i - 1, j - 1}$ $onesInRect(sx, sy, ex, ey) = ps_{ex, ey} - ps_{sx, ey} - ps_{ex, sy} + ps_{sx, sy}$ Let $Cost(k)$ the answer if we compress the image with $k$. Let's find $Cost(k)$. int ans = 0; for(int i = k; i < n + k; i++) for(int j = k; j < m + k; j++) ans += min(onesInRect(i - k, j - k, i, j), k * k - onesInRect(i - k, j - k, i, j)); Time complexity of $Cost(k)$ is $O({\frac{\mu m}{k^{2}}})$. Now the answer is $min_{k = 2}^{max(n, m)}Cost(k)$. Overall time complexity is $O(n\cdot m)$.
[ "brute force" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() const int maxn = 2505; int pr[maxn][maxn]; int n, m; int cost(int x1, int y1, int x2, int y2) { if (x1 >= n || y1 >= m) return 0; int s = (x2 - x1) * (y2 - y1); x2 = min(x2, n); y2 = min(y2, m); int ones = pr[x2][y2] + pr[x1][y1] - pr[x2][y1] - pr[x1][y2]; return min(ones, s - ones); } int cost(int k) { int res = 0; for (int i = 0; i < n; i += k) for (int j = 0; j < m; j += k) { res += cost(i, j, i + k, j + k); } return res; } signed main() { #ifdef LOCAL assert(freopen("b.in", "r", stdin)); #endif cin >> n >> m; vector<string> s(n); forn (i, n) cin >> s[i]; forn (i, n) forn (j, m) pr[i + 1][j + 1] = pr[i][j + 1] + pr[i + 1][j] - pr[i][j] + (s[i][j] == '1'); int res = n * m; for (int k = 2; k <= max(n, m); ++k) { // cerr << "cost " << k << ' ' << cost(k) << endl; res = min(res, cost(k)); } cout << res << endl; }
838
B
Diverging Directions
You are given a directed weighted graph with $n$ nodes and $2n - 2$ edges. The nodes are labeled from $1$ to $n$, while the edges are labeled from $1$ to $2n - 2$. The graph's edges can be split into two parts. - The first $n - 1$ edges will form a rooted spanning tree, with node $1$ as the root. All these edges will point away from the root. - The last $n - 1$ edges will be from node $i$ to node $1$, for all $2 ≤ i ≤ n$. You are given $q$ queries. There are two types of queries - $1 i w$: Change the weight of the $i$-th edge to $w$ - $2 u v$: Print the length of the shortest path between nodes $u$ to $v$ Given these queries, print the shortest path lengths.
For each second type of query, there are two options: $u$ is an ancestor of $v$. $u$ isn't an ancestor of $v$.Let's define distance $v$ from root be $disFromRoot_{v}$. Answer of the first type of second query is obviously $disFromRoot_{v} - disFromRoot_{u}$. Let's define minimum possible distance $v$ from some node in this subtree of v + the distance from this node to root be $minSubTreeDis_{v}$. Answer of the second type of the second query is obviously $minSubTreeDis_{u} + disFromRoot_{v}$. Now, let's see how to find $disFromRoot_{v}$. For each vertex like $v$, let the weight of edge from its parent to it be $w$, you should add $w$ to all of the subtree of $v$. Use segment tree with range updates and single element queries, sort vertices in dfs order, add $w$ to $[startingTime_{v}, finishingTime_{v})$. Now $disFromRoot_{v} = get(startingTime_{v})$. We can handle update queries (first type) easily, just change the weight and update the segment tree again. Now, let's see how to find $minSubTreeDis_{v}$. Like above use segment tree with lazy propagation and minimum query.
[ "data structures", "dfs and similar", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() int n; const int maxn = 200200; ll wup[maxn]; ll wroot[maxn]; int eid[maxn * 2]; vector<int> g[maxn]; const int base = 1 << 18; ll t[base * 2]; ll upd[base * 2]; int in[maxn]; int out[maxn]; int timer; void push(int v) { t[v * 2] += upd[v]; upd[v * 2] += upd[v]; t[v * 2 + 1] += upd[v]; upd[v * 2 + 1] += upd[v]; upd[v] = 0; } void add(int l, int r, int delta, int v = 1, int cl = 0, int cr = base) { if (l <= cl && cr <= r) { t[v] += delta; upd[v] += delta; return; } if (r <= cl || cr <= l) return; push(v); int cc = (cl + cr) / 2; add(l, r, delta, v * 2, cl, cc); add(l, r, delta, v * 2 + 1, cc, cr); t[v] = min(t[v * 2], t[v * 2 + 1]); } ll get(int l, int r, int v = 1, int cl = 0, int cr = base) { if (l <= cl && cr <= r) return t[v]; if (r <= cl || cr <= l) return 1e18; push(v); int cc = (cl + cr) / 2; return min(get(l, r, v * 2, cl, cc), get(l, r, v * 2 + 1, cc, cr)); } void pre(int u, ll h = 0) { in[u] = timer++; t[in[u] + base] = h + wroot[u]; for (int v: g[u]) pre(v, h + wup[v]); out[u] = timer; } bool isPrev(int u, int v) { return in[u] <= in[v] && out[v] <= out[u]; } ll pathUp(int u) { return get(in[u], in[u] + 1) - wroot[u]; } signed main() { #ifdef LOCAL assert(freopen("d.in", "r", stdin)); #endif int q; scanf("%d%d", &n, &q); forn (i, 2 * (n - 1)) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u, --v; if (i < n - 1) { g[u].push_back(v); wup[v] = w; eid[i] = v; } else { wroot[u] = w; eid[i] = u; } } pre(0); for (int i = base - 1; i > 0; --i) t[i] = min(t[i * 2], t[i * 2 + 1]); forn (i, q) { int t, a, b; scanf("%d%d%d", &t, &a, &b); if (t == 1) { --a; int u = eid[a]; if (a < n - 1) { // cerr << "tree "; add(in[u], out[u], b - wup[u]); wup[u] = b; } else { // cerr << "root "; add(in[u], in[u] + 1, b - wroot[u]); wroot[u] = b; } } else { --a, --b; if (isPrev(a, b)) { // cerr << "prev "; cout << pathUp(b) - pathUp(a) << ' '; } else { // cerr << "huev "; cout << get(in[a], out[a]) - pathUp(a) + pathUp(b) << ' '; } } } }
838
C
Future Failure
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists $n$ characters, each of which is one of the first $k$ letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game. Given $n, k, p$, find the number of words with exactly $n$ characters consisting of the first $k$ letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number $p$.
Let the frequencies of the characters be $a_{1}, a_{2}, ..., a_{k}$. Alice loses if and only if $\left({}_{a_{1},a_{2},\ldots,a_{k}}\right)$ is odd and $n$ is even. So, if $n$ is odd, answer is $k^{n}$. Otherwise, we have to count number of $a_{1}, a_{2}, ..., a_{k}$ such that $a_{1} + a_{2} + ... + a_{k} = n$ and $\frac{n}{a_{1}!a_{2}!\cdots a_{k}!}$ is odd. Let the number of 1's in expansion of $x$ be $bp(x)$, the greatest power of $2$ in $x!$ is $x - bp(x)$ (More information). Now we want to count number of $a_{1}, a_{2}, ..., a_{k}$ such that $a_{1} + a_{2} + ... + a_{k} = n$ and $\begin{array}{c}{{a_{1}-b p(a_{1})+a_{2}-b p(a_{k})+\cdot\cdot\cdot\cdot+a_{k}-b p(a_{k})\,=\,n-b p(n)\,\Rightarrow\,b p(a_{1})+}}\\ {{b p(a_{2})+\cdot\cdot\cdot+b p(a_{k})=b p(n)}}\end{array}$. By Lucas's theorem, this is equivalent to $a_{1} + a_{2} + ... + a_{k} = a_{1}|a_{2}|... |a_{k}$. Let's define $dp_{i, mask}$ be the number of ways to choose $a_{1}, a_{2}, ..., a_{i}$ such that $\textstyle\sum a_{i}=a_{1}|a_{2}|\cdot\cdot\cdot|a_{i}=m a s k$. Then, $dp_{i}$ can be computed with time complexity $O(3^{\log_{2}^{n}}))$. For instance, the solutions is something like $d p_{i,m a s k}=\sum\textstyle{\frac{1}{x^{i}}}\cdot d p_{i-1,m a s k e j\delta a}$ for $x$ as a subset of $mask$ (and then after, multiply $dp_{k, mask}$ by $mask!$). We can use the convolution to multiply $\left[\frac{1}{0!},\,\frac{1}{1!},\,\frac{1}{2!},\,\frac{1}{3!},\,\ddots\,*\right]$ and $dp_{i - 1}$ to find $dp_{i}$ (More information). Time complexity: $O(n\cdot\log^{k}{.}(\log^{n})^{2})$.
[ "dp", "games" ]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() int mod; void udd(int &a, int b) { a += b; if (a >= mod) a -= mod; } void uub(int &a, int b) { udd(a, mod - b); } int add(int a, int b) { a += b; if (a >= mod) a -= mod; return a; } int mul(ll a, ll b) { return a * b % mod; } int bin(int a, int deg) { int r = 1; while (deg) { if (deg & 1) r = mul(r, a); deg >>= 1; a = mul(a, a); } return r; } int inv(int a) { assert(a); return bin(a, mod - 2); } const int LG = 19; const int B = 1 << LG; const int maxk = 30; int fact[B]; int ifact[B]; int n, lg; int a[B][LG]; int res[B]; int vec[LG]; int ways[LG]; int nways[LG]; void conv() { forn (bit, lg + 1) forn (i, n + 1) { if (i & (1 << bit)) { forn (j, lg + 1) udd(a[i][j], a[i ^ (1 << bit)][j]); } } } void iconv() { forn (bit, lg + 1) forn (i, n + 1) { if (i & (1 << bit)) { uub(res[i], res[i ^ (1 << bit)]); } } } void mul(int n, int* a, int* b) { forn (i, n) { nways[i] = 0; forn (j, i + 1) udd(nways[i], mul(a[j], b[i - j])); } } signed main() { #ifdef LOCAL assert(freopen("f.in", "r", stdin)); #endif int k; cin >> n >> k >> mod; int all = bin(k, n); if (n % 2) { cout << all << endl; return 0; } lg = 1; while ((1 << lg) <= n) ++lg; forn (i, n + 1) fact[i] = i ? mul(i, fact[i - 1]) : 1; for (int i = n; i >= 0; --i) ifact[i] = i == n ? inv(fact[i]) : mul(ifact[i + 1], i + 1); forn (i, n + 1) a[i][__builtin_popcount(i)] = ifact[i]; conv(); int need = __builtin_popcount(n); forn (x, n + 1) { if ((x & n) != x) continue; forn (i, lg + 1) { vec[i] = a[x][i]; ways[i] = i == 0; } int kk = k; while (kk) { if (kk & 1) { mul(lg + 1, ways, vec); memcpy(ways, nways, sizeof(nways)); } kk >>= 1; mul(lg + 1, vec, vec); memcpy(vec, nways, sizeof(nways)); } res[x] = ways[need]; } iconv(); int ans = all; uub(ans, mul(res[n], fact[n])); cout << ans << endl; }
838
D
Airplane Arrangements
There is an airplane which has $n$ rows from front to back. There will be $m$ people boarding this airplane. This airplane has an entrance at the very front and very back of the plane. Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person $1$. Each person can independently choose either the front entrance or back entrance to enter the plane. When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry. Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo $10^{9} + 7$.
Consider adding an extra seat, and the plane is now circular. Now the number of ways such that $n + 1$-th seat becomes empty is the answer. For each seat there is $\frac{(2\cdot(n+1))^{2m}\cdot(n+1\!-\!m)}{n\!+\!1}$
[ "math", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() const int mod = 1e9 + 7; void udd(int &a, int b) { a += b; if (a >= mod) a -= mod; } int mul(ll a, ll b) { return a * b % mod; } int bin(int a, int deg) { int r = 1; while (deg) { if (deg & 1) r = mul(r, a); deg >>= 1; a = mul(a, a); } return r; } int inv(int a) { assert(a); return bin(a, mod - 2); } signed main() { #ifdef LOCAL assert(freopen("a.in", "r", stdin)); #endif int n, m; cin >> n >> m; int res = bin(mul(2, n + 1), m); res = mul(res, n - m + 1); res = mul(res, inv(n + 1)); cout << res << endl; }
838
E
Convex Countour
You are given an strictly convex polygon with $n$ vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once. More specifically your path can be represented as some sequence of distinct polygon vertices. Your path is the straight line segments between adjacent vertices in order. These segments are not allowed to touch or intersect each other except at the vertices in your sequence. Given the polygon, print the maximum length non-intersecting path that visits each point at most once.
Let $dp_{i, j}$ be the longest path given that we've included segment $i, j$ in our solution, and we are only considering points to the right of ray $i, j$ (so $dp_{i, j}$ and $dp_{j, i}$ may be different). This leads to an $O(n^{3})$ solution. The optimal solution will pass from all of the points, so let's define $dp_{i, j, 0}$ the best path in ray $i, j$ such that it has an end point in $i$ and $dp_{i, j, 1}$ the best path in ray $i, j$ such that it has an end point in $j$. Now the transitions are easy, take a loop on j - i, when reached state $i, j, k$, $d p_{i-1{\mathrm{~mod~}}n_{3},0^{\prime}}>d p_{i,j,0}+d i s(i-1\mathrm{~mod~}n,i)$ $d p_{j+1}\,\,{\mathrm{mod}}\,\,{n.}_{i,1}{\ !}\qquad\qquad d p_{i,j,0}+d i s(j+1\quad{\mathrm{mod}}\,\,{n,i})$ $d p_{i-1{\mathrm{~mod~}}n_{3},1}\ref{'}^{?}>d p_{i,j,0}+d i s(i-1\mod n,i)$ $d p_{j+1}\,\,{\mathrm{mod}}\,\,{n.}_{i,0}{\ !}\,>d p_{i,j,0}+d i s(j+1)\,\,{\mathrm{mod}}\,\,{n},\,i)$ ($x? > y$ stands for $x = max(x, y)$).
[ "dp" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() struct pt { ld x, y; pt operator-(const pt &p) const { return pt{x - p.x, y - p.y}; } ld abs() const { return hypotl(x, y); } }; const int maxn = 2505; pt p[maxn]; ld d[maxn][maxn][2]; ld dist[maxn][maxn]; void uax(ld &a, ld b) { a = max(a, b); } signed main() { #ifdef LOCAL assert(freopen("c.in", "r", stdin)); #endif int n; cin >> n; forn (i, n) { cin >> p[i].x >> p[i].y; } forn (i, n) forn (j, n) { dist[i][j] = (p[i] - p[j]).abs(); forn (k, 2) d[i][j][k] = -1e18; } forn (i, n) d[i][i][0] = d[i][i][1] = 0; forn (len, n - 1) { forn (i, n) { int j = (i + len) % n; int ni = (i + n - 1) % n; int nj = (j + 1) % n; uax(d[ni][j][0], d[i][j][0] + dist[ni][i]); uax(d[nj][i][1], d[i][j][0] + dist[nj][i]); j = (i + n - len) % n; ni = (i + 1) % n; nj = (j + n - 1) % n; uax(d[ni][j][1], d[i][j][1] + dist[ni][i]); uax(d[nj][i][0], d[i][j][1] + dist[nj][i]); } } ld res = 0; forn (i, n) forn (j, n) forn (k, 2) uax(res, d[i][j][k]); cout << fixed; cout.precision(10); cout << res; }
838
F
Expected Earnings
You are playing a game with a bag of red and black balls. Initially, you are told that the bag has $n$ balls total. In addition, you are also told that the bag has probability $p_{i} / 10^{6}$ of containing exactly $i$ red balls. You now would like to buy balls from this bag. You really like the color red, so red balls are worth a unit of $1$, while black balls are worth nothing. To buy a ball, if there are still balls in the bag, you pay a cost $c$ with $0 ≤ c ≤ 1$, and draw a ball randomly from the bag. You can choose to stop buying at any point (and you can even choose to not buy anything at all). Given that you buy optimally to maximize the expected profit (i.e. # red balls - cost needed to obtain them), print the maximum expected profit.
We want to compute $dp_{i, j}$: expected value given we have seen $i$ red balls and $j$ black balls. Final answer is $dp_{0, 0}$. Now, to compute $dp_{i, j}$, we either take a ball or don't. Let $p_{i, j}$ be the probability that after we have seen $i$ red balls and $j$ black balls the next ball is red. Then, $dp_{i, j} = max(0, - c + p_{i, j} \cdot (dp_{i + 1, j} + 1) + (1 - p_{i, j}) \cdot (dp_{i, j + 1}))$. To compute $p_{i, j}$, we can compute $\sum_{k=i}^{n}{\frac{p({\mathrm{there~are~}}k{\mathrm{~red~balls~lseen~}}i{\mathrm{~seen~}}i{\mathrm{~red~badis~and~}}j{\mathrm{~black~balls}})\cdot(k-i)}{(n-i-i)}}$. By Bayes' theorem, ${p({\mathrm{here~are~}}k{\mathrm{~red~balk~ts~lank~}})}={\frac{a-m+b a}{m}}{\frac{\langle{\mathrm{ha}}\rangle\cdot{\mathrm{a}}\ |s\ |s\ |s\ |s\ |s\ |s\ |s\ |s\ |s\ |s\ |s\rangle}{\langle{\frac{d-a-b a^{\mathrm{fac}}}{m}}\langle{\frac{d-a^{\mathrm{fac}}}{d t}}\langle{\frac{d^{\mathrm{hadjs}}}{d t}}\rangle}}$ This gives an $O(n^{3})$ solution. To speed this up to $O(n^{2})\,$, let's figure out how to compute $p_{i, j}$ faster. Let's suppose that $i + j + 1 = n$. Then, it's easy, either $k = i$ or $k = i + 1$, so we can compute this in constant time. Now, suppose $i + j + 1 < n$. Let's throw out some balls at random without looking at them, and figure out new probabilities that there are $k$ red balls within the bag. You can see the code for more details on how to compute this new distribution. Codes here. P.S. Please notify me if there are any problems.
[]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() ld fact[100100]; const int maxn = 10005; ld d[2][maxn]; ld p[2][maxn]; signed main() { #ifdef LOCAL assert(freopen("e.in", "r", stdin)); #endif forn (i, 100100) fact[i] = i ? fact[i - 1] * i : 1; int q = 0; int N; ld C; cin >> N >> C; forn (i, N + 1) { cin >> p[q][i]; p[q][i] *= 1e-6; d[q][i] = i; } C *= 1e-6; for (int n = N - 1; n >= 0; --n, q ^= 1) { forn (w, n + 1) { p[q ^ 1][w] = p[q][w + 1] * (w + 1) / (n + 1) + p[q][w] * (n + 1 - w) / (n + 1); ld pr1 = p[q][w + 1] * (w + 1) / (n + 1); ld pr0 = p[q][w] * (n + 1 - w) / (n + 1); if (pr0 + pr1 == 0) continue; ld pr = pr1 / (pr0 + pr1); ld cur = pr * d[q][w + 1] + (1 - pr) * d[q][w] - C; d[q ^ 1][w] = max<ld>(w, cur); } } cout << fixed; cout.precision(10); cout << d[q][0] << endl; }
839
A
Arya and Bran
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have $0$ Candies. There are $n$ days, at the $i$-th day, Arya finds $a_{i}$ candies in a box, that is given by the Many-Faced God. Every day she can give Bran \textbf{at most} $8$ of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later. Your task is to find the minimum number of days Arya needs to give Bran $k$ candies \textbf{before} the end of the $n$-th day. Formally, you need to output the minimum day index to the end of which $k$ candies will be given out (the days are indexed from 1 to $n$). Print -1 if she can't give him $k$ candies during $n$ given days.
Let $t$ be number of her candies. At $i$-th day , we increase $t$ by $a_{i}$ ,then we give Bran $min(8, t)$ . So we decrease $k$ from this value. We will print the answer once $k$ becomes smaller or equal to $0$ . Or we will print $- 1$ if it does'n happen after $n$ days.
[ "implementation" ]
900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e2 + 17; int n, k, cur, ans; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; while(n--){ int x; cin >> x; cur += x; int r = min(8, cur); cur -= r; k -= r; ans++; if(k <= 0) break; } if(k > 0) cout << -1 << '\n'; else cout << ans << '\n'; return 0; }
839
B
Game of the Rows
Daenerys Targaryen has an army consisting of $k$ groups of soldiers, the $i$-th group contains $a_{i}$ soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has $n$ rows, each of them has $8$ seats. We call two seats neighbor, if they are in the same row and in seats ${1, 2}$, ${3, 4}$, ${4, 5}$, ${5, 6}$ or ${7, 8}$. \begin{center} {\small A row in the airplane} \end{center} Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats. Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.
Use greedy solution. Consider a group with $x \ge 4$ members, put $4$ of them in seats [3, 6] of some row, and throw the row. Now we have $x - 4$ members in this group now. Continue till all of the seats in the range $[3, 6]$ become full, continue with $[1, 2]$ and $[7, 8]$. Now handle groups with size $ \le 3$. For groups with size $= 3$, allocate $4$ seats in range $[3, 6]$ or $4$ seats in range $[1, 2]$ or $[7, 8]$. For groups with size $= 2$, allocate $2$ seats in range $[1, 2]$ or $[7, 8]$ or $3$ seats in range $[3, 6]$. If no seat found, divide this group and make it two groups with size 1. Fill the other parts with groups with groups with size $= 1$. If in any part we ran out of seat, the answer is NO, YES otherwise.
[ "brute force", "greedy", "implementation" ]
1,900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e2 + 17; int n, k, have[5], cnt[5]; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; have[2] = 2 * n, have[4] = n; for(int i = 0; i < k; i++){ int x; cin >> x; while(x >= 3) if(have[4] > 0) x -= 4, have[4]--; else if(have[2] > 0) x -= 2, have[2]--; else return cout << "NO" << '\n', 0; if(x > 0) cnt[x]++; } while(cnt[2]) if(have[2] > 0) cnt[2]--, have[2]--; else if(have[4] > 0) cnt[2]--, have[4]--, have[1]++; else cnt[2]--, cnt[1] += 2; if(cnt[1] > have[1] + have[2] + have[4] * 2) return cout << "NO" << '\n', 0; cout << "YES" << '\n'; return 0; }
839
C
Journey
There are $n$ cities and $n - 1$ roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be $1$. The journey starts in the city $1$. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.
Let the cities be vertices and roads be edges of a tree and vertex $1$ be the root of the tree. Let $ans[i]$ be the answer for the $i$-th vertex (the expected value if they start their journey from that vertex and the horse doesn't go to it's parent). Now we can calculate $ans[i]$ by knowing the answer for it's children. Let $v_{1}, v_{2}, \dots ., v_{k}$ be the children of $i$-th vertex , then $a n s[i]={\frac{a n s[v_{1}]+a n s[v_{2}]+\dots+a n s[v_{k}]}{k}}+1$ . Because when we are at $i$-th vertex , we have $k$ choices with equal probabilities and $+ 1$ for going to one of them (length of the edge between $i$-th vertex and it's children). So if we know the answer of some vertex's children, we can calculate its expected value and we can do it by a simple DFS (note that the answer for a leave is $0$).
[ "dfs and similar", "dp", "graphs", "probabilities", "trees" ]
1,500
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long double ld; const int maxn = 2e5 + 17, maxv = 1e6 + 17, mod = 1e9 + 7; int n; vector<int> g[maxn]; ld dfs(int v = 0, int p = -1){ ld sum = 0; for(auto u : g[v]) if(u != p) sum += dfs(u, v) + 1; return sum ? sum / (g[v].size() - (p != -1)) : 0; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n; for(int v, u, i = 1; i < n; i++){ cin >> v >> u, v--, u--; g[v].push_back(u); g[u].push_back(v); } cout << fixed << setprecision(7) << dfs() << '\n'; return 0; }
839
D
Winter is here
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of $n$ soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the $i$-th soldier’s strength be $a_{i}$. For some $k$ he calls $i_{1}, i_{2}, ..., i_{k}$ a clan if $i_{1} < i_{2} < i_{3} < ... < i_{k}$ and $gcd(a_{i1}, a_{i2}, ..., a_{ik}) > 1$ . He calls the strength of that clan $k·gcd(a_{i1}, a_{i2}, ..., a_{ik})$. Then he defines the strength of his army by the sum of strengths of all possible clans. Your task is to find the strength of his army. As the number may be very large, you have to print it modulo $1000000007$ ($10^{9} + 7$). Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
1st method: Let $cnt[i]$ be the number of such $j$s that $a_{j}$ is divisible by $i$. Also let $p[i]$ be $i$-th prime number. Let $f(m)$ be $\textstyle\sum_{x\subseteq S}s i z e(x)$ for an arbitrary set with $m$ members(something like the sum of strengths of all possible subsets, but replace $1$ with the $gcd$ of the sequence) Finally let $ans[i]$ be the sum of strengths of clans which $gcd(strengths - of - clan's - soldiers) = i$. Now we can calculate $ans[i]$ by "Inclusion-exclusion principle" : $\begin{array}{c}{{a n s[i]=i[\sum_{j}f(c n t[p_{j}\cdot i])-\sum_{j\leq k}f(c n t[p_{j}\cdot p_{k}\cdot i])+\sum_{j\leq k}f(c n t[p_{j}\cdot p_{k}\cdot p_{t}\cdot i]).}}\end{array}$ Because $i \cdot f(i)$ includes all possible clans that their members are all multiples of $i$, not the ones with $gcd$ equal to $i$ .Now, we can do the above calculation by a "foor-loop" through the multiples of $i$. So all we have to do , is to calculate $f(x)$ very fast. Actually $f(x) = x \cdot 2^{x - 1}$ because : $f(x)=\sum_{i=0}^{x}i\cdot{\left(\begin{array}{l}{x}\\ {i}\end{array}\right)}=x\cdot2^{x-1}$ 2nd method: Let $cnt[i]$ be the number of such $j$s that $a_{j}$ is divisible by $i$. Than $cnt[i]$ is count of soliders with strength of $i, 2i, 3i, ...$. Let $ans[i]$ be count of people in clans with $gcd = i$. To find $ans[i]$ let's understand, how to find count of people in clans, in which every number is divided by $i$. If $cnt[i] = c$, it's $\frac{1\cdot\left(_{1}^{c}\right)+2\cdot\left(_{^{c}}^{c}\right)+\cdot\cdot\cdot\cdot\cdot\left(_{_{c}}^{c}\right)+\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\left(_{_{G}}^{\left(1\right)}=\frac{_{V^{c}}}{\left(c-1\right)!\,1}+\frac{_{-c^{1}}}{\left(c-1\right)!\,2}+\cdot\cdot\cdot\cdot\cdot\cdot+\frac{_{\mathrm{-cl}}}{_{(C-1)}}\left(\frac{^{c}}{c-1}\right)+\cdot\cdot\cdot\cdot\cdot\cdot\left(\frac{_{_{C}}}{_{1}^{c}}\right)=c\cdot2^{c-1}\left(\frac{^{-1}}{c-1}\right)\left(\frac{^{c-1}}{c-1}\right)-\cdot\right)\left(\frac{_{V}}{c-1}\right)}\right)$ Let's calculate $ans[i]$ from the end. Then $ans[i] = cnt[i] \cdot 2^{cnt[i] - 1} - ans[2i] - ans[3i] - ...$. Answer for problem's question is $\sum_{i=2}^{1000000}i\cdot a n s[i]$. Asymptotics of solution is $O(k+{\frac{k}{2}}+{\frac{k}{3}}+\cdot\cdot\cdot)=O(k\cdot l o g_{k})$, where $k$ is maximal value of $a_{i}$.
[ "combinatorics", "dp", "math", "number theory" ]
2,200
//sobskdrbhvk //remember the flying, the bird dies ):( #include <bits/stdc++.h> using namespace std; typedef long long int LL; typedef pair<int, int> pii; typedef pair<LL, LL> pll; #define PB push_back #define MP make_pair #define L first #define R second #define sz(x) ((int)(x).size()) #define smax(x, y) ((x) = max((x), (y))) #define smin(x, y) ((x) = min((x), (y))) #define all(x) x.begin(),x.end() const int maxn = 1e6 + 10; const LL Mod = 1e9 + 7; bool isp[maxn]; int sign[maxn], cnt[maxn]; LL P[maxn]; int n; LL func(int x) { return (x * P[x - 1]) % Mod; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); memset(isp, true, sizeof isp); fill(sign, sign + maxn, 1); isp[0] = isp[1] = false; for (int i = 2; i < maxn; i++) if (isp[i]) for (int j = i; j < maxn; j += i) { isp[j] = i == j; if ((j / i) % i == 0) sign[j] = 0; else sign[j] *= -1; } P[0] = 1; for (int i = 1; i < maxn; i++) P[i] = (P[i - 1] << 1) % Mod; cin >> n; for (int x, i = 0; i < n; i++) cin >> x, cnt[x]++; for (int i = 1; i < maxn; i++) for (int j = i + i; j < maxn; j += i) cnt[i] += cnt[j]; LL ans = 0; for (int i = 2; i < maxn; i++) { LL rc = 0; for (int j = i; j < maxn; j += i) rc = (rc + sign[j / i] * func(cnt[j])) % Mod; ans += rc * i; ans %= Mod; } ans = (ans + Mod) % Mod; cout << ans << endl; return 0; }
839
E
Mother of Dragons
There are $n$ castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has $k$ liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles $a$ and $b$, and they contain $x$ and $y$ liters of that liquid, respectively, then the strength of that wall is $x·y$. Your task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.
Lemma : Let $G$ be a simple graph. To every vertex of $G$ we assign a nonnegative real number such that the sum of the numbers assigned to all vertices is $1$. For any two connected vertices (by an edge), compute the product of the numbers associated to these vertices. The maximal value of the sum of these products is when assign equal numbers to a maximal clique (a subgraph that all of its vertices are connected to each other) and $0$ to the rest of the graph. Proof : If the graph is complete of order $n$ then the problem reduces to finding the maximum of $\sum_{1<i<i<n}x_{i}.x_{j}$ knowing that $x_{1} + x_{2} + \dots + x_{n} = 1$. This is easy, since $\sum_{1\leq i<j\leq n}x_{i}.x_{j}=\textstyle{\frac{1}{2}}(1-\sum_{i=1}^{n}x_{i}^{2})\leq\textstyle{\frac{1}{2}}(1-{\frac{1}{n}})$. The last inequality is just the Cauchy-Schwarz inequality and we have equality when all variables are $\textstyle{\frac{1}{n}}$. Unfortunately, the problem is much more difficult in other cases, but at least we have an idea of a possible answer: indeed, it is easy now to find a lower bound for the maximum: if $H$ is the complete subgraph with maximal number of vertices $k$, then by assigning these vertices $\textstyle{\frac{1}{k}}$ and to all other vertices $0$, we find that the desired maximum is at least $\textstyle{\frac{1}{2}}(1-{\frac{1}{k}})$. We still have to solve the difficult part: showing that the desired maximum is at most $\textstyle{\frac{1}{2}}(1-{\frac{1}{k}})$. Let us proceed by induction on the number n of vertices of $G$. If $n = 1$ everything is clear, so assume the result true for all graphs with at most $n-1$ vertices and take a graph $G$ with $n$ vertices, numbered $1, 2, ... , n$. Let $A$ be the set of vectors with nonnegative coordinates and whose components add up to $1$ and $E$ the set of edges of $G$. Because the function $f(x_{1},x_{2},\cdot\cdot\cdot,x_{n})=\sum_{(i,j)\in E}x_{i}\cdot x_{j}$ is continuous on the compact set $A$ , it attains its maximum in a point $(x_{1}, x_{2}, ... , x_{n})$. If at least one of the $x_{i}$ is zero, then $f(G) = f(G_{1})$ where $G_{1}$ is the graph obtained by erasing vertex $i$ and all edges that are incident to this vertex. It suffices to apply the induction hypothesis to $G_{1}$ (clearly, the maximal complete subgraph of $G_{1}$ has at most as many vertices as the maximal complete subgraph of $G$). So, suppose that all $x_{i}$ are positive. We may assume that $G$ is not complete, since this case has already been discussed. So, let us assume for example that vertices $1$ and $2$ are not connected. Choose any number $0 < a \le x_{1}$ and assign to vertices $1, 2, ... , n$ of $G$ the numbers $x_{1}-a, x_{2} + a, x_{3}, ... , x_{n}$. By maximality of $f(G)$, we must have $\textstyle\sum_{i\in C_{1}}x_{i}\leq\sum_{i\in C_{2}}x_{i}$ , where $C_{1}$ is the set of vertices that are adjacent to vertex 2 and not adjacent to vertex 1 (the definition of C2 being clear). By symmetry, we deduce that we must actually have $\textstyle\sum_{i\in C_{1}}x_{i}=\sum_{i\in C_{2}}x_{i}$ , which shows that $f(x_{1}, x_{2}, ... , x_{n}) = f(0, x_{1} + x_{2}, x_{3}, ... , x_{n})$. Hence we can apply the previous case and the Lemma is solved. Now by the Lemma , we have to find the maximal clique and get the answer.(Let the maximal clique have $m$ vertices, then the answer is $\frac{k^{2}\!\cdot\!\left(m\!-\!1\right)}{2\!\cdot\!m}$). We can find the maximal clique by the "meet in the middle" approach. Divide the vertices of the graph into 2 sets with equal number of vertices in each set(if $n$ is odd, one set will have a vertex more than the other). We can save the maximal clique for each subset of the first set in $dp[mask]$. Now ,for each clique $C$ in the second set, let $v_{1}, ... , v_{t}$ be vertices in the first set that are connected to all of the vertices of $C$. Then $m = max(m, dp[mask(v_{1}, ... , v_{t})] + sizeof(C))$ ($m$ is size of maximum clique). Note : finding the maximal clique is also possible by a wise brute forces.
[ "brute force", "graphs", "math", "meet-in-the-middle" ]
2,700
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 40, C = 20; int n, k, dp[1 << C]; ll adj[maxn]; int maxc(){ for(int i = 0; i < n; i++) for(int j = 0, x; j < n; j++) cin >> x, adj[i] |= (ll) (x || i == j) << j; for(int i = 1; i < (1 << max(0, n - C)); i++){ int x = i; for(int j = 0; j < C; j++) if((i >> j) & 1) x &= adj[j + C] >> C; if(x == i) dp[i] = __builtin_popcount(i); } for(int i = 1; i < (1 << max(0, n - C)); i++) for(int j = 0; j < C; j++) if((i >> j) & 1) dp[i] = max(dp[i], dp[i ^ (1 << j)]); int ans = 0; for (int i = 0; i < (1 << min(C, n)); i++){ int x = i, y = (1 << max(0, n - C)) - 1; for (int j = 0; j < min(C, n); j++) if ((i >> j) & 1) x &= adj[j] & ((1 << C) - 1), y &= adj[j] >> C; if (x != i) continue; ans = max(ans, __builtin_popcount(i) + dp[y]); } return ans; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; int ans = maxc(); long double x = (long double) k / ans; cout << fixed << setprecision(8) << x * x * ans * (ans - 1) / 2 << '\n'; return 0; }
840
A
Leha and Function
Leha like all kinds of strange things. Recently he liked the function $F(n, k)$. Consider all possible $k$-element subsets of the set $[1, 2, ..., n]$. For subset find minimal element in it. $F(n, k)$ — mathematical expectation of the minimal element among all $k$-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays $A$ and $B$, each consists of $m$ integers. For all $i, j$ such that $1 ≤ i, j ≤ m$ the condition $A_{i} ≥ B_{j}$ holds. Help Leha rearrange the numbers in the array $A$ so that the sum $\textstyle\sum_{i=1}^{m}F(A_{i}^{\prime},B_{i})$ is maximally possible, where $A'$ is already rearranged array.
First of all, let's understand what is the value of $F(N, K)$. For any subset of size $K$, say, $a_{1}, a_{2}...a_{K}$, we can represent it as a sequence of numbers $d_{1}, d_{2}...d_{K + 1}$, so that $d_{1} = a_{1}$, $d_{1} + d_{2} = a_{2}$, ..., $\sum_{i=1}^{K+1}d_{i}=N+1$. We're interested in $E[d_{1}]$, expected value of $d_{1}$. Knowing some basic facts about expected values, we can derive the following: $E[d_{1} + ... + d_{K + 1}] = N + 1$ $E[d_{1}] + ... + E[d_{K + 1}] = (K + 1) \cdot E[d_{1}]$ And we immediately get that $E[d_{1}]={\frac{N+1}{K+1}}$. We could also get the formula by using the Hockey Stick Identity, as Benq stated in his comment. Now, according to rearrangement inequality, $\sum_{i=1}^{n}{\frac{A_{1}+1}{B_{1}+1}}$ is maximized when $A$ is increasing and $B$ is decreasing. Complexity: $O(NlogN)$
[ "combinatorics", "greedy", "math", "number theory", "sortings" ]
1,300
null
840
B
Leha and another game about graph
Leha plays a computer game, where is on each level is given a connected graph with $n$ vertices and $m$ edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer $d_{i}$, which can be equal to $0$, $1$ or $ - 1$. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, $d_{i}$ = - 1 or it's degree modulo 2 is equal to $d_{i}$. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.
Model solution uses the fact that the graph is connected. We'll prove that "good" subset exists iff $- 1$ values among $d_{i}$ can be changed to $0 / 1$ so that $\sum_{i=1}^{n}d_{i}$ is even. If the sum can only be odd, there is no solution obviously (every single valid graph has even sum of degrees). Now we'll show how to build the answer for any case with even sum. First of all, change all $- 1$ values so that the sum becomes even. Then let's find any spanning tree and denote any vertex as the root. The problem is actually much easier now. Let's process vertices one by one, by depth: from leaves to root. Let's denote current vertex as $cur$. There are two cases: 1) $d_{cur} = 0$ In this case we ignore the edge from $cur$ to $parent_{cur}$ and forget about $cur$. Sum remains even. 2) $d_{cur} = 1$ In this case we add the edge from $cur$ to $parent_{cur}$ to the answer, change $d_{parentcur}$ to the opposite value and forget about $cur$. As you can see, sum changed its parity when we changed $d_{parentcur}$, but then it changed back when we discarded $cur$. So, again, sum remains even. Using this simple manipulations we come up with final answer. Complexity: $O(N + M)$
[ "constructive algorithms", "data structures", "dfs and similar", "dp", "graphs" ]
2,100
null
840
C
On the Bench
A year ago on the bench in public park Leha found an array of $n$ numbers. Leha believes that permutation $p$ is right if for all $1 ≤ i < n$ condition, that $a_{pi}·a_{pi + 1}$ is not perfect square, holds. Leha wants to find number of right permutations modulo $10^{9} + 7$.
Let's divide all numbers into groups. Scan all numbers from left to right. Suppose that current position is $i$. If $group_{i}$ is not calculated yet, $i$ forms a new group. Assign unique number to $group_{i}$. Then for all $j$ such that $j > i$ and $a[j] \cdot a[i]$ is a perfect square, make $group_{j}$ equal to $group_{i}$. Now we can use dynamic programming to calculate the answer. $F(i, j)$ will denote the number of ways to place first $i$ groups having $j$ "bad" pairs of neighbors. Suppose we want to make a transition from $F(i, j)$. Let's denote size of group $i$ as $size$, and total count of numbers placed before as $total$. We will iterate $S$ from $1$ to $min(size, total + 1)$ and $D$ from $0$ to $min(j, S)$. $S$ is the number of subsegments we will break the next group in, and $D$ is the number of currently existing "bad" pairs we will eliminate. This transition will add $T$ to $F(i + 1, j - D + size - S)$ ($D$ "pairs" eliminated, $size - S$ new pairs appeared after placing new group). $T$ is the number of ways to place the new group according to $S$ and $D$ values. Actually it's $s i z e!\cdot\left(\stackrel{s i z e-1}{S-1}\right)\cdot\left(\stackrel{j}{D}\right)\cdot\left(\stackrel{t o t a l+1-j}{S-D}\right)$. Why? Because there are $\textstyle{\binom{s(s z e-1)}{S-1}}$ ways to break group of size $size$ into $S$ subsegments. $\textstyle{\binom{j}{D}}$ ways to select those $D$ "bad" pairs out of existing $j$ we will eliminate. And $\stackrel{\left(v a l a+1-3\right)}{\leq}$ ways to choose placements for $S - D$ subsegment (other $D$ are breaking some pairs so their positions are predefined). After all calculations, the answer is $F(g, 0)$, where $g$ is the total number of groups. Complexity: O(N^3)
[ "combinatorics", "dp" ]
2,500
null
840
D
Destiny
Once, Leha found in the left pocket an array consisting of $n$ integers, and in the right pocket $q$ queries of the form $l$ $r$ $k$. If there are queries, then they must be answered. Answer for the query is minimal $x$ such that $x$ occurs in the interval $l$ $r$ strictly more than $\textstyle{\frac{r-l+1}{k}}$ times or $ - 1$ if there is no such number. Help Leha with such a difficult task.
We will use classical divide and conquer approach to answer each query. Suppose current query is at subsegment $[L;R]$. Divide the original array into two parts: $[1;mid]$ and $[mid + 1;N]$, where $m i d={\frac{L+R}{2}}$. If our whole query belongs to the first or the second part only, discard the other part and repeat the process of division. Otherwise, $L \le mid \le R$. We claim that if we form a set of $K$ most frequent values on $[L;mid]$ and $K$ most frequent values on $[mid + 1;R]$, one of the values from this set will be the answer, or there is no suitable value. $K$ most frequent values thing can be precalculated. Run recursive function $build(node, L, R)$. First, like in a segment tree, we'll run this function from left and right son of $node$. Then we need $K$ most frequent values to be precalculated for all subsegments $[L1;R1]$, such that $L \le L1 \le R1 \le R$ and at least one of $L1$ and $R1$ is equal to $\frac{L+R}{2}$. We will consider segments such that their left border is $mid$ in the following order: $[mid;mid], [mid;mid + 1], ...[mid;R]$. If we already have $K$ most frequent values and their counts for $[mid, i]$, it's rather easy to calculate them for $[mid, i + 1]$. We update the count of $a_{i + 1}$ and see if anything should be updated for the new list of most frequent values. Exactly the same process happens to the left side of $mid$: we are working with the subsegments in order $[mid;mid], [mid - 1;mid], ..., [L;mid]$. Now, having all this data precalculated, we can easily run divide and conquer and get the candidates for being the solution at any $[L;R]$ segment. Checking a candidate is not a problem as well: we can save all occurrences in the array for each number and then, using binary search, easily answer the following questions: "How many times $x$ appears from $L$ to $R$?". Complexity: O(KNlogN)
[ "data structures", "probabilities" ]
2,500
null
840
E
In a Trap
Lech got into a tree consisting of $n$ vertices with a root in vertex number $1$. At each vertex $i$ written integer $a_{i}$. He will not get out until he answers $q$ queries of the form $u$ $v$. Answer for the query is maximal value $a_{i}\oplus d i s t(i,v)$ among all vertices $i$ on path from $u$ to $v$ including $u$ and $v$, where $dist(i, v)$ is number of edges on path from $i$ to $v$. Also guaranteed that vertex $u$ is ancestor of vertex $v$. Leha's tastes are very singular: he believes that vertex is ancestor of itself. Help Leha to get out. The expression $x\oplus y$ means the bitwise exclusive OR to the numbers $x$ and $y$. Note that vertex $u$ is ancestor of vertex $v$ if vertex $u$ lies on the path from root to the vertex $v$.
The path from $u$ to $v$ can be divided into blocks of $256$ nodes and (possibly) a single block with less than $256$ nodes. We can consider this last block separately, by iterating all of its nodes. Now we need to deal with the blocks with length exactly $256$. They are determined by two numbers: $x$ - last node in the block, and $d$ - $8$ highest bits. We can precalculate this values and then use them to answer the queries. Let's now talk about precalculating $answer(x, d)$. Let's fix $x$ and $255$ nodes after $x$. It's easy to notice that lowest $8$ bits will always be as following: $0, 1, ..., 255$. We can xor this values: $0$ with $a_{x}$, $1$ with $a_{nextx}$ and so on, and store the results in a trie. Now we can iterate all possible values of $d$ (from $0$ to $255$) and the only thing left is to find a number stored in a trie, say $q$, such that $q$ xor $255 \cdot d$ is maximized. Complexity: O(NsqrtNlogN)
[ "trees" ]
3,200
null
841
A
Generous Kefa
One day Kefa found $n$ baloons. For convenience, we denote color of $i$-th baloon as $s_{i}$ — lowercase letter of the Latin alphabet. Also Kefa has $k$ friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out \textbf{all} baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Consider each balloon color separately. For some color $c$, we can only assign all balloons of this color to Kefa's friends if $c \le k$. Because otherwise, by pigeonhole principle, at least one of the friends will end up with at least two balloons of the same color. This leads us to a fairly simple solution: calculate number of occurrences for each color, like, $cnt_{c}$. Then just check that $cnt_{c} \le k$ for each possible $c$. Complexity: $O(N + K)$
[ "brute force", "implementation" ]
900
null
841
B
Godsend
Leha somehow found an array consisting of $n$ integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?
First player wins if there is at least one odd number in the array. Let's prove this. Let's denote total count of odd numbers at $T$. There are two cases to consider: 1) $T$ is odd. First player takes whole array and wins. 2) $T$ is even. Suppose that position of the rightmost odd number is $pos$. Then the strategy for the first player is as follows: in his first move, pick subarray $[1;pos - 1]$. The remaining suffix of the array will have exactly one odd number that second player won't be able to include in his subarray. So, regardless of his move, first player will take the remaining numbers and win.
[ "games", "math" ]
1,100
null
842
A
Kirill And The Game
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers $a$ and $b$ such that $l ≤ a ≤ r$ and $x ≤ b ≤ y$ there is a potion with experience $a$ and cost $b$ in the store (that is, there are $(r - l + 1)·(y - x + 1)$ potions). Kirill wants to buy a potion which has efficiency $k$. Will he be able to do this?
Let's denote the potion's amount of experience as $exp$ and its cost as $cost$. We want to know if there is a potion such that $exp$ and $cost$ meet the following condition: $\stackrel{\alpha,p}{\omega,q}=k$. To do this, we can iterate on $cost$ from $x$ to $y$ and check that $exp = k \cdot cost$ is not less than $l$ and not greater than $r$.
[ "brute force", "two pointers" ]
1,200
"#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nsigned main()\n{\n // k = exp / cost;\n int l, r, x, y, k;\n bool ans = 0;\n cin >> l >> r >> x >> y >> k;\n for (int i = x; i <= y; i++)\n {\n if (l <= i * k && i * k <= r)\n {\n ans = 1;\n }\n }\n if (ans)\n {\n cout << \"YES\";\n }\n else\n {\n cout << \"NO\";\n }\n return 0;\n}"
842
B
Gleb And Pizza
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius $r$ and center at the origin. Pizza consists of the main part — circle of radius $r - d$ with center at the origin, and crust around the main part of the width $d$. Pieces of sausage are also circles. The radius of the $i$ -th piece of the sausage is $r_{i}$, and the center is given as a pair ($x_{i}$, $y_{i}$). Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.
To understand whether some piece of sausage intersects with pizza, we can check if their borders intersect. And to check this, since their borders are circles, we are interested in their radii and the distance between their centers. To check if a piece of sausage is inside the crust, we firstly check that it is inside the pizza $({\sqrt{x^{2}+y^{2}}})+c r\leq r$), and secondly check that it is completely outside the central part of the pizza $({\sqrt{x^{2}+y^{2}}}\geq r-d+c r$).
[ "geometry" ]
1,100
"#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <vector>\n#include <string>\n#include <ctime>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n\n//#include <unordered_set>\n//#include <unordered_map>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define for1(i, n) for (int i = 1; i < int(n); i++)\n#define forft(i, from, to) for (int i = int(from); i < int(to); i++)\n#define forr(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define X first\n#define Y second\n#define mp make_pair\n#define pb push_back\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define ms(a, v) memset(a, v, sizeof(a))\n#define correct(x, y, n, m) (x >= 0 && x < n && y >= 0 && y < m)\n\nusing namespace std;\n\ntemplate<typename T> T sqr(const T &x) {\n return x * x;\n}\n\ntypedef long long ll;\ntypedef long long li;\ntypedef pair<int, int> pt;\ntypedef long double ld;\ntypedef pair<ld, ld> pd;\n\nconst int INF = int(1e9);\nconst ll INF_LL = ll(4e18);\nconst ll INF64 = ll(4e18);\nconst ll LINF = ll(4e18);\nconst ld EPS = 1e-9;\nconst ld PI = 3.14159265358979323846264338;\n\nint r, d;\nint n;\n\nbool read() {\n scanf(\"%d%d%d\", &r, &d, &n);\n return true;\n}\n\nvoid solve() {\n int ans = 0;\n\n forn(i, n) {\n int x, y, cr;\n scanf(\"%d%d%d\", &x, &y, &cr);\n\n if (sqr(li(x)) + sqr(li(y)) <= sqr(li(r - cr)) && 2 * cr <= d && sqr(li(x)) + sqr(li(y)) >= sqr(li(r - d + cr))) {\n ++ans;\n }\n }\n\n printf(\"%d\\n\", ans);\n}\n\nint main() {\n srand((int) time(NULL));\n cout << setprecision(10) << fixed;\n \n read();\n solve();\n\n cerr << clock() << endl;\n\n return 0;\n}"
842
C
Ilya And The Tree
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex $1$. There is an integer number written on each vertex of the tree; the number written on vertex $i$ is equal to $a_{i}$. Ilya believes that the beauty of the vertex $x$ is the greatest common divisor of all numbers written on the vertices on the path from the root to $x$, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to $0$ or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have. For each vertex the answer must be considered independently. The beauty of the root equals to number written on it.
It's easy to see that if the number written on some vertex $i$ is not equal to $0$, then its beauty will be some divisor of $a_{i}$. Also if the number written on the root is $0$ then the beauty of each vertex can be easily calculated. Otherwise beauty of each vertex will be a divisor of the number in the root. Let's calculate the beauty of each vertex if the number in the root is 0. This can be done by traversing the tree, and the beauty of $i$ is $gcd(a_{i}, ans[par_{i}])$. If the number in the root is not $0$, then possible values of beauty for each vertex are among divisors of this number. For each of these divisors we can maintain how many numbers on the path from the root to current vertex are divisible by that divisor. When we enter or leave some vertex, we need to update this information by iterating on divisors of the number in the root. If we maintain it and current depth $d$, then we can calculate the possible beauty of current vertex. It is equal to greatest divisor such that there are at least $d - 1$ numbers on the path that are divisible by this divisor.
[ "dfs and similar", "graphs", "math", "number theory", "trees" ]
2,000
"#include<bits/stdc++.h>\n#define f first\n#define s second\nusing namespace std;\n\nint n;\nvector<int>ans;\nvector<bool>vis;\nvector<int>mas;\nvector<int>del;\nvector<int>koll;\nvector<vector<int>>edges;\n\nint nod(int a, int b)\n{\n if (b == 0)\n return a;\n return nod(b, a % b);\n}\n\nvoid dfs1(int v)\n{\n vis[v] = 1;\n for (auto u : edges[v])\n if (! vis[u])\n {\n ans[u] = nod(ans[v], mas[u]);\n dfs1(u);\n }\n}\n\nvoid dfs2(int v, int dist)\n{\n vis[v] = 1;\n for (int i = 0; i < del.size(); i++)\n {\n koll[i] += (mas[v] % del[i] == 0);\n if (koll[i] >= dist)\n ans[v] = max(ans[v], del[i]);\n }\n for (auto u : edges[v])\n if (! vis[u])\n dfs2(u, dist + 1);\n for (int i = 0; i < del.size(); i++)\n koll[i] -= (mas[v] % del[i] == 0);\n}\n\nsigned main()\n{\n ios_base::sync_with_stdio(0);\n int n;\n cin>>n;\n ans.resize(n);\n vis.resize(n);\n mas.resize(n);\n edges.resize(n);\n for (int i = 0; i < n; i++)\n cin>>mas[i];\n for (int i = 0; i < n - 1; i++)\n {\n int a, b;\n cin>>a>>b;\n a--; b--;\n edges[a].push_back(b);\n edges[b].push_back(a);\n }\n int p = mas[0];\n mas[0] = 0;\n ans[0] = 0;\n dfs1(0);\n mas[0] = p;\n for (int i = 0; i < n; i++)\n vis[i] = 0;\n for (int i = 1; i*i <= mas[0]; i++)\n {\n if (mas[0] % i == 0)\n {\n del.push_back(i);\n del.push_back(mas[0] / i);\n if (i*i == mas[0])\n del.pop_back();\n }\n }\n sort(del.begin(), del.end());\n koll.resize(del.size());\n dfs2(0, 0);\n for (int i = 0; i < n; i++)\n cout<<ans[i]<<' ';\n return 0;\n}"
842
D
Vitya and Strange Lesson
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, $mex([4, 33, 0, 1, 1, 5]) = 2$ and $mex([1, 2, 3]) = 0$. Vitya quickly understood all tasks of the teacher, but can you do the same? You are given an array consisting of $n$ non-negative integers, and $m$ queries. Each query is characterized by one number $x$ and consists of the following consecutive steps: - Perform the bitwise addition operation modulo $2$ (xor) of each array element with the number $x$. - Find mex of the resulting array. Note that after each query the array changes.
If the last query was $x_{i}$ and then we receive a query $x_{i + 1}$, then we can leave the original array unchanged and use the number $x_{i}\oplus x_{i+1}$ as the second query. So we will maintain current xor of queries instead of changing the array. It's easy to see that if the array contains all numbers from zero to $2^{k} - 1$ and the number in the query is less than $2^{k}$, then the array will still contain all those numbers. Let's store all numbers from the array in binary trie and maintain the number of leaves in each subtree. To answer each query, we will descend the trie. We need to get the lowest possible answer, so if current bit of the number in the query equals $i$ ($i = 0$ or $i = 1$), so we firstly check the subtree that corresponds to bit $i$. We will descend into the vertex only if the subtree is not a complete binary tree (so there exists a number that would belong to this subtree but is not included in the array). When we try to descend into an empty subtree, then we set all remaining bits in the answer to zero.
[ "binary search", "data structures" ]
2,000
"#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <vector>\n#include <string>\n#include <ctime>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n\n//#include <unordered_set>\n//#include <unordered_map>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define for1(i, n) for (int i = 1; i < int(n); i++)\n#define forft(i, from, to) for (int i = int(from); i < int(to); i++)\n#define forr(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define X first\n#define Y second\n#define mp make_pair\n#define pb push_back\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define ms(a, v) memset(a, v, sizeof(a))\n#define correct(x, y, n, m) (x >= 0 && x < n && y >= 0 && y < m)\n\nusing namespace std;\n\ntemplate<typename T> T sqr(const T &x) {\n return x * x;\n}\n\ntypedef long long ll;\ntypedef long long li;\ntypedef pair<int, int> pt;\ntypedef long double ld;\ntypedef pair<ld, ld> pd;\n\nconst int INF = int(1e9);\nconst ll INF_LL = ll(4e18);\nconst ll INF64 = ll(4e18);\nconst ll LINF = ll(4e18);\nconst ld EPS = 1e-9;\nconst ld PI = 3.14159265358979323846264338;\n\nconst int N = 3e5 + 10;\nconst int M = 20;\n\nint n, m;\nint a[N];\n\nstruct node {\n int nxt[2];\n int d;\n\n node() {\n nxt[0] = -1;\n nxt[1] = -1;\n d = 0;\n }\n};\n\nnode t[N * M];\nint len = 1;\n\nbool read() {\n scanf(\"%d%d\", &n, &m);\n\n forn(i, n) {\n scanf(\"%d\", &a[i]);\n }\n\n return true;\n}\n\nvoid add(int v, int num, int pos) {\n if (pos < 0) {\n t[v].d = 1;\n return;\n }\n\n int nxt = ((num >> pos) & 1);\n\n if (t[v].nxt[nxt] == -1) {\n t[v].nxt[nxt] = len++;\n }\n\n add(t[v].nxt[nxt], num, pos - 1);\n t[v].d = 0;\n \n if (t[v].nxt[0] != -1) {\n t[v].d += t[t[v].nxt[0]].d;\n }\n \n if (t[v].nxt[1] != -1) {\n t[v].d += t[t[v].nxt[1]].d;\n }\n}\n\nvoid get(int v, int num, int pos, int &ans) {\n if (v == -1) {\n return;\n }\n\n int nxt = ((num >> pos) & 1);\n\n if (t[t[v].nxt[nxt]].d == (1 << pos)) { \n nxt = 1 - nxt;\n }\n\n ans |= ((nxt ^ ((num >> pos) & 1)) << pos);\n get(t[v].nxt[nxt], num, pos - 1, ans);\n}\n\nvoid solve() {\n forn(i, n) {\n add(0, a[i], M - 1);\n }\n\n int c = 0;\n\n forn(i, m) {\n int k;\n scanf(\"%d\", &k);\n c ^= k;\n\n int ans = 0;\n get(0, c, M - 1, ans);\n printf(\"%d\\n\", ans);\n }\n}\n\nint main() {\n srand((int) time(NULL));\n cout << setprecision(10) << fixed;\n \n read();\n solve();\n\n cerr << clock() << endl;\n\n return 0;\n}"
842
E
Nikita and game
Nikita plays a new computer game. There are $m$ levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class $y_{i}$ (and $y_{i}$ is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index $1$. Changing the class to its neighbour (child-class or parent-class) in the tree costs $1$ coin. You can not change the class back. The cost of changing the class $a$ to the class $b$ is equal to the total cost of class changes on the path from $a$ to $b$ in the class tree. Suppose that at $i$ -th level the maximum cost of changing one class to another is $x$. For each level output the number of classes such that for each of these classes there exists some other class $y$, and the distance from this class to $y$ is exactly $x$.
The vertices in the answer are the endpoints of some diameter of the tree. Let's consider diameter ($a$, $b$), where $a$ and $b$ are its endpoints, and we add a new vertex $c$. Then the length of diameter either remains the same or increases by one (then new endpoints are vertices ($a$, $c$) or ($b$, $c$)). We have to maintain current centers of the tree (there are not more than two centers). If the length of diameter increases, then the number of centers changes (but there will always exist a vertex that was the center before the query and remains the center after the query). Let's build a segment tree on the eulerian tour of the tree. The vertex that maintains the segment $[l, r]$ will store current maximal distance to the center and the number of vertices that have this distance. Then the answer for the query will be stored in the root of the segment tree. When we add a new vertex, we need to check whether the length of diameter increases; this can be done with LCA. If the diameter increases, we update centers and distances to them.
[ "binary search", "dfs and similar", "divide and conquer", "graphs", "trees" ]
2,800
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = int(1e9), N = 1e6, M = 21;\n\nint n, up[M][N], tin[N], tout[N], p[4 * N], timer;\npair<int, int> t[4 * N];\nvector<int> g[N];\n\nvoid push(int now)\n{\n\tif (p[now] == 0)\n {\n\t\treturn;\n\t}\n\tt[now].first += p[now];\n\tif (now * 2 + 2 < 4 * N)\n\t{\n\t\tp[now * 2 + 1] += p[now];\n\t\tp[now * 2 + 2] += p[now];\n\t}\n\tp[now] = 0;\n}\n\nvoid update1(int now)\n{\n\tint l = now * 2 + 1;\n\tint r = now * 2 + 2;\n\tif (t[l].first > t[r].first)\n {\n\t\tt[now] = t[l];\n\t}\n\telse if (t[r].first > t[l].first)\n {\n t[now] = t[r];\n }\n else\n {\n t[now] = t[l];\n t[now].second += t[r].second;\n\t}\n}\n\nvoid change(int now, int l, int r, int pos, int val)\n{\n\tpush(now);\n\tif (l == r)\n {\n\t\tt[now] = {val, 1};\n\t\treturn;\n\t}\n\tint mid = (l + r) / 2;\n\tif (pos <= mid)\n\t{\n\t\tchange(now * 2 + 1, l, mid, pos, val);\n\t}\n\telse\n {\n\t\tchange(now * 2 + 2, mid + 1, r, pos, val);\n\t}\n\tpush(now * 2 + 1);\n\tpush(now * 2 + 2);\n\tupdate1(now);\n}\n\nvoid update(int now, int l, int r, int tl, int tr, int val)\n{\n if (tl > tr)\n {\n return;\n }\n\tpush(now);\n\tif (l == tl && r == tr)\n {\n\t\tp[now] += val;\n\t\tpush(now);\n\t\treturn;\n\t}\n\tint mid = (l + r) / 2;\n\tupdate(now * 2 + 1, l, mid, tl, min(mid, tr), val);\n\tupdate(now * 2 + 2, mid + 1, r, max(tl, mid + 1), tr, val);\n\tpush(now * 2 + 1);\n\tpush(now * 2 + 2);\n\tupdate1(now);\n}\n\nvoid dfs(int v, int p = 0)\n{\n\ttin[v] = timer++;\n\tup[0][v] = p;\n\tfor(int i = 1; i < M; i++)\n\t{\n up[i][v] = up[i - 1][up[i - 1][v]];\n }\n\tfor(int i = 0; i < g[v].size(); i++)\n\t{\n\t\tint u = g[v][i];\n\t\tif (u != p)\n {\n\t\t\tdfs(u, v);\n\t\t}\n\t}\n\ttout[v] = timer++;\n}\n\nbool anc(int p, int v)\n{\n\treturn tin[p] <= tin[v] && tout[v] <= tout[p];\n}\n\nint dist(int v1, int v2)\n{\n if (anc(v1, v2))\n {\n \t return 0;\n }\n\tint ans = 0;\n\tfor (int i = M - 1; i >= 0; i--)\n\t{\n\t\tif (!anc(up[i][v1], v2))\n\t\t{\n\t\t\tans += (1 << i);\n\t\t\tv1 = up[i][v1];\n\t\t}\n\t}\n\treturn ans + 1;\n}\n\nint lca(int v1, int v2)\n{\n\tfor (int i = M - 1; i >= 0; i--)\n\t{\n\t\tif (!anc(up[i][v1], v2))\n {\n\t\t\tv1 = up[i][v1];\n\t\t}\n\t}\n\treturn v1;\n}\n\nint main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n cin >> n;\n n++;\n\tfor(int i = 1; i < n; i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\tx--;\n\t\tg[i].push_back(x);\n\t\tg[x].push_back(i);\n\t}\n\tfor (int i = 0; i < N * 4; i++)\n {\n t[i] = {-INF, 0};\n }\n dfs(0);\n\tpair<int, int> c = {0, -1};\n\tchange(0, 0, 2 * n - 1, tin[0], 0);\n\tfor(int i = 1; i < n; i++)\n\t{\n\t\tint cd = t[0].first;\n\t\tint v = i;\n\t\tint nd = dist(v, c.first) + dist(c.first, v);\n\t\tif (c.second != -1)\n {\n\t\t\tint nd2 = dist(v, c.second) + dist(c.second, v);\n\t\t\tif (nd2 < nd)\n {\n\t\t\t\tnd = nd2;\n\t\t\t\tswap(c.first, c.second);\n\t\t\t}\n\t\t}\n\t\tchange(0, 0, 2 * n - 1, tin[v], nd);\n\t\tif (nd > cd)\n {\n pair<int, int> nc;\n if (c.second != -1)\n {\n nc = {c.first, -1};\n if (anc(c.first, c.second))\n {\n update(0, 0, 2 * n - 1, tin[c.second], tout[c.second], 1);\n }\n else\n {\n if (c.first > 0)\n {\n update(0, 0, 2 * n - 1, 0, tin[c.first] - 1, 1);\n }\n if (c.first < 2 * n - 1)\n {\n update(0, 0, 2 * n - 1, tout[c.first] + 1, 2 * n - 1, 1);\n }\n }\n }\n else\n {\n if (anc(c.first, v))\n {\n nc = {lca(v, c.first), c.first};\n }\n else\n {\n nc = {up[0][c.first], c.first};\n }\n if (anc(nc.first, nc.second))\n {\n if (nc.second > 0)\n {\n update(0, 0, 2 * n - 1, 0, tin[nc.second] - 1, -1);\n }\n if (nc.second < 2 * n - 1)\n {\n update(0, 0, 2 * n - 1, tout[nc.second] + 1, 2 * n - 1, -1);\n }\n }\n else\n {\n update(0, 0, 2 * n - 1, tin[nc.first], tout[nc.first], -1);\n }\n }\n c = nc;\n }\n cout << t[0].second << \"\\n\";\n\t}\n return 0;\n}"
843
A
Sorting by Subsequences
You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ consisting of \textbf{different} integers. It is required to split this sequence into the \textbf{maximum} number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence.
Sorting any sequence means applying some permutation to its elements. All elements of sequence $a$ are different, so this permutation is unique and fixed. Let's call it $P$. One could split this permutation into simple cycles. The subsequences in the answer are subsequences formed by these simple cycles. One could prove that it's impossible to split the sequence into more subsequences because if we could split the sequence into more subsequences, we also could split permutation $P$ into more cycles.
[ "dfs and similar", "dsu", "implementation", "math", "sortings" ]
1,400
null
843
B
Interactive LowerBound
This is an interactive problem. You are given a \textbf{sorted} in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to $x$. More formally, there is a singly liked list built on an array of $n$ elements. Element with index $i$ contains two integers: $value_{i}$ is the integer value in this element, and $next_{i}$ that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if $next_{i} ≠ - 1$, then $value_{nexti} > value_{i}$. You are given the number of elements in the list $n$, the index of the first element $start$, and the integer $x$. You can make up to $2000$ queries of the following two types: - ? i ($1 ≤ i ≤ n$) — ask the values $value_{i}$ and $next_{i}$, - ! ans — give the answer for the problem: the minimum integer, greater than or equal to $x$, or ! -1, if there are no such integers. Your program should terminate after this query. Write a program that solves this problem.
Let's ask the values in index $start$ and in 999 other random indexes, choose among them the largest value less or equal to $x$. Let's go from it in order to the elements of the list, until we meet the first element greater or equal to x, which will be the answer. The probability that this algorithm for 2000 of actions will not find the desired element is equal to the probability that among 1000 of previous before the correct answer of the list elements there will no one from our sample of 999 random elements. This probability can be estimated as $(1 - 999 / n)^{1000} \approx 1.7 \cdot 10^{ - 9}$ In order to not be hacked in this problem, you should use high-precision current system time as a random seed.
[ "brute force", "interactive", "probabilities" ]
2,000
null
843
C
Upgrading Tree
You are given a tree with $n$ vertices and you are allowed to perform \textbf{no more than} $2n$ transformations on it. Transformation is defined by three vertices $x, y, y'$ and consists of deleting edge $(x, y)$ and adding edge $(x, y')$. Transformation $x, y, y'$ could be performed if all the following conditions are satisfied: - There is an edge $(x, y)$ in the current tree. - After the transformation the graph remains a tree. - After the deletion of edge $(x, y)$ the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex $x$ by $V_{x}$, and the set of nodes in the component containing vertex $y$ by $V_{y}$. Then condition $|V_{x}| > |V_{y}|$ should be satisfied, i.e. the size of the component with $x$ should be strictly larger than the size of the component with $y$. You should \textbf{minimize} the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than $2n$ transformations and output any sequence of transformations leading initial tree to such state. Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.
A centroid-vertex remains a centroid during such process. If we have two centroids in a tree, the edge between them couldn't change. The components that are attached to the centroid can not change centroid they attached to or separate to several components. Using the size of the component operations, one could turn it into a bamboo, then using the size of the component operations one could turn it into a hedgehog suspended from its centroid. The proof that the sum of squares of distances couldn't be less is an additional exercise. Complexity of solution is ${\mathrm{on}}$
[ "constructive algorithms", "dfs and similar", "graphs", "math", "trees" ]
2,600
null
843
D
Dynamic Shortest Path
You are given a weighted directed graph, consisting of $n$ vertices and $m$ edges. You should answer $q$ queries of two types: - 1 v — find the length of shortest path from vertex $1$ to vertex $v$. - {2 c $l_{1} l_{2} ... l_{c}$} — add $1$ to weights of edges with indices $l_{1}, l_{2}, ..., l_{c}$.
Firstly, let's run an usual Dijkstra from $s$, find distances and make them a potentials of vertices. Then for each request let's recalculate all distances and make the potentials equal to these distances. To quickly recalculate the distance between requests, we can use the fact that in a graph with potentials, all distances are 0. When we increased the weight of some edges by 1, in the graph with potentials, all distances do not exceed the number of changed edges so we can run a Dijkstra on a vector per $O(V + E)$.
[ "graphs", "shortest paths" ]
3,400
null
843
E
Maximum Flow
You are given a directed graph, consisting of $n$ vertices and $m$ edges. The vertices $s$ and $t$ are marked as source and sink correspondingly. Additionally, there are no edges ending at $s$ and there are no edges beginning in $t$. The graph was constructed in a following way: initially each edge had capacity $c_{i} > 0$. A maximum flow with source at $s$ and sink at $t$ was constructed in this flow network. Let's denote $f_{i}$ as the value of flow passing through edge with index $i$. Next, all capacities $c_{i}$ and flow value $f_{i}$ were erased. Instead, indicators $g_{i}$ were written on edges — if flow value passing through edge $i$ was positive, i.e. $1$ if $f_{i} > 0$ and $0$ otherwise. Using the graph and values $g_{i}$, find out what is the \textbf{minimum} possible number of edges in the initial flow network that could be saturated (the passing flow is equal to capacity, i.e. $f_{i} = c_{i}$). Also construct the corresponding flow network with maximum flow in it. A flow in directed graph is described by flow values $f_{i}$ on each of the edges so that the following conditions are satisfied: - for each vertex, except source and sink, total incoming flow and total outcoming flow are equal, - for each edge $0 ≤ f_{i} ≤ c_{i}$ A flow is maximum if the difference between the sum of flow values on edges from the source, and the sum of flow values on edges to the source (there are no such in this problem), is maximum possible.
Let's find a minimal set of saturated edges. We will create new flow network consisting of the same set of vertices and a little bit different edges. For an each edge from original graph without any flow let's create a new edge with the same direction and $c = INF$ carrying capacity. For every edge with a flow let's create two edges: the first one with the same direction and $c = 1$ capacity and the second edge with reversed direction and $c = INF$. In the new network, we have to find the minimum cut, it will consist of edges with $f = 1$, corresponding edges of the initial graph will be a desired minimal set. If this minimal set was equal to infinity the description of the problem wouldn't be about maximum flow because it had to be increasing for sure. So now it's enough to create a non-zero flow for all edges needed in the task and to make $c = f$ on edges which we chose to be saturated and $c = f + 1$ on the rest. Let's consider directed graph with edges with a flow. Lemma: Every edge of a graph lies either on a cycle or on the way from source to flow. In the first situation we might make a circulation on a cycle $1$, in the second case, we can put a flow on the way from the source to the stream of $1$. Thus, for each edge on which something is to flow, something will flow. The proof of Lemma: Suppose the contrary. Let's take the edge of the form $u$->$v$. Well then, there is no way from $s$ to $u$ or no way from $v$ to $t$. Let the second be true without loss of generality. Let's consider the set of vertices attainable from $v$. If there are $u$ in this set, there is a cycle. Otherwise, this set is "bad", cause there are no $t$, in it something flows in and nothing follows, in a correct network this is impossible.
[ "flows", "graphs" ]
3,000
null
844
A
Diversity
Calculate the minimum number of characters you need to change in the string $s$, so that it contains at least $k$ different letters, or print that it is impossible. String $s$ consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
One could note what in case $k > |s|$, we should always print <<impossible>>. Overwise the finding value is equal $max(0, k - d)$, where $d$ is a number of different letters in the original string. It is correct because if $k \le d$ condition is satisfied and we shouldn't do anything, so the answer is zero. If $d < k \le |s|$ we could change $k - d$ duplicated letters to a different letters initially weren't contained in $s$. Solution complexity is $\mathbf{O}(|{\hat{s}}|)$
[ "greedy", "implementation", "strings" ]
1,000
null
844
B
Rectangles
You are given $n × m$ table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: - All cells in a set have the same color. - Every two cells in a set share row or column.
One could note, that each appropriate set of cells is always contained in one row or in one column. We should calculate numbers of white and black cells $k_{0}$ and $k_{1}$ in every row and every column. For every $k$ we will summarize $2^{k} - 1$ (the number of non-empty subsets of this color contained in one row/column). In the end, we subtract $n \cdot m$ from the whole sum (this is a number of one-cell sets, which we count twice). Solution complexity is $\mathrm{Otn}\cdot\mathrm{m}\rangle$
[ "combinatorics", "math" ]
1,300
null
845
A
Chess Tourney
Berland annual chess tournament is coming! Organizers have gathered $2·n$ chess players who should be divided into two teams with $n$ people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil. Thus, organizers should divide all $2·n$ players into two teams with $n$ people each in such a way that the first team always wins. Every chess player has its rating $r_{i}$. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win. After teams assignment there will come a drawing to form $n$ pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random. Is it possible to divide all $2·n$ players into two teams with $n$ people each so that the player from the first team in every pair wins \textbf{regardless} of the results of the drawing?
Let's sort the input array in non-decreasing order. Now we should take the first $n$ players to the first team and the last $n$ players - to the second team. That will guarantee that every member of the first team has greater or equal rating than every member of the second team. Now the only thing left is to check if all ratings in the first teams differ from all the ratings in the second team (if some are equal then $a_{n} = a_{n + 1}$ in sorted order).
[ "implementation", "sortings" ]
1,100
null
845
B
Luba And The Ticket
Luba has a ticket consisting of $6$ digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.
Let's iterate over all 6-digit numbers. Now we will calculate number of positions in which digit of current ticket differs from digit of input ticket and call it $res$. Then answer will be minimal value $res$ over all lucky tickets.
[ "brute force", "greedy", "implementation" ]
1,600
null
845
C
Two TVs
Polycarp is a great fan of television. He wrote down all the TV programs he is interested in for today. His list contains $n$ shows, $i$-th of them starts at moment $l_{i}$ and ends at moment $r_{i}$. Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV. Polycarp wants to check out all $n$ shows. Are two TVs enough to do so?
Let's process all the segments on the line from left to right. For each segment we should push events ($l_{i}, 1$) and ($r_{i} + 1, - 1$) into some array. Sort this array of pair in increasing order (usual less comparator for pairs). Then we iterate over its elements and maintain $cnt$ - the current amount of open segments (we passed their left border and didn't pass their right border). When we meet the event of the first type, we increment the value of $cnt$, the second type - decrement $cnt$. If $cnt \ge 3$ in some moment then the answer is "NO". Overall complexity: $O(n\cdot\log n)$.
[ "data structures", "greedy", "sortings" ]
1,500
null
845
D
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: - Polycarp changes the speed of his car to specified (this event comes with a positive integer number); - Polycarp's car overtakes the other car; - Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); - Polycarp's car goes past the "overtake is allowed" sign; - Polycarp's car goes past the "no speed limit"; - Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type $1$ (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
Let's notice that you should never say that you didn't notice signs "no speed limit" and "overtake is allowed". Also if you drive with speed $sp$, you don't want to remove signs "speed limit" with number greater or equal to $sp$. Thus, greedy solution will work. Process all the events in chronological order. We should maintain stack of signs "speed limit" and amount of signs "no overtake allowed". If we meet sign "speed limit", we push its limit to stack, sign "no overtake allowed" - increase $cnt$, "no speed limit" - clear stack, "overtake is allowed" - assign $cnt$ to zero. After every event we should check if our speed is fine. While value of sign on the top of the stack is less than current speed, pop it and increase answer. If we overtake someone, we add $cnt$ to answer and assign $cnt$ to zero. Overall complexity: $O(n)$.
[ "data structures", "dp", "greedy" ]
1,800
null
845
E
Fire in the City
The capital of Berland looks like a rectangle of size $n × m$ of the square blocks of same size. Fire! It is known that $k + 1$ blocks got caught on fire ($k + 1 ≤ n·m$). Those blocks are centers of ignition. Moreover positions of $k$ of these centers are known and one of these stays unknown. All $k + 1$ positions are distinct. The fire goes the following way: during the zero minute of fire only these $k + 1$ centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner. Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of $k$ blocks (centers of ignition) are known and ($k + 1$)-th can be positioned in any other block. Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.
We can use binary search to find the answer. When binary searching, to check whether the whole city will be lightened up after $t$ minutes, we can use sweep line technique to find the smallest $x$-coordinate of the cell that is not lightened by $k$ centers of ignition (and the smallest $y$-coordinate too). Suppose that $x_{0}$ and $y_{0}$ are these coordinates; then we can place the last center of ignition at coordinates $(x_{0} + t, y_{0} + t)$. Then we can use sweep line again to check whether the city is fully ignited.
[ "binary search", "data structures" ]
2,400
null
845
F
Guards In The Storehouse
Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop. The storehouse can be represented as a matrix with $n$ rows and $m$ columns. Each element of the matrix is either . (an empty space) or x (a wall). Polycarp wants to hire some guards (possibly zero) to watch for the storehouse. Each guard will be in some cell of matrix and will protect every cell to the right of his own cell and every cell to the bottom of his own cell, until the nearest wall. More formally, if the guard is standing in the cell $(x_{0}, y_{0})$, then he protects cell $(x_{1}, y_{1})$ if all these conditions are met: - $(x_{1}, y_{1})$ is an empty cell; - either $x_{0} = x_{1}$ and $y_{0} ≤ y_{1}$, or $x_{0} ≤ x_{1}$ and $y_{0} = y_{1}$; - there are no walls between cells $(x_{0}, y_{0})$ and $(x_{1}, y_{1})$. \textbf{There can be a guard between these cells, guards can look through each other.} Guards can be placed only in empty cells (and can protect only empty cells). The plan of placing the guards is some set of cells where guards will be placed (of course, two plans are different if there exists at least one cell that is included in the first plan, but not included in the second plan, or vice versa). Polycarp calls a plan suitable if there is \textbf{not more than one} empty cell that is not protected. Polycarp wants to know the number of suitable plans. Since it can be very large, you have to output it modulo $10^{9} + 7$.
This problem can be solved using dynamic programming with broken profile. First of all, we have to make the number of rows not larger than $15$; if it is larger, then we can just rotate the given matrix. Let's fill the matrix from left to right, and in each column from top to bottom. Let $dp[pos][mask][f1][f2]$ be the number of ways to achieve the following situation: we now want to fill cell with index $pos$, $mask$ denotes the rows which are already protected in this column (so there is a wall in this row or there is a guard to the left), $f1$ is a flag that denotes if current cell is protected by some guard above, and $f2$ is a flag that denotes if there was a cell that was not protected. When advancing from one column to another, we have to change the mask so we update the rows that are currently protected. The rows such that in the previous column there was a wall in this row become un-protected, and the rows such that there is a wall in current column in this row become protected. And, of course, $f1$ becomes zero. When we place a guard, we set $f1$ to one and make the corresponding row protected. And when we are at the wall, we have to set $f1$ to zero, so the guard from above doesn't protect next cell. The answer is the sum of all $dp[n \cdot m][whatever][whatever][whatever]$ values.
[ "bitmasks", "dp" ]
2,500
null
845
G
Shortest Path Problem?
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex $1$ and vertex $n$. \textbf{Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.}
Let's find some path from $1$ to $n$. Let its length be $P$, then the answer to the problem can be represented as $P\oplus C$, where $C$ is the total length of some set of cycles in the graph (they can be disconnected; it doesn't matter because we can traverse the whole graph and return to the starting vertex with cost $0$). Let's treat each cycle's cost as a vector $(c_{0}, c_{1}, c_{2}...)$ where $c_{i}$ is the $i$-th bit in binary representation of cycle's cost. We can use Gaussian elimination to find the independent set of vectors that generates all these vectors. To do this, let's build any spanning tree of the graph, and then for any edge $(x, y)$ not belonging to the spanning tree we can try to add $d(x)\oplus w_{(x,y)}\oplus d(y)$ to the independent set ($d(x)$ is the length of the path from the root to $x$ in the spanning tree). When trying to add some vector, we firstly need to check if it can be represented as a combination of some vectors from the set, and only if it's impossible, then we add it to the set. The number of vectors in the set won't exceed $30$, so we can use Gaussian elimination to check if the vector is a combination of elements from the set. Then, after we found the basis, let's build the answer greedily from the most significant bit to the least: we will check if we can set the current bit so it is equal to the corresponding bit of $P$, while maintaining all the previous bit. To check it, we also can use Gaussian elimination.
[ "dfs and similar", "graphs", "math" ]
2,300
null
846
A
Curriculum Vitae
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced $n$ games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV. More formally, you are given an array $s_{1}, s_{2}, ..., s_{n}$ of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one. Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.
The statement literally asks for the longest subsequence which looks like $[0, 0, 0, ..., 1, 1, 1]$. Let's find out how many zeroes will be in this sequence and then take all ones which come after the last zero. On each step take the next zero from the beginning of the sequence and count ones after it. Update answer with the maximum value. You can precalc number of ones on suffix with partial sums but it was not necessary in this task. Overall complexity: $O(n^{2})$ (naively) or $O(n)$ (with partial sums).
[ "brute force", "implementation" ]
1,500
null
846
B
Math Show
Polycarp takes part in a math show. He is given $n$ tasks, each consists of $k$ subtasks, numbered $1$ through $k$. It takes him $t_{j}$ minutes to solve the $j$-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order. By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all $k$ of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is $k + 1$. Polycarp has $M$ minutes of time. What is the maximum number of points he can earn?
Constraints tell us that we can avoid making any weird assumptions for any greedy solutions. You can easily count the answer for some fixed amount of tasks completed. Just sort all left subtasks (but the longest to solve in each uncompleted task) and take the easiest till the time is over. Now you can iterate from $0$ to $n$ tasks completed and take maximum over all options. Overall complexity: $O(n^{2} \cdot k)$.
[ "brute force", "greedy" ]
1,800
null
846
C
Four Segments
You are given an array of $n$ integer numbers. Let $sum(l, r)$ be the sum of all numbers on positions from $l$ to $r$ non-inclusive ($l$-th element is counted, $r$-th element is not counted). For indices $l$ and $r$ holds $0 ≤ l ≤ r ≤ n$. Indices in array are numbered from $0$. For example, if $a = [ - 5, 3, 9, 4]$, then $sum(0, 1) = - 5$, $sum(0, 2) = - 2$, $sum(1, 4) = 16$ and $sum(i, i) = 0$ for each $i$ from $0$ to $4$. Choose the indices of three delimiters $delim_{0}$, $delim_{1}$, $delim_{2}$ ($0 ≤ delim_{0} ≤ delim_{1} ≤ delim_{2} ≤ n$) and divide the array in such a way that the value of $res = sum(0, delim_{0})$ - $sum(delim_{0}, delim_{1})$ + $sum(delim_{1}, delim_{2})$ - $sum(delim_{2}, n)$ is maximal. Note that some of the expressions $sum(l, r)$ can correspond to empty segments (if $l = r$ for some segment).
Imagine the same task but without the first term in sum. As the sum of the array is fixed, the best second segment should be the one with the greatest sum. This can be solved in $O(n)$ with partial sums. When recalcing the best segment to end at position $i$, you should take minimal prefix sum from $0$ to $i$ inclusive (from the whole sum you want to subtract the lowest number). Now let's just iterate over all possible ends of the first segment and solve the task above on the array without this segment. Oveall complexity: $O(n^{2})$.
[ "brute force", "data structures", "dp" ]
1,800
null
846
D
Monitor
Recently Luba bought a monitor. Monitor is a rectangular matrix of size $n × m$. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square $k × k$ consisting entirely of broken pixels. She knows that $q$ pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all $q$ pixels stopped working).
At first let's sort broken pixels in non-descending order by times they appear. Obviously, if the first $cnt$ broken pixels make monitor broken, $cnt + 1$ pixel won't fix it. Thus, binary search on answer will work. Let's search for the first moment in time when the monitor becomes broken. The function to check if in some moment $anst$ monitor is broken looks the following way. As we want to check if there is a submatrix of size $k \times k$, which consists only of broken pixels, let's precalc the array of partial sums $cnt$, $cnt_{i, j}$ is the number of broken pixels on submatrix from $(1, 1)$ to $(i, j)$. $cnt_{i, j}$ is calculated as ($1$ if $a_{i, j}$ is broken pixel, $0$ otherwise) $+ cnt_{i - 1, j} + cnt_{i, j - 1} - cnt_{i - 1, j - 1}$. Sum on submatrix of size $k \times k$ then looks like $cnt_{i, j} - cnt_{i - k, j} - cnt_{i, j - k} + cnt_{i - k, j - k}$. Check all possible $i$ and $j$ from $k$ to $n$ and find out if there exists submatrix with sum equal to $k \cdot k$. Overall complexity: $O(n^{2}\cdot\log{q})$.
[ "binary search", "data structures" ]
1,900
null
846
E
Chemistry in Berland
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange. Berland chemists are aware of $n$ materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each $i$ $(2 ≤ i ≤ n)$ there exist two numbers $x_{i}$ and $k_{i}$ that denote a possible transformation: $k_{i}$ kilograms of material $x_{i}$ can be transformed into $1$ kilogram of material $i$, and $1$ kilogram of material $i$ can be transformed into $1$ kilogram of material $x_{i}$. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is \textbf{always an integer number of kilograms}. For each $i$ ($1 ≤ i ≤ n$) Igor knows that the experiment requires $a_{i}$ kilograms of material $i$, and the laboratory contains $b_{i}$ kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Since $x_{i} < i$, then the transformation graph is a tree. Let's solve the problem recursively. Suppose that material $j$ is a leaf in the tree (there is no $y$ such that $x_{y} = j$). Then if we don't have enough material $j$, we have to transform some of material $x_{j}$ into $j$. Let's transform the amount required to set current amount of material $j$ to $a_{j}$; if we don't have the required amount of material $x_{j}$, then this amount will temporarily be negative. And if we have more material $j$ than we need to conduct the experiment, then we will transform it to $x_{j}$. The same algorithm can be applied to any non-root node, but we first need to do this for all its children. This algorithm is optimal because each time we take the minimum possible amount from the parent. After this the root will be the only node such that $a_{j}$ is not necessarily equal to current amount of material $j$. Since we solved the problem for all other materials and did it optimally, now the answer is YES iff current amount of material $1$ is not less than $a_{1}$. This must be implemented carefully. Since the total amount of materials never increases, then if some material's current amount is less than, for example, $- 2 \cdot 10^{17}$, then the answer is already NO. Also overflows in multiplication must be avoided; to do this, we can firstly check if the result of multiplication is not too big by multiplying values as real numbers.
[ "dfs and similar", "greedy", "trees" ]
2,300
null
846
F
Random Query
You are given an array $a$ consisting of $n$ positive integers. You pick two integer numbers $l$ and $r$ from $1$ to $n$, inclusive (numbers are picked randomly, equiprobably and independently). If $l > r$, then you swap values of $l$ and $r$. You have to calculate the expected value of the number of unique elements in segment of the array from index $l$ to index $r$, inclusive ($1$-indexed).
For each index $i$ we will find the number of pairs $(l, r)$ (before swapping) such that $i$ is the first occurence of $a_{i}$ in the chosen segment. Let $f(i)$ be previous occurence of $a_{i}$ before $i$ (if $i$ is the first occurence, then $f(i) = 0$ if we suppose the array to be $1$-indexed). Let's find the number of pairs such that $l \le r$, and then multiply it by $2$ and subtract $1$ for this index. $l$ has to be in segment $(f(i), i]$, and $r$ has to be in segment $[i, n]$, so the number of ways to choose this pair is $(i - f(i))(n - i + 1)$. The value we receive as the sum of these values over all segments is the total number of distinct elements over all pairs $(l, r)$, so we need to divide it by the number of these pairs.
[ "data structures", "math", "probabilities", "two pointers" ]
1,800
null