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
696
C
PLEASE
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts $n$ turns and Barney \textbf{independently choses} a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After $n$-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number $n$ of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array $a_{1}, a_{2}, ..., a_{k}$ such that \begin{center} $n=\prod_{i=1}^{k}a_{i},$ \end{center} in other words, $n$ is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction $p / q$ such that $\operatorname*{gcd}(p,q)=1$, where $\operatorname{gcd}$ is the greatest common divisor. Since $p$ and $q$ can be extremely large, you only need to find the remainders of dividing each of them by $10^{9} + 7$. Please note that we want $\operatorname{gcd}$ of $p$ and $q$ to be $1$, \textbf{not $\operatorname{gcd}$ of their remainders} after dividing by $10^{9} + 7$.
It gets tricky when the problem statement says $p$ and $q$ should be coprimes. A wise coder in this situation thinks of a formula to make sure this happens. First of all let's solve the problem if we only want to find the fraction $\overset{p}{q}$. Suppose $dp[i]$ is answer for swapping the cups $i$ times. It's obvious that $dp[1] = 0$. For $i > 0$, obviously the desired cup shouldn't be in the middle in $(i - 1) - th$ swap and with this condition the probability that after $i - th$ swap comes to the middle is $0.5$. That's why $d p[i]=(1-d p[i-1])*0.5={\frac{1{-}d p[i-1]}{2}}$. Some people may use matrix to find $p$ and $q$ using this dp (using pair of ints instead of floating point) but there's a risk that $p$ and $q$ are not coprimes, but fortunately or unfortunately they will be. Using some algebra you can prove that: if $n$ is even then $p={\frac{2^{n-1}+1}{3}}$ and $q = 2^{n - 1}$. if $n$ is odd then $p={\frac{2^{n-1}-1}{3}}$ and $q = 2^{n - 1}$. You can confirm that in both cases $p$ and $q$ are coprimes (since $p$ is odd and $q$ is a power of 2). The only thing left to handle is to find $2^{n}$ (or $2^{n - 1}$) and parity. Finding parity is super easy. Also $2^{n} = 2^{a1 \times a2 \times ... \times ak} = (...((2^{a1})^{a2})^{}...)^{ak}$. So it can be calculated using binary exponential. Also dividing can be done using Fermat's little theorem. Time complexity: $O(klg(MAX_A))$.
[ "combinatorics", "dp", "implementation", "math", "matrices" ]
2,000
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int mod = 1e9 + 7; inline int power(int a, ll b){ int ans = 1; while(b){ if(b & 1LL) ans = (1LL * ans * a) % mod; a = (1LL * a * a) % mod; b >>= 1; } return ans; } int main(){ int k; scanf("%d", &k); bool parity = 1, g = false; int x = 2; while(k--){ ll a; scanf("%lld", &a); if(a > 1) g = true; if(!(a & 1LL)) parity = 0; x = power(x, a); } if(!g){ cout << "0/1 "; return 0; } parity = !parity; x = (1LL * x * power(2, mod-2)) % mod; int y = (mod + x + (parity? 1: -1)) % mod; y = (1LL * y * power(3, mod-2)) % mod; cout << y << "/" << x << endl; return 0; }
696
D
Legen...
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is $0$. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows $n$ pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees $i$-th pickup line as a \textbf{consecutive subsequence} of Barney's text message her happiness level increases by $a_{i}$. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab. Due to texting app limits, Barney's text may have up to $l$ characters. Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
Build the prefix automaton of these strings (Aho-Corasick). In this automaton every state denotes a string which is prefix of one of given strings (and when we feed characters to it the current state is always the longest of these prefixes that is a suffix of the current string we have fed to it). Building this DFA can be done in various ways (fast and slow). Suppose these automaton has $N$ states ($N=O(|s_{1}|+\ldots+|s_{n}|)$) and state $v$ has edges outgoing to states in vector $neigh[v]$ (if we define our DFA as a directed graph). Suppose state number $1$ is the initial state (denoting an empty string). If $l$ was smaller we could use dp: suppose $dp[l][v]$ is the maximum score of all strings with length equal to $l$ ending in state $v$ of our DFA when fed into it. It's easy to show that $dp[0][1] = 0$ and $dp[1][v] \le b_{v} + dp[l + 1][u]$ for $u$ in $neigh[v]$ and calculating dps can be done using this (here $b_{v}$ is sum of $a$ of all strings that are a suffix of string related to state $v$). Now that $l$ is large, let's use matrix exponential to calculate the dp. Now dp is not an array, but a column matrix. Finding a matrix to update the dp is not hard. Also we need to reform + and * operations. In matrix multiplying we should use + instead of * and max instead of + in normal multiplication. Time complexity: $O(N^{3}l g(l))$.
[ "data structures", "dp", "matrices", "strings" ]
2,500
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 200 + 10; struct matrix{ ll a[maxn][maxn]; int n, m; matrix(){ n = m = 0; memset(a, -1, sizeof a); } matrix(int n, int m): n(n), m(m){ memset(a, -1, sizeof a); } inline void I(){ For(i,0,n) a[i][i] = 0; } inline matrix operator * (const matrix &x){ matrix ans(n, x.m); For(k,0,m) For(i,0,n) For(j,0,x.m) if(~a[i][k] && ~x.a[k][j]) smax(ans.a[i][j], a[i][k] + x.a[k][j]); return ans; } }; string s[maxn]; int tr[maxn][27], au[maxn][27], nx = 1, e[maxn], a[maxn], f[maxn], n; ll l; inline void add(int i){ int v = 0; rep(ch, s[i]){ int c = ch - 'a'; if(!tr[v][c]) tr[v][c] = nx ++; v = tr[v][c]; } e[v] += a[i]; } inline void ahoc(){ queue<int> q; q.push(0); while(!q.empty()){ int v = q.front(); q.pop(); if(f[v] != v) e[v] += e[f[v]]; For(i,0,26){ int u = tr[v][i]; if(u){ au[v][i] = u; if(v) f[u] = au[f[v]][i]; q.push(u); } else au[v][i] = au[f[v]][i]; } } } inline matrix power(matrix a, ll b){ matrix c(a.n, a.m); c.I(); while(b){ if(b & 1) c = c * a; a = a * a; b >>= 1; } return c; } int main(){ iOS; cin >> n >> l; For(i,0,n) cin >> a[i]; For(i,0,n){ cin >> s[i]; add(i); } ahoc(); matrix dp(nx, nx); For(v,0,nx) For(i,0,26) smax(dp.a[au[v][i]][v], (ll)e[au[v][i]]); dp = power(dp, l); matrix M(nx, 1); M.a[0][0] = 0; M = dp * M; ll ans = 0; For(i,0,nx) smax(ans, M.a[i][0]); cout << ans << endl; return 0; }
696
E
...Wait for it...
Barney is searching for his dream girl. He lives in NYC. NYC has $n$ junctions numbered from $1$ to $n$ and $n - 1$ roads connecting them. We will consider the NYC as a rooted tree with root being junction $1$. $m$ girls live in NYC, $i$-th of them lives along junction $c_{i}$ and her weight initially equals $i$ pounds. Barney consider a girl $x$ to be better than a girl $y$ if and only if: girl $x$ has weight strictly less than girl $y$ or girl $x$ and girl $y$ have equal weights and index of girl $x$ living junction index is strictly less than girl $y$ living junction index, i.e. $c_{x} < c_{y}$. Thus for any two girls one of them is always better than another one. For the next $q$ days, one event happens each day. There are two types of events: - Barney goes from junction $v$ to junction $u$. As a result he picks at most $k$ \textbf{best girls he still have not invited} from junctions on his way and invites them to his house to test if one of them is his dream girl. If there are less than $k$ not invited girls on his path, he invites all of them. - Girls living along junctions in subtree of junction $v$ (including $v$ itself) put on some weight. As result, their weights increase by $k$ pounds. Your task is for each event of first type tell Barney the indices of girls he will invite to his home in this event.
First of all, for each query of 1st type we can assume $k = 1$ (because we can perform this query $k$ times, it doesn't differ). Consider this problem: there are only queries of type 1. For solving this problem we can use heavy-light decomposition. If for a vertex $v$ of the tree we denote $a_{v}$ as the weight of the lightest girl in it ($ \infty $ in case there is no girl in it), for each chain in HLD we need to perform two type of queries: Get weight of the lightest girl in a substring (consecutive subsequence) of this chain (a subchain). Delete the lightest girl in vertex $u$. As the result only $a_{u}$ changes. We can find this value after changing in $O(1)$ if we have the sorted vector of girls' weights for each vertex (and then we pop the last element from it and then current last element is the lightest girl, $ \infty $ in case it becomes empty). This can be done using a classic segment tree. In each node we only need a pair of integers: weight of lightest girl in interval of this node and the vertex she lives in (a pair<int, int>). This works for this version of the problem. But for the original version we need an additional query type: 3. Increase weight of girls in a substring (consecutive subsequence) of this chain (a subchain) by $k$. This can be done using the previous segment tree plus lazy propagation (an additional value in each node, type 3 queries to pass to children). Now consider the original problem. Consider an specific chain: after each query of the first type on of the following happens to this chain: Nothing. Only an interval (subchain) is effected. Whole chain is effected. When case 2 happens, $v$ (query argument) belongs to this chain. And this can be done using the 3rd query of chains when we are processing a 2nd type query (effect the chain $v$ belongs to). When case 3 happens, $v$ is an ancestor of the topmost vertex in this chain. So when processing 1st type query, we need to know sum of $k$ for all 2nd type queries that their $v$ is an ancestor of topmost chain in current chain we're checking. This can be done using a single segment/Fenwick tree (using starting-finishing time trick to convert tree to array). So for each query of 1st type, we will check all chains on the path to find the lightest girl and delete her. Time Complexity: $O((n+q)l g^{2}(n))$
[ "data structures", "dsu", "trees" ]
3,000
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e5 + 10, maxl = 19; const ll inf = 1LL << 60; int st[maxn], ft[maxn], par[maxn][maxl], h[maxn], tim, sz[maxn], fst[maxn], stm[maxn], lst[maxn]; vi adj[maxn]; vi people[maxn]; typedef pair<ll, int> person; person emp(inf, -1); ll lz[maxn * 4], seg[maxn * 4]; person mn[maxn * 4]; int n, m, q; inline void DFS(int v = 0, int p = -1){ sz[v] = 1; rep(u, adj[v]) if(u - p){ DFS(u, v); sz[v] += sz[u]; } } inline void dfs(int v = 0, int p = -1, bool big = false){ fst[v] = (big? fst[p]: v); stm[tim] = v; st[v] = tim ++; par[v][0] = p; if(~p) h[v] = h[p] + 1; For(i,1,maxl) if(~par[v][i-1]) par[v][i] = par[par[v][i-1]][i-1]; int mx = 0, I = -1; For(i,0,adj[v].size()) if(adj[v][i] - p && mx < sz[adj[v][i]]) mx = sz[adj[v][i]], I = i; if(~I) rotate(adj[v].begin(), adj[v].begin() + I, adj[v].end()); For(i,0,adj[v].size()) if(adj[v][i] - p) dfs(adj[v][i], v, !i); ft[v] = tim; smax(lst[fst[v]], st[v]); } inline void addtree(int x, int y, int val, int id = 1, int l = 0, int r = n){ if(l >= y or x >= r) return ; if(x <= l && r <= y){ seg[id] += val; return ; } int mid = (l + r)/2; addtree(x, y, val, L(id), l, mid); addtree(x, y, val, R(id), mid, r); } inline ll asktree(int p, int id = 1, int l = 0, int r = n){ ll ans = seg[id]; if(r - l < 2) return ans; int mid = (l + r)/2; if(p < mid) ans += asktree(p, L(id), l, mid); else ans += asktree(p, R(id), mid, r); return ans; } inline void upd(int id, ll val){ lz[id] += val; mn[id].x += val; smin(mn[id], emp); } inline void shift(int id){ upd(L(id), lz[id]); upd(R(id), lz[id]); lz[id] = 0; } inline void build(int id = 1, int l = 0, int r = n){ if(r - l < 2){ mn[id] = emp; int v = stm[l]; if(!people[v].empty()) mn[id] = {people[v].back() + lz[id], l}; return ; } int mid = (l + r)/2; build(L(id), l, mid); build(R(id), mid, r); mn[id] = min(mn[L(id)], mn[R(id)]); } inline void add(int x, int y, int val, int id = 1, int l = 0, int r = n){ if(x >= r or l >= y) return ; if(x <= l && r <= y){ upd(id, val); return ; } int mid = (l + r)/2; shift(id); add(x, y, val, L(id), l, mid); add(x, y, val, R(id), mid, r); mn[id] = min(mn[L(id)], mn[R(id)]); } inline void set_element(int p, int id = 1, int l = 0, int r = n){ if(r - l < 2){ mn[id] = emp; int v = stm[l]; if(!people[v].empty()) mn[id] = {people[v].back() + lz[id], l}; return ; } int mid = (l + r)/2; shift(id); if(p < mid) set_element(p, L(id), l, mid); else set_element(p, R(id), mid, r); mn[id] = min(mn[L(id)], mn[R(id)]); } inline person ask(int x, int y, int id = 1, int l = 0, int r = n){ if(x >= r or l >= y) return emp; if(x <= l && r <= y) return mn[id]; int mid = (l + r)/2; shift(id); return min(ask(x, y, L(id), l, mid), ask(x, y, R(id), mid, r)); } inline int lca(int v, int u){ if(h[v] < h[u]) swap(v, u); rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]) v = par[v][i]; if(v == u) return v; rof(i,maxl-1,-1) if(par[v][i] - par[u][i]) v = par[v][i], u = par[u][i]; return par[v][0]; } inline person askchain(int v, int u){// u is ancestor of v //assert(fst[v] == fst[u]); ll val = asktree(st[fst[u]]); person ans = ask(st[u], st[v] + 1); ans.x += val; smin(ans, emp); return ans; } inline person hld(int v, int u){// us in ancestor of v auto ans = emp; while(fst[v] != fst[u]){ smin(ans, askchain(v, fst[v])); v = par[fst[v]][0]; } smin(ans, askchain(v, u)); return ans; } inline int erase(person p){ if(p.y == -1) return -1; int v = stm[p.y]; int ans = people[v].back(); people[v].PB; set_element(st[v]); return ans; } vector<int> anss; inline bool query(int v, int u, int w){ person p = min(hld(v, w), hld(u, w)); if(p.x == inf or p.y == -1) return false; anss.pb(erase(p)); return true; } inline void solve(int v, int u, int k){ int w = lca(v, u); anss.clear(); For(i,0,k) if(!query(v, u, w)) break ; printf("%d ", (int)anss.size()); rep(x, anss) printf("%d ", x); puts(""); } int main(){ memset(par, -1, sizeof par); fill(mn, mn + 4 * maxn, emp); scanf("%d %d %d", &n, &m, &q); For(i,1,n){ int v, u; scanf("%d %d", &v, &u); -- v, -- u; adj[v].pb(u), adj[u].pb(v); } For(i,1,m+1){ int v; scanf("%d", &v); -- v; people[v].pb(i); } For(i,0,n) reverse(all(people[i])); DFS(); dfs(); build(); while(q--){ int type, v, u, k; scanf("%d %d", &type, &v); if(type == 1){ scanf("%d %d", &u, &k); -- v, -- u; solve(v, u, k); } else{ scanf("%d", &k); -- v; addtree(st[v], ft[v], k); if(v != fst[v]) add(st[v], lst[fst[v]] + 1, k); } } return 0; }
696
F
...Dary!
Barney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of $n$ points. Like most of castles in Demonata worlds, this castle has no ceiling. Barney and Lyanna have an escape plan, but it requires some geometry knowledge, so they asked for your help. Barney knows that demons are organized and move in lines. He and Lyanna want to wait for the appropriate time so they need to watch for the demons. Each of them wants to stay in a point \textbf{inside the castle} (possibly on edges or corners), also they may stay in the same position. They both want to pick a real number $r$ and watch all points in the circles with radius $r$ around each of them (these two circles may overlap). We say that Barney and Lyanna are watching carefully if and only if for every edge of the polygon, at least one of them can see at least one point on the line this edge lies on, thus such point may not be on the edge but it should be on edge's line. Formally, each edge line should have at least one common point with at least one of two circles. The greater $r$ is, the more energy and focus they need. So they asked you to tell them the minimum value of $r$ such that they can watch carefully.
In the first thoughts you see that there's definitely a binary search needed (on $r$). Only problem is checking if there are such two points fulfilling conditions with radius $r$. For each edge, we can shift it $r$ units inside the polygon (parallel to this edge). The only points that can see the line coinciding the line on this edge are inside the half-plane on one side of this shifted line (side containing this edge). So problem is to partition these half-planes in two parts such that intersection of half-planes in each partition and the polygon (another $n$ half-planes) is not empty. There are several algorithms for this propose: $O(n^{3})$ Algorithm: It's obvious that if intersection of some half-planes is not empty, then there's at least on point inside this intersection that is intersection of two of these lines (lines denoting these half-planes). The easiest algorithm is to pick any intersection of these $2n$ lines ($n$ shifted half-planes and $n$ edges of the polygon) like $p$ that lies inside the polygon, delete any half-plane containing this point (intersection of deleted half-planes and polygon is not empty because it contains at least $p$) and check if the intersection of half-planes left and polygon is not empty (of course this part needs sorting half-planes and adds an additional $log$ but we can sort the lines initially and use something like counting sort in this step). Well, constant factor in this problem is too big and this algorithm will not fit into time limit. But this algorithm will be used to prove the faster algorithm: $O(n^{2})\,$ Algorithm: In the previous algorithm we checked if $p$ can be in intersection of one part. Here's the thing: Lemma 1: If $p$ is inside intersection of two half-planes ($p$ is not necessarily intersection of their lines) related to $l - th$ and $r - th$ edge ($l < r$) and two conditions below are fulfilled, then there's no partitioning that in it $p$ is inside intersection of a part (and polygon): At least one of the half-planes related to an edge with index between $l$ and $r$ exists that doesn't contain $p$. At least one of the half-planes related to an edge with index greater than $r$ or less than $l$ exists that doesn't contain $p$. Because if these two lines exist, they should be in the other part that doesn't contain $p$ and if they are, intersection of them and polygon will be empty(proof is easy, homework assignment ;)). This proves that if such partitioning is available that $p$ is in intersection of one of them, then it belongs to an interval of edges(cyclic interval) and the rest are also an interval (so intersection of both intervals with polygon should be non-empty). Thus, we don't need $p$ anymore. We only need intervals! Result is, if such partitioning exists, there are integers $l$ and $r$ ($1 \le l \le r \le n$) such that intersection of half-planes related to $l, l + 1, ..., r$ and polygon and also intersection of half-planes related to $r + 1, r + 2, ..., n, 1, 2, ..., l - 1$ and polygon are both non-empty. This still gives an $O(n^{3})$ algorithm (checking every interval). But this lemma comes handy here: We call an interval(cyclic) good if intersection of lines related to them and polygon is non-empty. Lemma 2: If an interval is good, then every subinterval of this interval is also good. Proof is obvious. That gives and idea: Denote $interval(l, r)$ is a set of integers such that: If $l \le r$, then $interval(l, r) = {l, l + 1, ..., r}$ If $l \le r$, then $interval(l, r) = {r, r + 1, ..., n, 1, ..., l}$ (In other words it's a cyclic interval) Also $MOD(x)$ is: $x$ iff $x \le n$ $MOD(x - n)$ iff $x > n$ (In other words it's modulo $n$ for 1-based) The only thing that matters for us for every $l$, is maximum $len$ such that $interval(l, MOD(l + len))$ is good (because then all its subintervals are good). If $l_{i}$ is maximum $len$ that $interval(i, MOD(i + len))$ is good, we can use 2-pointer to find values of $l$. Lemma 3: $l_{MOD(i + 1)} \ge l_{i} - 1$. Proof is obvious in result of lemma 2. Here's a pseudo code: check(r): len = 0 for i = 1 to n: while len < n and good(i, MOD(i+len)): // good(l, r) returns true iff interval(l, r) is good len = len + 1 if len == 0: return false // Obviously if len == n: return true // Barney and Lyanna can both stay in the same position l[i] = len for i = 1 to n: if l[i] + l[MOD(i+l[i])] >= n: return true return false$good$ function can be implemented to work in ${\cal O}(n)$ (with sorting as said before). And 2-pointer makes the calls to $good$ to be ${\mathcal{O}}(n)$. So the total complexity to check an specific $r$ is $O(n^{2})\,$. Time Complexity: $O(n^{2}l g(M A X_{-}C O O R D I N A T E))$
[ "binary search", "geometry", "two pointers" ]
3,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define X first #define Y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef pair<double, double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} inline point operator - (const point &p, const point &q){return point(p.x - q.x, p.y - q.y);} inline point operator + (const point &p, const point &q){return point(p.x + q.x, p.y + q.y);} inline point operator * (const point &p, const point &q){return point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);} inline point operator * (const point &p, const double &d){return point(p.x*d, p.y*d);} inline point operator * (const double &d, const point &p){return point(p.x*d, p.y*d);} inline point operator / (const point &p, const double &d){return point(p.x/d, p.y/d);} inline double abs(const point &p){ return sqrt(p.X * p.X + p.Y * p.Y); } const int maxn = 300 + 100; int len[maxn]; const double eps = 1e-12, inf = 1e10; pii pol[maxn]; inline short sign(double a) { return abs(a) < eps ? 0 : (a < 0? -1:1) ; } inline point unit(point p){ return p/ abs(p); } inline double cross(point a, point b){ return a.X * b.Y - a.Y * b.X; } inline double dot(point a, point b){ return a.x * b.x + a.y * b.y; } inline double arg(const point &p){ complex<double> c(p.x, p.y); return arg(c); } inline point inter(point a, point b, point c, point d){ return a + (b-a) * (cross(c-a, d-c)/cross(b-a, d-c)); } inline point shift(point p, double x){ return x * unit(p) * point(0, 1); } inline double getAlpha( point a , point b , point c , point d ) { point cd = d - c; return cross( c-a , cd ) / cross( b - a , cd ); } inline bool sect(point a, point b, point c, point d){ double alpha = getAlpha(a, b, c, d); return -eps <= alpha && alpha <= 1 + eps; } inline point proj(const point &a, const point &b){ // projection of b on o-a return a * dot(a, b) / dot(a, a); } inline double dis(const point &a, const point &b, const point &c){ point h = b + proj(a-b, c-b); return abs(h - c); } int n; point p[maxn * 2], q[maxn * 2]; int perm[maxn * 2]; point que[maxn * 2]; int st, en; inline point mult(const point &p, double d){ return p * d; return point(sign(p.X) * d * abs(p.X), sign(p.Y) * d * abs(p.Y)); } inline bool add(int i){ auto x = p[i], y = q[i]; point c = x + mult(unit( y - x ), -inf); point d = x + mult(unit( y - x ), inf); if(st == en){ que[en ++] = c; que[en ++] = d; return true; } while(en > 1 && sign(cross(unit(y-x), que[en-2]-c)) <= 0){ -- en; } if(en == 1) return false; if( sign(cross( unit(que[en-1] - que[en-2]) , unit(d-c) )) == 0 ) return true; que[en-1] = inter(que[en-2], que[en-1], x, y); que[en ++] = d; return true; } inline bool relax(){ For(i,0,n) p[i] = point(pol[i]); while(en - st > 3 && sign(cross(que[en-1] - que[en-2], que[st+1] - que[en-2])) <= 0) ++ st; while(en - st > 3 && sign(cross(que[st+1] - que[st] , que[en-2] - que[st])) <= 0) -- en; if(!sign(cross( que[st+1] - que[st] , que[en-1] - que[en-2] ))) return 1; que[st] = inter(que[st], que[st+1], que[en-2], que[en-1]); -- en; } inline bool canDo(int l, int r){ en = st = 0; For(j,0,2*n){ int i = perm[j]; if(i < n or (l <= i-n && i-n <= r) or (l > r && (i-n <= r or l <= i-n))){ bool flag = add(i); if(!flag) return false; } } return true; } point c1, c2; inline bool cmp(const int &i, const int &j){ point a = q[i] - p[i]; point b = q[j] - p[j]; if (sign(a.X) >= 0 && sign(b.X) < 0) return false; if (sign(a.X) < 0 && sign(b.X) >= 0) return true; if (sign(a.X) == 0 && sign(b.X) == 0){ if (sign(a.Y) >= 0 || sign(b.Y) >= 0) return a.Y < b.Y; return b.Y < a.Y; } double det = a.X * b.Y - b.X * a.Y; if (sign(det) < 0) return false; if (sign(det) > 0) return true; int S = sign(cross(q[j] - p[j], q[i] - p[j])); if(S) return S > 0; double d1 = a.X * a.X + a.Y * a.Y; double d2 = b.X * b.X + b.Y * b.Y; return d1 < d2; } inline bool checker(point C1, point C2, double r){ For(i,0,n){ int j = (i + 1) % n; if(cross(p[j] - p[i], C1 - p[i]) < -1e-5) return false; if(cross(p[j] - p[i], C2 - p[i]) < -1e-5) return false; if(min(dis(p[i], p[j], C1), dis(p[i], p[j], C2)) > r + 1e-6) return false; } return true; } inline bool check(double x, bool cer = false){ For(i,0,n){ int j = (i + 1) % n; perm[i] = i; perm[i + n] = i + n; p[i] = point(pol[i].x, pol[i].y); q[i] = point(pol[j].x, pol[j].y); point s = shift(q[i] - p[i], x); q[i + n] = p[i] + s; p[i + n] = q[i] + s; } sort(perm, perm + 2 * n, cmp); fill(len, len + n, 0); int l = 0; For(i,0,n){ while(l < n && canDo(i, (i+l)%n)) ++ l; if(l < 1) return false; if(l == n){ if(cer){ relax(); For(j,st,en) if(checker(que[j], que[j], x)){ c1 = c2 = que[j]; return true; } return false; } return true; } len[i] = l; -- l; } For(i,0,n){ int j = (i + len[i]) % n; if(len[i] + len[j] >= n){ if(cer){ canDo(i,(j-1+n) % n); relax(); vector<point> V; For(e,st,en) V.pb(que[e]); canDo(j, (i-1+n) % n); relax(); do{ c1 = V[rand() % (int)V.size()]; c2 = que[st + rand() % (en-st)]; }while(!checker(c1, c2, x)); } return true; } } return false; } int main(){ iOS; cerr << fixed << setprecision(10); cin >> n; For(i,0,n) cin >> pol[i].x >> pol[i].y; double lo = 0, hi = 2e4 + 100; while(hi - lo > 1e-7){ double mid = (lo + hi)/2.; if(check(mid)) hi = mid; else lo = mid; } cout << fixed << setprecision(30); cout << lo << endl; error(check(lo + 2e-7, true)); cout << c1.X << ' ' << c1.Y << ' '; cout << c2.X << ' ' << c2.Y << endl; return 0; }
697
A
Pineapple Incident
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time $t$ (in seconds) it barks for the first time. Then every $s$ seconds after it, it barks twice with $1$ second interval. Thus it barks at times $t$, $t + s$, $t + s + 1$, $t + 2s$, $t + 2s + 1$, etc. Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time $x$ (in seconds), so he asked you to tell him if it's gonna bark at that time.
You should check two cases for YES: $x mod s = t mod s$ and $t \le x$ $x mod s = (t + 1) mod s$ and $t + 1 < x$ Time Complexity: $O(1)$
[ "implementation", "math" ]
900
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} int main(){ iOS; int t, s, x; cin >> t >> s >> x; cout << (((x >= t && x % s == t % s) or(x > t + 1 && x % s == (t + 1) % s)) ? "YES": "NO") << endl; return 0; }
697
B
Barnicle
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number $x$ is the notation of form $AeB$, where $A$ is a real number and $B$ is an integer and $x = A × 10^{B}$ is true. In our case $A$ is between $0$ and $9$ and $B$ is non-negative. Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.
Nothing special, right? just find the position of letters . and e with string searching methods (like .find) and do the rest. Time Complexity: ${\cal O}(n)$
[ "brute force", "implementation", "math", "strings" ]
1,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1000 + 10; string s; string t; int b; int main(){ iOS; cin >> s; int e = s.find('e'); For(i,e+1,s.size()) b = 10 * b + s[i] - '0'; t += s[0]; For(i,2,e) t += s[i]; vector<char> v; while(t.size() < b + 1) t += '0'; For(i,0,b+1) v.pb(t[i]); v.pb('.'); For(i,b+1,t.size()) v.pb(t[i]); while(v.back() == '0') v.PB; if(v.back() == '.') v.PB; rep(c, v) cout << c; cout << endl; return 0; }
698
A
Vacations
Vasya has $n$ days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this $n$ days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the $i$-th day there are four options: - on this day the gym is closed and the contest is not carried out; - on this day the gym is closed and the contest is carried out; - on this day the gym is open and the contest is not carried out; - on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
This problem can be solved with dynamic programming. Let's solve the opposite problem and find the maximum number of days which Vasya will not have a rest. We need o use two-dimensional array $d$, where $d[i][j]$ equals to the maximum number of days, which Vasya will not have a rest, if $i$ days passed and $j$ equals to: 0, if Vasya had a rest during the $i$-th day, 1, if Vasya participated in the contest on the $i$-th day, 2, if Vasya went to gym on the $i$-th day. Then the transitions for the day number $i$ look like: $d[i][0]$ must be updated with maximum value of the array $d$ for the previous day; if there will be a contest on the $i$-th day (i. e. $a_{i}$ equals to $1$ or $3$), than we update $d[i][1]$ with values $d[i - 1][0] + 1$ and $d[i - 1][2] + 1$; if the gym is open on the $i$-th day (i. e. $a_{i}$ equals to $2$ or $3$), than we update $d[i][2]$ with values $d[i - 1][0] + 1$ and $d[i - 1][1] + 1$. After that we need to choose $max$ from all values of the array $d$ for the last day and print $n - max$.
[ "dp" ]
1,400
null
698
B
Fix a Tree
A tree is an undirected connected graph without cycles. Let's consider a rooted undirected tree with $n$ vertices, numbered $1$ through $n$. There are many ways to represent such a tree. One way is to create an array with $n$ integers $p_{1}, p_{2}, ..., p_{n}$, where $p_{i}$ denotes a parent of vertex $i$ (here, for convenience a root is considered its own parent). \begin{center} {\small For this rooted tree the array $p$ is $[2, 3, 3, 2]$.} \end{center} Given a sequence $p_{1}, p_{2}, ..., p_{n}$, one is able to restore a tree: - There must be exactly one index $r$ that $p_{r} = r$. A vertex $r$ is a root of the tree. - For all other $n - 1$ vertices $i$, there is an edge between vertex $i$ and vertex $p_{i}$. A sequence $p_{1}, p_{2}, ..., p_{n}$ is called valid if the described procedure generates some (any) rooted tree. For example, for $n = 3$ sequences (1,2,2), (2,3,1) and (2,1,3) \textbf{are not} valid. You are given a sequence $a_{1}, a_{2}, ..., a_{n}$, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
One can easily see that given sequence describes a functional graph, thus a directed graph with edges going from $i$ to $a_{i}$ for every $i$. This graph represents a set of cycles and each cycle vertex is a root of its own tree (possibly consisting of one vertex). Picture above shows an example of a functional graph. It consists of two cycles $1, 6, 3$ and $4$. Vertex $6$ is the root of the tree consisting of vertices $0$, $2$, $6$ and $8$, vertex $3$ roots the tree of vertices $3$ and $5$, vertex $4$ - root of tree of vertices $4$ and $7$ and vertex $1$ forms a tree of only one vertex. In terms of functional graph, our goal is to make the graph consisting of exactly one cycle of exactly one vertex looped to itself. Operation of change is equivalent to removing some outgoing edge and adding a new one, going to somewhat else vertex. Let's firstly make our graph containing only one cycle. To do so, one can choose any of initially presented cycles and say that it will be the only one. Then one should consider every other cycle, remove any of its in-cycle edges and replace it with an edge going to any of the chosen cycle's vertices. Thus the cycle will be broken and its vertices (along with tree ones) will be connected to the only chosen cycle. One will need to do exactly $cycleCount - 1$ such operations. Note that the removing of any non-cycle edge does not make sense, because it does not break any cycle. The next thing is to make the cycle length be equal to $1$. That might be already satisfied, if one will choose a cycle of minimal length and this length equals $1$. Thus, if the initial graph contains any cycle of length $1$, we are done with $cycleCount - 1$ operations. Otherwise, the cycle contains more than one vertex. It can be fixed with exactly one operation - one just need to break any of in-cycle edges, say from $u$ to $a_{u}$, and add an edge from $u$ to $u$. The graph will remain consisting of one cycle, but consisting of one self-looped vertex. In that case, we are done with $cycleCount$ operations. To do all the operations above, one can use DSU structure, or just a series of DFS. Note that there is no need in realisation of edge removing and creating, one just needs to analyze initial graph.
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "trees" ]
1,700
null
699
A
Launch of Collider
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. $n$ particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, $x_{i}$ is the coordinate of the $i$-th particle and its position in the collider at the same time. All coordinates of particle positions are \textbf{even integers}. You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of $1$ meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time. Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
To solve this problem it is enough to look at all pairs of adjacent particles such that the left particle will move to the right and the right particle will move to the left. If there is no such pair the answer is -1. Otherwise, let's iterate through the particles from the left to the right. If the particle $i$ will move to the right and the particle $i + 1$ will move to the left we know that this particles will be at the same point simultaneously, so we need to update the answer with value $(x_{i + 1} - x_{i}) / 2$. The answer is always integer because all coordinates of the particles are even numbers.
[ "implementation" ]
1,000
null
699
B
One Bomb
You are given a description of a depot. It is a rectangular checkered field of $n × m$ size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell $(x, y)$, then after triggering it will wipe out all walls in the row $x$ and all walls in the column $y$. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering \textbf{exactly one bomb}. The bomb can be laid both in an empty cell or in a cell occupied by a wall.
To solve this problem we need to calculate two arrays $V[]$ and $G[]$, where $V[j]$ must be equal to the number of walls in the column number $j$ and $G[i]$ must be equal to the number of walls in the row number $i$. Also let's store the total number of walls in the variable $cur$. Now we need to look over the cells. Let the current cell be $(x, y)$. Let's count the value $cur$ - how many walls will destroy the bomb planted in the cell $(x, y)$: $cnt = V[y] + G[x]$. If the cell $(x, y)$ has a wall we count it twice, so we need to subtract $1$ from the $cnt$. If $cur = cnt$ we found the answer and need to plant the bomb in the cell $(x, y)$. If there is no such cell we need to print "NO".
[ "implementation" ]
1,400
null
700
A
As Fast As Possible
On vacations $n$ pupils decided to go on excursion and gather all together. They need to overcome the path with the length $l$ meters. Each of the pupils will go with the speed equal to $v_{1}$. To get to the excursion quickly, it was decided to rent a bus, which has seats for $k$ people (it means that it can't fit more than $k$ people at the same time) and the speed equal to $v_{2}$. In order to avoid seasick, each of the pupils want to get into the bus \textbf{no more than once}. Determine the minimum time required for all $n$ pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
This problem can be solved with formula or with help of the binary search. Let's describe the solution with binary search on the answer. If the target function of the binary search returns $true$ we need to move in mid the right end of the search, else we need to move in mid the left end of the search. The target function must works in the following way. Let's divide all pupils on the groups, the number of the groups equals to $(n + k - 1) / k$, where $n$ is the total number of pupils and $k$ is the number of seats in the bus. Then for the current $mid$ we know the minimal time which the first group of the pupils is needed to ride on the bus to reach the finish point in the time $mid$. Then we need to solve simple equation and get that this time equals to $T - (v2 \cdot T - (l - posM)) / (v2 - v1)$, where for the first group $T$ equals to $mid$, $posM$ equals to 0 (in $posM$ we will store the position of the pupils, who did not already rode on the bus). Than we need to accurate recalculate $T$ and $posM$ for every following group (do not forget that the bus must returns back to get the other group). If for some group $v2 \cdot T$ became less than $l - posM$ or $T$ became less than $0$, the target function must return $false$. If all groups of pupils will reach the finish point in time $mid$ the target function must return $true$. Also do not forget that the bus does not need to ride back after it took to the needed point the last group of the pupils.
[ "binary search", "math" ]
1,900
null
700
B
Connecting Universities
Treeland is a country in which there are $n$ towns connected by $n - 1$ two-way road such that it's possible to get from any town to any other town. In Treeland there are $2k$ universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in $k$ pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to $1$.
Let's root a tree with vertex $1$ by single DFS and by the way find two values for every vertex $v$: $lv$ - length of the edge that leads from parent of $v$ to vertex $v$; $sv$ - the number of universities in the subtree of vertex $v$ (including $v$ itself). Consider any optimal solution, i.e. such solution that the total length is maximum. Look at some edge that leads from the parent of $v$ to $v$. We claim that it should be used in $min(s_{v}, 2 \cdot k - s_{v})$ paths. It obviously cannot be used more time than this value, however, if it is used less number of times, that means there is at least one connected pair (let's say $a$ and $b$) located in the subtree of $v$ and at least one connected pair located outside (vertices $c$ and $d$). By the properties of the tree, paths from $a$ to $c$ and from $b$ to $d$ cover all edges of the paths from $a$ to $b$ and from $c$ to $d$ plus some extra edges, meaning the current answer is not optimal. Thus, this edge will be used exactly $min(s_{v}, 2 \cdot k - s_{v})$ times. The above means we can compute the answer value as $\sum_{v\in V}m i n(s_{v},2\cdot k-s_{v})$. Note that the above method doesn't provide the optimal matching itself (though, not many modifications required).
[ "dfs and similar", "dp", "graphs", "trees" ]
1,800
null
701
A
Cards
There are $n$ cards ($n$ is \textbf{even}) in the deck. Each card has a positive integer written on it. $n / 2$ people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
Because of it is guaranteed, that the answer always exists, we need to sort all cards in non-descending order of the numbers, which are written on them. Then we need to give to the first player the first and the last card from the sorted array, give to the second player the second and the penultimate cards and so on.
[ "greedy", "implementation" ]
800
null
701
B
Cells Not Under Attack
Vasya has the square chessboard of size $n × n$ and $m$ rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another. The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack. You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are \textbf{not under attack} after Vasya puts it on the board.
To solve this problem we will store two sets - the set of the verticals, in which there is at least one rook, and the set of the horizontals, in which there is at least one rook. We need to iterate through the rooks in the order of we put them on the board and calculate the number of the cells under attack, after put each rook. Let we put current rook in the cell $(x, y)$. We need to add $y$ in the set of verticals and add $x$ in the set of horizontals. Let after it the size of set with verticals equals to $szY$ and the size of set with horizontals equals to $szX$. Then it is easy to show, that the number of the cells under attack equals to $cnt = szY \cdot n + szX \cdot n - szX \cdot szY$, so, the number of cells which are not under attack equals to $n \cdot n - cnt$.
[ "data structures", "math" ]
1,200
null
701
C
They Are Everywhere
Sergei B., the young coach of Pokemons, has found the big house which consists of $n$ flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number $1$ is only connected with the flat number $2$ and the flat number $n$ is only connected with the flat number $n - 1$. There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
At first let's find all different letters, which exist in the given string. It can be done with help of the array with letters or with help of the set. Then we need to use the array $len$, where $len[i]$ equals to minimal length of the substring, which ends in the position $i$ and contains all different letters from the given string. If for some position $i$ there is no such a substring, we will store in the $len[i]$ some big number, which more than the length of the given string, for example, $10^{9}$. Now we need to iterate through all different letters of the string in any order. Let the current letter equals to $c$. Let's iterate on the positions of the given string from the left to the right and will store in the variable $last$ the last position of the string $s$ in which $s[last] = c$. At first $last = - 1$. Let the current position of the given string equals to $i$. If $s[i] = c$ we need to make $last = i$. If for current position $i$ the value of the $last$ equals to $- 1$ we need to make $len[i] = 10^{9}$ (because there is no substring which ends in the position $i$ and contains all different letters of the given string $s$). In the other case, we need to update $len[i] = max(len[i], i - last + 1)$. The answer is the minimal value from all values of the array $len$ after we iterated through all different letters of the given string $s$.
[ "binary search", "strings", "two pointers" ]
1,500
null
702
A
Maximum Increase
You are given array consisting of $n$ integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray \textbf{strictly greater} than previous.
Let's iterate through the given array from the left to the right and store in the variable $cur$ the length of the current increasing subarray. If the current element is more than the previous we need to increase $cur$ on one. In the other case we need to update the answer with the value of $cur$ and put in $cur$ 1, because new increasing subarray began.
[ "dp", "greedy", "implementation" ]
800
null
702
B
Powers of Two
You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Find the number of pairs of indexes $i, j$ ($i < j$) that $a_{i} + a_{j}$ is a power of $2$ (i. e. some integer $x$ exists so that $a_{i} + a_{j} = 2^{x}$).
To solve this problem we need to use map $cnt$ and store in this map how many times every integer appears in the given array. Then we need to iterate through all given numbers with variable $i$. Let the current number is equal to $a_{i}$. For this number we need to iterate on all possible powers of 2 (the number of these powers is no more than 31). Let the current power is equal to $cur$. Then we need to make $cnt[a_{i}] -$ and add the value $cnt[a_{i} - cur]$ to the asnwer.
[ "brute force", "data structures", "implementation", "math" ]
1,500
null
702
C
Cellular Network
You are given $n$ points on the straight line — the positions ($x$-coordinates) of the cities and $m$ points on the same line — the positions ($x$-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than $r$ from this tower. Your task is to find minimal $r$ that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than $r$. If $r = 0$ then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than $r$ from this tower.
At first store coordinates of all towers in set $towers$. Then let's look through all cities. Let the current city be located in the point $cur$. Let $it = towers.lower_{bound}(cur)$. Then if $it$ is not equal to the end of the set we put in the variable $dist$ the value $( * it - cur)$ - the distance to the nearest tower on the right for the current city. If $it$ is not equal to the beginning of the set we need to make $it -$ and update $dist = min(dist, cur - * it)$ - the distance to the nearest tower on the left to the current city. After that we only need to update the answer: $ans = max(ans, dist)$. Also this problem can be solved with help of two pointers in linear time.
[ "binary search", "implementation", "two pointers" ]
1,500
null
702
D
Road to Post Office
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to $d$ kilometers. Vasiliy's car is not new — it breaks after driven every $k$ kilometers and Vasiliy needs $t$ seconds to repair it. After repairing his car Vasiliy can drive again (but after $k$ kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station. To drive one kilometer on car Vasiliy spends $a$ seconds, to walk one kilometer on foot he needs $b$ seconds ($a < b$). Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.
To solve this problem we need to analyze some cases. If $d \le k$ then Vasiliy can ride car all road without breaking, so the answer is $d * a$. If $t + k * a > k * b$ (i. e. it is better to do not repair the car), Vasiliy must ride car the first $k$ kilometers and then walks on foot, so the answer is $k * a + (d - k) * b$. The only case left when it is better to ride car through all road until $d % k$ kilometers left. Now we need to understand what better - repair the car and ride or do not repair the car and walk on foot. Let $cnt = d / k$, so Vasiliy necessarily must repair the car $cnt - 1$ times. Then the answer equals to $k * cnt * a + (cnt - 1) * t + min(t + (d % k) * a, (d % k) * b)$.
[ "math" ]
1,900
null
702
E
Analysis of Pathes in Functional Graph
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from $0$ to $n - 1$. Graph is given as the array $f_{0}, f_{1}, ..., f_{n - 1}$, where $f_{i}$ — the number of vertex to which goes the only arc from the vertex $i$. Besides you are given array with weights of the arcs $w_{0}, w_{1}, ..., w_{n - 1}$, where $w_{i}$ — the arc weight from $i$ to $f_{i}$. \begin{center} {\small The graph from the first sample test.} \end{center} Also you are given the integer $k$ (the length of the path) and you need to find for each vertex two numbers $s_{i}$ and $m_{i}$, where: - $s_{i}$ — the sum of the weights of all arcs of the path with length equals to $k$ which starts from the vertex $i$; - $m_{i}$ — the minimal weight from all arcs on the path with length $k$ which starts from the vertex $i$. The length of the path is the number of arcs on this path.
This problem can be solved with help of the binary exponentiation. Let the $f_{r}[u]$ is a structure, which for the vertex $u$ store the information about the path from this vertex with length equals to $r$. The information which we need: $f_{r}[u].to$ - the number of vertex, in which ends the path with length $r$ from the vertex $u$, $f_{r}[u].len$ - the sum of the arcs weights on the path with length $r$ from the vertex $u$, $f_{r}[u].min$ - the minimal weight of the arc on the path with length $r$ from the vertex $u$. So if we have this values for all vertices and two fixed values $r$: $r = r_{1}$ and $r = r_{2}$ it is easy to find the values $f_{r1 + r2}[u]$ for all $u$: $f_{r1 + r2}[u].to = f_{r2}[f_{r1}[u].to].to$, i. e. at first we went to the vertex $f_{r1}[u].to$, and then with help of the array $f_{r2}$ we can undrstand where we will stand in the end of the path; $f_{r1 + r2}[u].len = f_{r1}[u].len + f_{r2}[f_{r1}[u].to].len$; $f_{r1 + r2}[u].min = min(f_{r1}[u].min, f_{r2}[f_{r1}[u].to].min)$. The structures for the values $r = r_{1}$ and $r = r_{2}$ are and arrays of the structures, indexed with numbers of the graph vertices. So we showed that if we have two arrays for $r = r_{1}$ and $r = r_{2}$ we can get the array for $r = r_{1} + r_{2}$. The operation which we described above we can call the multiply of the arrays, then the needed values $f_{k}$ can be found with help of raised values $f_{1}$ to the power $k$. For make it we can use the binary exponentiation. Also this problem can be solved with help of "binary shifts", but in fact it is the same thing that we described above.
[ "data structures", "graphs" ]
2,100
null
703
A
Mishka and Game
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds $n$ is defined. In every round each of the players throws a cubical dice with distinct numbers from $1$ to $6$ written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner. In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw. Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!
In this problem you had to do use the following algo. If Mishka wins Chris in the current round, then increase variable $countM$ by 1. Otherwise (if Chris wins Mishka) increase variable $countC$. After that you had to compare this values and print the answer.
[ "implementation" ]
800
null
703
B
Mishka and trip
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country. Here are some interesting facts about XXX: - XXX consists of $n$ cities, $k$ of whose (just imagine!) are capital cities. - All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of $i$-th city equals to $c_{i}$. - All the cities are consecutively connected by the roads, including $1$-st and $n$-th city, forming a cyclic route $1 — 2 — ... — n — 1$. Formally, for every $1 ≤ i < n$ there is a road between $i$-th and $i + 1$-th city, and another one between $1$-st and $n$-th city. - Each capital city is connected with each other city directly by the roads. Formally, if city $x$ is a capital city, then for every $1 ≤ i ≤ n, i ≠ x$, there is a road between cities $x$ and $i$. - There is \textbf{at most one} road between any two cities. - Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities $i$ and $j$, price of passing it equals $c_{i}·c_{j}$. Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing \textbf{each of the roads} in XXX. Formally, for every pair of cities $a$ and $b$ ($a < b$), such that there is a road between $a$ and $b$ you are to find sum of products $c_{a}·c_{b}$. Will you help her?
Let's look at the first capital. Note that the total cost of the outgoing roads is $c[id_{1}] \cdot (sum - c[id_{1}])$, where $sum$ - summary beauty of all cities. Thus iterating through the capitals we can count the summary cost of roads between capitals and all the other cities. But don't forget that in this case we count the roads between pairs of capitals twice. To avoid this on each step we should update $sum = sum - c[id_{cur}]$, where $id_{cur}$ is the position of current capital. In the end we should add to the answer the cost of roads between "non-capital" neighbour cities. Complexity - $O(n)$.
[ "implementation", "math" ]
1,400
null
703
C
Chris and Road
And while Mishka is enjoying her trip... Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend. Once walking with his friend, John gave Chris the following problem: At the infinite horizontal road of width $w$, bounded by lines $y = 0$ and $y = w$, there is a bus moving, presented as a convex polygon of $n$ vertices. The bus moves continuously with a constant speed of $v$ in a straight $Ox$ line in direction of decreasing $x$ coordinates, thus in time \textbf{only $x$ coordinates} of its points are changing. Formally, after time $t$ each of $x$ coordinates of its points will be decreased by $vt$. There is a pedestrian in the point $(0, 0)$, who can move only by a vertical pedestrian crossing, presented as a segment connecting points $(0, 0)$ and $(0, w)$ with any speed not exceeding $u$. Thus the pedestrian can move only in a straight line $Oy$ in any direction with any speed not exceeding $u$ and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly. Please look at the sample note picture for better understanding. We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies \textbf{strictly inside} the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus). You are given the bus position at the moment $0$. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point $(0, w)$ and not to be hit by the bus.
Imagine that the bus stands still and we move "to the right" with a constant speed $v$. Then it's not hard to see that movement along the line $y = (u / v) \cdot (x - v \cdot t_{0})$ is optimal, where $t_{0}$ - time in which we begin our movement. In this way answer is $t = t_{0} + (w / u)$. If $t_{0} = 0$, then we start our movement immediately. In this case we need to check that our line doesn't intersect polygon (either we can cross the road in front of a bus, or the bus is gone). Otherwise we need to find such minimal $t_{0}$ that our line is tangent to the polygon. It can be done with binary search. Complexity - $O(n log n)$. Exercise: Solve this problem in $O(n)$.
[ "geometry", "implementation" ]
2,100
null
703
D
Mishka and Interesting sum
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of $n$ elements! Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process $m$ queries. Each query is processed in the following way: - Two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$) are specified — bounds of query segment. - Integers, presented in array segment $[l, r]$ (in sequence of integers $a_{l}, a_{l + 1}, ..., a_{r}$) \textbf{even number of times}, are written down. - XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are $x_{1}, x_{2}, ..., x_{k}$, then Mishka wants to know the value $x_{1}\oplus x_{2}\oplus\cdot\cdot\leftrightarrow x_{k}$, where $\mathbb{C}$ — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Easy to see, that the answer for query is XOR-sum of all elements in the segment xored with XOR-sum of distinct elements in the segment. XOR-sum of all numbers we can find in $O(1)$ using partial sums. As for the XOR-sum of distinct numbers... Let's solve easier problem. Let the queries be like "find the number of distinct values in a segment". Let's sort all the queries according to their right bounds and iterate through all elements of our array. We also need to make a list $last$, where $last[value]$ is the last position of $value$ on the processed prefix of array. Assume we are at position $r$. Then the answer for the query in the segment $[l, r]$ ($l \le r$) is $\textstyle\sum_{i=1}^{r}c n t[i]$, where $cnt[i] = 1$ if $last[a_{i}] = i$ and $0$ otherwise. It's easy to store and update such values in $cnt$. When moving to the next position we have to make the following assignments: $cnt[last[a_{i}]] = 0, cnt[i] = 1, last[a_{i}] = i$. To get described sum in $O(log n)$ we can use segment tree (or Fenwick tree) instead of standard array. Now let's turn back to our problem. Everything we have to do is to change assignment $cnt[i] = 1$ to $cnt[i] = a_{i}$ and count XOR-sum instead of sum. Now we can solve this problem in $O(n log n)$. P.S.: Also there is a solution with $O(n sqrt n)$ complexity (using Mo's algo), but we tried to kill it :D
[ "data structures" ]
2,100
null
703
E
Mishka and Divisors
After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem. You are given integer $k$ and array $a_{1}, a_{2}, ..., a_{n}$ of $n$ integers. You are to find \textbf{non-empty} subsequence of array elements such that the product of its elements is divisible by $k$ and it contains minimum possible number of elements. Formally, you are to find a sequence of indices $1 ≤ i_{1} < i_{2} < ... < i_{m} ≤ n$ such that $\prod_{j=1}^{m}a_{i_{j}}$ is divisible by $k$ while $m$ is minimum possible among all such variants. If there are more than one such subsequences, you should choose one among them, such that sum of its elements is \textbf{minimum possible}. Mishka quickly solved this problem. Will you do so?
Let's use dp to solve this problem. Suppose $dp[i][d]$ is the minimal number of elements on prefix of size $i$, that their product is divisible by $d$. It's easy to see that $dp[i][d] = min(dp[i - 1][d], dp[i - 1][d / gcd(d, a_{i})] + 1)$. That is so because it's optimal to take as much divisors of $a_{i}$ as possible. Answer - $dp[n][k]$. Let's imrove our solution. Notice, that as $d$ we should use only divisors of $k$ (which in the worst case would be 6720). As for $gcd$, we can easily find it in $O(primes(k))$, where $primes(k)$ - number of primes in decomposition of $k$. We also need to renumber our divisors according to their prime decomposition. To get AC in this problem you had to optimize described dp and add minimization of used elements' sum. Final complexity - $O(n \cdot divs(k) \cdot primes(k))$.
[ "dp", "number theory" ]
2,600
null
704
A
Thor
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are $n$ applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). $q$ events are about to happen (in chronological order). They are of three types: - Application $x$ generates a notification (this new notification is unread). - Thor reads all notifications generated so far by application $x$ (he may re-read some notifications). - Thor reads the first $t$ notifications generated by phone applications (notifications generated in first $t$ events of the first type). It's guaranteed that there were at least $t$ events of the first type before this event. Please note that he doesn't read first $t$ unread notifications, he just reads the very first $t$ notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Consider a queue $e$ for every application and also a queue $Q$ for the notification bar. When an event of the first type happens, increase the number of unread notifications by 1 and push pair $(i, x)$ to $Q$ where $i$ is the index of this event among events of the first type, and also push number $i$ to queue $e[x]$. When a second type event happens, mark all numbers in queue $e[x]$ and clear this queue (also decreese the number of unread notifications by the number of elements in this queue before clearing). When a third type query happens, do the following: while Q is not empty and Q.front().first <= t: i = Q.front().first x = Q.front().second Q.pop() if mark[i] is false: mark[i] = true e[v].pop() ans = ans - 1 // it always contains the number of unread notificationsBut in C++ set works much faster than queue! Time Complexity: $O(q)$
[ "brute force", "data structures", "implementation" ]
1,600
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e6 + 100; set<int> s[maxn]; set<pii> se; int main(){ int n, q; scanf("%d %d", &n, &q); int nx = 0; while(q--){ int type; scanf("%d", &type); if(type == 1){ int x; scanf("%d", &x); -- x; s[x].insert(nx); se.insert({nx ++, x}); } else if(type == 2){ int x; scanf("%d", &x); -- x; rep(i, s[x]) se.erase({i, x}); s[x].clear(); } else{ int t; scanf("%d", &t); while(!se.empty() && se.begin()->x < t){ pii p = *se.begin(); se.erase(p); s[p.y].erase(p.x); } } printf("%d ", (int)se.size()); } return 0; }
704
B
Ant Man
Scott Lang is at war with Darren Cross. There are $n$ chairs in a hall where they are, numbered with $1, 2, ..., n$ from left to right. The $i$-th chair is located at coordinate $x_{i}$. Scott is on chair number $s$ and Cross is on chair number $e$. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number $s$), visit each chair \textbf{exactly once} and end up on chair number $e$ with Cross. As we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number $i$ to chair number $j$ takes $|x_{i} - x_{j}|$ seconds. Also, jumping off a chair and landing on a chair takes extra amount of time. If Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large. Jumping off the $i$-th chair takes: - $c_{i}$ extra seconds if he's small. - $d_{i}$ extra seconds otherwise (he's large). Also, landing on $i$-th chair takes: - $b_{i}$ extra seconds if he's small. - $a_{i}$ extra seconds otherwise (he's large). In simpler words, jumping from $i$-th chair to $j$-th chair takes exactly: - $|x_{i} - x_{j}| + c_{i} + b_{j}$ seconds if $j < i$. - $|x_{i} - x_{j}| + d_{i} + a_{j}$ seconds otherwise ($j > i$). Given values of $x$, $a$, $b$, $c$, $d$ find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once.
Reduction to TSP is easy. We need the shortest Hamiltonian path from $s$ to $e$. Consider the optimal answer. Its graph is a directed path. Consider the induced graph on first $i$ chairs. In this subgraph, there are some components. Each components forms a directed path. Among these paths, there are 3 types of paths: In the future (in chairs in right side of $i$), we can add vertex to both its beginning and its end. In the future (in chairs in right side of $i$), we can add vertex to its beginning but not its end (because its end is vertex $e$). In the future (in chairs in right side of $i$), we cannot add vertex to its beginning (because its beginning is vertex $s$) but we can add to its end. There are at most 1 paths of types 2 and 3 (note that a path with beginning $s$ and ending $e$ can only exist when all chairs are in the subgraph. i.e. induced subgraph on all vertices). This gives us a dp approach: $dp[i][j][k][l]$ is the answer for when in induced subgraph on the first $i$ vertices there are $j$ components of type $1$, $k$ of type $2$ and $l$ of type $3$. Please note that it contains some informations more than just the answer. For example we count $d[i]$ or $- x[i]$ when we add $i$ to the dp, not $j$ (in the problem statement, when $i < j$). Updating it requires considering all four ways of incoming and outgoing edges to the last vertex $i$ (4 ways, because each edge has 2 ways, left or right). You may think its code will be hard, but definitely easier than code of B. Time Complexity: $O(n^{2})\,$
[ "dp", "graphs", "greedy" ]
2,500
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 5000 + 100; const ll inf = 1LL << 60; int a[maxn], b[maxn], c[maxn], d[maxn], x[maxn], n, s, e; ll dp[2][maxn][2][2], ans = inf; int main(){ iOS; cin >> n >> s >> e; -- s, -- e; For(i,0,n) cin >> x[i]; For(i,0,n) cin >> a[i]; For(i,0,n) cin >> b[i]; For(i,0,n) cin >> c[i]; For(i,0,n) cin >> d[i]; fill(&dp[0][0][0][0], &dp[0][0][0][0] + 8 * maxn, inf); dp[1][0][0][0] = 0; For(i,0,n){ bool I = i & 1; bool J = !I; For(j,0,n+1) For(k,0,2) For(l,0,2) dp[I][j][k][l] = inf; For(j,0,n+1) For(k,0,2) For(l,0,2) if(dp[J][j][k][l] != inf){ ll val = dp[J][j][k][l]; if(i != s && i != e){ /* LL */{ ll cur = 2LL * x[i] + a[i] + c[i]; if(j + k + l > 1) smin(dp[I][j-1][k][l], cur + val); if(i == n-1 && !j && k && l) smin(ans, cur + val); } /* LR */{ ll cur = a[i] + d[i]; if(j or k) smin(dp[I][j][k][l], cur + val); } /* RL */{ ll cur = b[i] + c[i]; if(j or l) smin(dp[I][j][k][l], cur + val); } /* RR */{ ll cur = -2LL * x[i] + b[i] + d[i]; smin(dp[I][j+1][k][l], cur + val); } } else if(i == s && !k){ /* L */{ ll cur = x[i] + c[i]; if(j) smin(dp[I][j-1][1][l], cur + val); if(i == n-1 && !j && l) smin(ans, cur + val); } /* R */{ ll cur = -x[i] + d[i]; smin(dp[I][j][1][l], cur + val); } } else if(i == e && !l){ /* L */{ ll cur = x[i] + a[i]; if(j) smin(dp[I][j-1][k][1], cur + val); if(i == n-1 && !j && k) smin(ans, cur + val); } /* R */{ ll cur = -x[i] + b[i]; smin(dp[I][j][k][1], cur + val); } } } } cout << ans << endl; return 0; }
704
C
Black Widow
Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form: Where $\boldsymbol{\mathit{V}}$ represents logical OR and $\mathbb{C}$ represents logical exclusive OR (XOR), and $v_{i, j}$ are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and $v_{i, j}$ are called literals. In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables $x_{1}, x_{2}, ..., x_{m}$ and their negations. An XNF formula is 2-XNF-2 if: - For each $1 ≤ i ≤ n$, $k_{i} ≤ 2$, i.e. the size of each clause doesn't exceed two. - Each variable occurs \textbf{in the formula at most two times} (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of $m$ variables, consisting of $n$ clauses. Please, make sure to check the samples in order to properly understand how the formula looks like. Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set $x_{1}, ..., x_{m}$ with $true$ and $false$ (out of total of $2^{m}$ ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo $10^{9} + 7$. Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to $false$ or $true$ gives different ways to set variables).
Build a graph. Assume a vertex for each clause. For every variable that appears twice in the clauses, add an edge between clauses it appears in (variables that appear once are corner cases). Every vertex in this graph has degree at most two. So, every component is either a cycle or a path. We want to solve the problem for a path component. Every edge either appear the same in its endpoints or appears differently. Denote a $dp$ to count the answer. $dp[i][j]$ is the number of ways to value the edges till $i - th$ vertex in the path so that the last clause($i$'s) value is $j$ so far ($j$ is either 0 or 1). Using the last edge to update $dp[i][j]$ from $dp[i - 1]$ is really easy in theory. Counting the answer for a cycle is practically the same, just that we also need another dimension in our $dp$ for the value of the first clause (then we convert it into a path). Handling variables that appear once (edges with one endpoint, this endpoint is always an endpoint of a path component) is also hard coding. And finally we need to merge the answers. Time Complexity: $O(n+m)$
[ "dp", "graphs", "implementation", "math" ]
2,900
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e5 + 100, mod = 1e9 + 7; typedef pair<int, bool> pib; vector<pib> lit[maxn], cl[maxn]; int V[maxn], U[maxn]; bool S[maxn]; vi adj[maxn]; int n, m; bool mark[maxn]; pii ans = {1, 0}; inline void app(pii p){ int x = (1LL * ans.x * p.x + 1LL * ans.y * p.y) % mod; int y = (1LL * ans.x * p.y + 1LL * ans.y * p.x) % mod; ans = {x, y}; } bool block[maxn], isa[maxn]; vi pat; vector<bool> sgn; inline void dfs(int v){ mark[v] = true; pat.pb(v); rep(e, adj[v]){ if(block[e]) continue ; block[e] = true; sgn.pb(S[e]); int u = V[e] + U[e] - v; if(!mark[u]) dfs(u); } } int dp[maxn][2][2][2]; inline int MOD(int a){ while(a >= mod) a -= mod; return a; } inline void solve(){ int sz = pat.size(); //rep(i, pat) error(i); For(i,0,sz + 2) For(j,0,2) For(k,0,2) For(l,0,2) dp[i][j][k][l] = 0; dp[0][0][0][0] = 1; if(isa[pat[0]]) dp[0][1][1][1] = 1; For(i,1,sz) For(b,0,2) For(e,0,2) For(t,0,2){ int s = sgn[i-1]; For(x,0,2){ int p = e | x; int w = s ^ x; int B = b; if(i == 1) B = p; int T = (2 + t + w + p - e) & 1; dp[i][B][w][T] = MOD(dp[i][B][w][T] + dp[i-1][b][e][t]); } } int o = sz-1; if((int)sgn.size() == sz){ ++ o; int s = sgn.back(); For(b,0,2) For(e,0,2) For(t,0,2) For(x,0,2){ int w = e | x; int B = b | (s ^ x); int T = (4 + t + w - e + B - b) & 1; dp[o][B][w][T] = MOD(dp[o][B][w][T] + dp[o-1][b][e][t]); } } else if(isa[pat.back()]){ ++ o; For(b,0,2) For(e,0,2) For(t,0,2) For(x,0,2){ int w = e | x; int T = (2 + t + w - e) & 1; dp[o][b][w][T] = MOD(dp[o][b][w][T] + dp[o-1][b][e][t]); } } int ans[2]; ans[0] = ans[1] = 0; For(b,0,2) For(e,0,2) For(t,0,2) ans[t] = MOD(ans[t] + dp[o][b][e][t]); app({ans[0], ans[1]}); } int main(){ scanf("%d %d", &n, &m); For(i,0,n){ int k; scanf("%d", &k); while(k--){ int a; scanf("%d", &a); bool s = a > 0; a = abs(a); -- a; cl[i].pb({a, s}); lit[a].pb({i, s}); } } int t = 1; For(i,0,m){ if(lit[i].empty()) t = (2LL * t) % mod; else if((int)lit[i].size() == 2){ bool s = lit[i][0].y ^ lit[i][1].y; int v = lit[i][0].x, u = lit[i][1].x; if(v == u){ isa[v] = true; if(s){ app({0, 2}); cl[v].clear(); } else cl[v].PB; } else{ adj[v].pb(i); adj[u].pb(i); V[i] = v, U[i] = u, S[i] = s; } } else isa[lit[i][0].x] = true; } For(i,0,n){ if(mark[i]) continue ; if(cl[i].empty()){ mark[i] = true; continue ; } if(adj[i].empty()){ mark[i] = true; if(cl[i].size() == 1) app({1, 1}); else app({1, 3}); continue ; } if(adj[i].size() == 1){ pat.clear(); sgn.clear(); dfs(i); solve(); } } For(i,0,n) if(!mark[i]){ pat.clear(); sgn.clear(); dfs(i); solve(); } int ans = ::ans.y; ans = (1LL * ans * t) % mod; printf("%d ", ans); return 0; }
704
D
Captain America
Steve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are $n$ shields in total, the $i$-th shield is located at point $(x_{i}, y_{i})$ of the coordinate plane. It's possible that two or more shields share the same location. Steve wants to paint all these shields. He paints each shield in either red or blue. Painting a shield in red costs $r$ dollars while painting it in blue costs $b$ dollars. Additionally, there are $m$ constraints Steve wants to be satisfied. The $i$-th constraint is provided by three integers $t_{i}$, $l_{i}$ and $d_{i}$: - If $t_{i} = 1$, then the absolute difference between the number of red and blue shields on line $x = l_{i}$ should not exceed $d_{i}$. - If $t_{i} = 2$, then the absolute difference between the number of red and blue shields on line $y = l_{i}$ should not exceed $d_{i}$. Steve gave you the task of finding the painting that satisfies all the condition and the total cost is minimum.
Assume $r < b$ (if not, just swap the colors). Build a bipartite graph where every vertical line is a vertex in part $X$ and every horizontal line is a vertex in part $Y$. Now every point(shield) is an edge (between the corresponding vertical and horizontal lines it lies on). We write 1 on an edge if we want to color it in red and 0 if in blue (there may be more than one edge between two vertices). Each constraint says the difference between 0 and 1 edges connected to a certain vertex should be less than or equal to some value. For every vertex, only the constraint with smallest value matters (if there's no constraint on this vertex, we'll add one with $d_{i} = number of edges connected to i$). Consider vertex $i$. Assume there are $q_{i}$ edges connected to it and the constraint with smallest $d$ on this vertex has $d_{j} = e_{i}$. Assume $r_{i}$ will be the number of red (with number 1 written on) edges connected to it at the end. With some algebra, you get that the constraint is fulfilled if and only if $\frac{q_{i}-e_{i}}{2}\le r_{i}\le\frac{q_{i}+e_{i}}{2}$. Denote $L_{i}=\left|{\frac{q_{i}-e_{i}}{2}}\right|$ and $R_{i}=[\frac{q_{\bot}\tau_{i}}{2}]$. So $L_{i} \le r_{i} \le R_{i}$. This gives us a L-R max-flow approach: aside these vertices, add a source $S$ and a sink $T$. For every vertex $v$ in part $X$, add an edge with minimum and maximum capacity $L_{v}$ and $R_{v}$ from $S$ to $v$. For every vertex $u$ in part $Y$, add an edge with minimum and maximum capacity $L_{u}$ and $R_{u}$ from $u$ to $T$. And finally for every edge $v - u$ from $X$ to $Y$ add an edge from $v$ to $u$ with capacity $1$ (minimum capacity is $0$). If there's no feasible flow in this network, answer is -1. Otherwise since $r \le b$, we want to maximize the number of red points, that is, maximizing total flow from $S$ to $T$. Since the edges in one layer (from $X$ to $Y$) have unit capacities, Dinic's algorithm works in $O(E{\sqrt{E}})$ (Karzanov's theorem) and because $V=O(n)$ and $E=O(n)$ Dinic's algorithm works in $O(n{\sqrt{n}})$. Time Complexity: $O(m+n{\sqrt{n}})$
[ "flows", "greedy" ]
3,100
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} template <class FlowT> class MaxFlow{ public: static const int maxn = 2e5 + 100, maxm = 5e5 + 100; static const FlowT FlowEPS = FlowT(1e-8), FlowINF = FlowT(1 << 29); int to[maxm * 2], prv[maxm * 2], hed[maxn], dis[maxn], pos[maxn]; FlowT cap[maxm * 2]; int n, m; inline void init(int N){n = N, m = 0;memset(hed, -1, n * sizeof hed[0]);} private: inline void add_single_edge(int v, int u, FlowT c){ to[m] = u, prv[m] = hed[v], cap[m] = c, hed[v] = m ++; } public: inline void add_edge(int v, int u, FlowT c, FlowT d = 0){ add_single_edge(v, u, c); add_single_edge(u, v, d); } inline bool bfs(int source, int sink){ static int qu[maxn], head, tail; head = tail = 0; memset(dis, -1, n * sizeof dis[0]); dis[source] = 0; qu[tail ++] = source; while(head < tail){ int v = qu[head ++]; for(int e = hed[v]; e + 1; e = prv[e]) if(cap[e] > FlowEPS && dis[to[e]] == -1) dis[to[e]] = dis[v] + 1, qu[tail ++] = to[e]; if(dis[sink] + 1) break ; } return dis[sink] + 1; } inline FlowT dfs(int v, int sink, FlowT cur = FlowINF){ if(v == sink) return cur; FlowT ans = 0; for(int &e = pos[v]; e + 1; e = prv[e]) if(cap[e] > FlowEPS && dis[to[e]] == dis[v] + 1){ FlowT tmp = dfs(to[e], sink, min(cur, cap[e])); cur -= tmp; ans += tmp; cap[e] -= tmp; cap[e ^ 1] += tmp; if(cur <= FlowEPS/2) break ; } return ans; } inline FlowT flow(int source, int sink){ FlowT ans = 0; while(bfs(source, sink)){ memcpy(pos, hed, n * sizeof hed[0]); ans += dfs(source, sink); } return ans; } }; MaxFlow<int> F, G; const int maxn = 1e5 + 100; vi xs, ys; int x[maxn], y[maxn]; inline int MPX(int x){ int i = lower_bound(all(xs), x) - xs.begin(); if(i == (int)xs.size() or xs[i] != x) return -1; return i; } inline int MPY(int y){ int i = lower_bound(all(ys), y) - ys.begin(); if(i == (int)ys.size() or ys[i] != y) return -1; return i; } int cntx[maxn], cnty[maxn], cx[maxn], cy[maxn], idx[maxn], idy[maxn], Lx[maxn], Rx[maxn], Ly[maxn], Ry[maxn], id[maxn]; int no_warn; int main(){ int n, m; int R, B; no_warn = scanf("%d %d", &n, &m); no_warn = scanf("%d %d", &R, &B); For(i,0,n){ no_warn = scanf("%d %d", x + i, y + i); xs.pb(x[i]); ys.pb(y[i]); } sort(all(xs)); sort(all(ys)); xs.resize(unique(all(xs)) - xs.begin()); ys.resize(unique(all(ys)) - ys.begin()); For(i,0,n){ x[i] = MPX(x[i]); y[i] = MPY(y[i]); ++ cntx[x[i]], ++ cx[x[i]]; ++ cnty[y[i]], ++ cy[y[i]]; } int X = xs.size(), Y = ys.size(); while(m--){ int t, i, d; no_warn = scanf("%d %d %d", &t, &i, &d); if(t == 1){ i = MPX(i); if(i == -1) continue ; smin(cx[i], d); } else{ i = MPY(i); if(i == -1) continue ; smin(cy[i], d); } } int s = X + Y, t = s + 1, S = t + 1, T = S + 1; F.init(T + 1); F.add_edge(t, s, n + 10); int tot = 0; For(i,0,X){ int deg = cntx[i]; int d = cx[i]; Lx[i] = (deg - d + 1) / 2; Rx[i] = (deg + d + 0) / 2; if(Lx[i] > Rx[i]){ cout << -1 << endl; return 0; } idx[i] = F.m; F.add_edge(s, i, Rx[i] - Lx[i]); if(Lx[i]){ F.add_edge(S, i, Lx[i]); F.add_edge(s, T, Lx[i]); tot += Lx[i]; } } For(i,0,n){ id[i] = F.m; F.add_edge(x[i], X + y[i], 1); } For(i,0,Y){ int deg = cnty[i]; int d = cy[i]; Ly[i] = (deg - d + 1) / 2; Ry[i] = (deg + d + 0) / 2; if(Ly[i] > Ry[i]){ cout << -1 << endl; return 0; } idy[i] = F.m; F.add_edge(X + i, t, Ry[i] - Ly[i]); if(Ly[i]){ F.add_edge(S, t, Ly[i]); F.add_edge(X + i, T, Ly[i]); tot += Ly[i]; } } int f = F.flow(S, T); if(f != tot){ puts("-1"); return 0; } G.init(t + 1); For(i,0,X) G.add_edge(s, i, F.cap[idx[i]], Rx[i] - Lx[i] - F.cap[idx[i]]); For(i,0,n){ int C = F.cap[id[i]]; int D = 1 - C; id[i] = G.m; G.add_edge(x[i], X + y[i], C, D); } For(i,0,Y) G.add_edge(X + i, t, F.cap[idy[i]], Ry[i] - Ly[i] - F.cap[idy[i]]); G.flow(s, t); string g = "rb"; if(R > B) swap(R, B), swap(g[0], g[1]); string ans; ll cost = 0; For(i,0,n){ int c = G.cap[id[i]]; cost += (c? B: R); ans += g[c]; } cout << cost << ' '; puts(ans.c_str()); return 0; }
704
E
Iron Man
Tony Stark is playing a game with his suits (they have auto-pilot now). He lives in Malibu. Malibu has $n$ junctions numbered from $1$ to $n$, connected with $n - 1$ roads. One can get from a junction to any other junction using these roads (graph of Malibu forms a tree). Tony has $m$ suits. There's a special plan for each suit. The $i$-th suit will appear at the moment of time $t_{i}$ in the junction $v_{i}$, and will move to junction $u_{i}$ using the shortest path between $v_{i}$ and $u_{i}$ with the speed $c_{i}$ roads per second (passing a junctions takes no time), and vanishing immediately when arriving at $u_{i}$ (if it reaches $u_{i}$ in time $q$, it's available there at moment $q$, but not in further moments). Also, suits move continuously (for example if $v_{i} ≠ u_{i}$, at time $t_{i}+{\frac{1}{2c_{i}}}$ it's in the middle of a road. Please note that if $v_{i} = u_{i}$ it means the suit will be at junction number $v_{i}$ only at moment $t_{i}$ and then it vanishes. An explosion happens if at any moment of time two suits share the same exact location (it may be in a junction or somewhere on a road; while appearing, vanishing or moving). Your task is to tell Tony the moment of the the first explosion (if there will be any).
First, we're gonna solve the problem for when the given tree is a bamboo (path). For simplifying, assume vertices are numbered from left to right with $1, 2, .., n$ (it's an array). There are some events (appearing and vanishing). Sort these events in chronological order. At first (time $- \infty $) no suit is there. Consider a moment of time $t$. In time $t$, consider all available suits sorted in order of their positions. This gives us a vector $f(t)$. Lemma 1: If $i$ and $j$ are gonna be at the same location (and explode), there's a $t$ such that $i$ and $j$ are both present in $f(t)$ and in $f(t)$ they're neighbours. This is obvious since if at the moment before they explode there's another suit between them, $i$ or $j$ and that suit will explode (and $i$ and $j$ won't get to the same location). Lemma 2: If $i$ and $j$ are present in $f(t)$ and in time $t$, $i$ has position less than $j$, then there's no time $e > t$ such that in it $i$ has position greater than $j$. This hold because they move continuously and the moment they wanna pass by each other they explode. So this gives us an approach: After sorting the events, process them one by one. consider $ans$ is the best answer we've got so far (earliest explosion, initially $ \infty $). Consider there's a set $se$ that contains the current available suits at any time, compared by they positions (so comparing function for this set would be a little complicated, because we always want to compare the suits in the current time, i.e. the time when the current event happens). If at any moment of time, time of event to be processed is greater than or equal to $ans$, we break the loop. When processing events: First of all, because current event's time is less than current $ans$, elements in $se$ are still in increasing order of their position due to lemma 2 (because if two elements were gonna switch places, they would explode before this event and $ans$ would be equal to their explosion time). There are two types of events: Suit $i$ appears. After updating the current moment of time (so $se$'s comparing function can use it), we insert $i$ into $se$. Then we check $i$ with its two neighbours in $se$ to update $ans$ (check when $i$ and its neighbours are gonna share the same position). Suit $i$ vanishes. After updating the current moment of time, we erase $i$ from $se$ and check its two previous neighbours (which are now neighbours to each other) and update $ans$ by their explosion time. This algorithm will always find the first explosion due to lemma 1 (because the suits that're gonna explode first are gonna be neighbours at some point). This algorithm only works for bamboos. For the original problem, we'll use heavy-light decompositions. At first, we decompose the path of a suit into heavy-light sub-chains (like $l$ sub-chains) and we replace this suit by $l$ suits, each moving only within a subchain. Now, we solve the problem for each chain (which is a bamboo, and we know how to solve the problem for a bamboo). After replacing each suit, we'll get $O(m l g(n))$ suits because $l=O(l g(n))$ and we need an extra log for sorting events and using set, so the total time complexity is $O(m l g^{2}(n))$. In implementation to avoid double and floating point bugs, we can use a pair of integers (real numbers). Time Complexity (more precisely): $O(n l g(n)+m l g^{2}(n)+m l g(n)l g(m))$
[ "data structures", "geometry", "trees" ]
3,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e5 + 10, maxl = 19; const ll inf = 1LL << 60; const double eps = 1e-12; struct frac{ ll x, y; frac(){x = 0, y = 1;} frac(ll X, ll Y){ x = X, y = Y; ll g = __gcd(abs(x), abs(y)); x /= g, y /= g; if(y < 0) x = -x, y = -y; } inline void relax(){ ll g = __gcd(abs(x), abs(y)); x /= g, y /= g; } frac(ll X){x = X, y = 1;} inline ostream& operator << (ostream &cout){ cout << (double)x/(double)y; return cout; } inline const double val() const{ return (double)x/(double)y; } inline void operator = (const frac &r){ x = r.x, y = r.y; } inline bool operator < (const frac &r) const{ return val() < r.val(); } inline bool operator > (const frac &r) const{ return val() > r.val(); } inline bool operator <= (const frac &r) const{ return val() < r.val() + eps; } inline bool operator >= (const frac &r) const{ return val() + eps > r.val(); } inline frac operator + (const frac &r) const{ frac ans; if(y == r.y){ ans.x = x + r.x; ans.y = y; } else{ ans.y = y * r.y; ans.x = x * r.y + r.x * y; } if(!ans.x) ans.y = 1; if(ans.y < 0) ans.x = -ans.x, ans.y = -ans.y; return ans; } inline frac operator - (const frac &r) const{ frac ans; if(y == r.y){ ans.x = x - r.x; ans.y = y; return ans; } else{ ans.y = y * r.y; ans.x = x * r.y - r.x * y; } if(!ans.x) ans.y = 1; if(ans.y < 0) ans.x = -ans.x, ans.y = -ans.y; return ans; } inline frac operator * (const frac &r) const{ frac ans; ans.y = y * r.y; ans.x = x * r.x ; ll g = __gcd(abs(ans.x), abs(ans.y)); ans.x /= g, ans.y /= g; if(!ans.x) ans.y = 1; if(ans.y < 0) ans.x = -ans.x, ans.y = -ans.y; return ans; } inline frac operator / (const frac &r) const{ frac ans; ans.y = y * r.x; ans.x = x * r.y ; if(!ans.x) ans.y = 1; if(ans.y < 0) ans.x = -ans.x, ans.y = -ans.y; return ans; } inline frac operator + (const ll &r) const{ return (*this) + frac(r); } inline frac operator - (const ll &r) const{ return (*this) - frac(r); } inline frac operator * (const ll &r) const{ return (*this) * frac(r); } inline frac operator / (const ll &r) const{ return (*this) / frac(r); } }; int st[maxn], ft[maxn], par[maxn][maxl], h[maxn], tim, sz[maxn], fst[maxn], stm[maxn], lst[maxn]; int BIG[maxn]; vi adj[maxn]; int n, m; struct CAR{ int v, u, c; frac t; }a[maxn]; inline void DFS(int v = 0, int p = -1){ sz[v] = 1; rep(u, adj[v]) if(u - p){ DFS(u, v); sz[v] += sz[u]; } } inline void dfs(int v = 0, int p = -1, bool big = false){ BIG[v] = v; fst[v] = (big? fst[p]: v); stm[tim] = v; st[v] = tim ++; par[v][0] = p; if(~p) h[v] = h[p] + 1; For(i,1,maxl) if(~par[v][i-1]) par[v][i] = par[par[v][i-1]][i-1]; int mx = 0, I = -1; For(i,0,adj[v].size()) if(adj[v][i] - p && mx < sz[adj[v][i]]) mx = sz[adj[v][i]], I = i, BIG[v] = adj[v][i]; if(~I) rotate(adj[v].begin(), adj[v].begin() + I, adj[v].end()); For(i,0,adj[v].size()) if(adj[v][i] - p) dfs(adj[v][i], v, !i); ft[v] = tim; smax(lst[fst[v]], st[v]); } inline bool anc(int v, int u){// u is ancestor of v return st[u] <= st[v] && ft[v] <= ft[u]; } inline int lca(int v, int u){ if(h[v] < h[u]) swap(v, u); rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]) v = par[v][i]; if(v == u) return v; rof(i,maxl-1,-1) if(par[v][i] - par[u][i]) v = par[v][i], u = par[u][i]; return par[v][0]; } typedef pair<frac, frac> pd; typedef pair<pii, int> piii; typedef pair<piii, pd> car; vector<car> cars[maxn]; inline int sign(frac x){ if(!x.x) return 0; if(x.x > 0) return 1; return -1; } inline void add(int v, int u, int i, bool LA = true, bool rev = false){ // u is ancestor of v int V = v; while(fst[v] != fst[u]){ int l = v; int r = par[fst[v]][0]; frac b = frac(h[V] - h[l])/frac(a[i].c) + a[i].t; frac e = frac(h[V] - h[r])/frac(a[i].c) + a[i].t; if(!rev) cars[fst[v]].pb({{{h[l], h[r]}, i}, {b, e}}); else cars[fst[v]].pb({{{h[r], h[l]}, i}, {e, b}}); v = par[fst[v]][0]; } if(!LA) return ; int l = v; int r = u; frac b = frac(h[V] - h[l])/frac(a[i].c) + a[i].t; frac e = frac(h[V] - h[r])/frac(a[i].c) + a[i].t; if(!rev) cars[fst[v]].pb({{{h[l], h[r]}, i}, {b, e}}); else cars[fst[v]].pb({{{h[r], h[l]}, i}, {e, b}}); } frac ans(2e5); int I = -1, J = -1, ID; frac TIME; inline frac pos(const int &i){ frac dis (cars[ID][i].x.x.y - cars[ID][i].x.x.x); frac T = cars[ID][i].y.y - cars[ID][i].y.x; if(!sign(T)) return cars[ID][i].x.x.x; frac V (sign(dis) * a[cars[ID][i].x.y].c); frac ans = V * (TIME - cars[ID][i].y.x) + cars[ID][i].x.x.x ; return ans; } struct cmp{ inline bool operator ()(const int &i, const int &j) const{ frac a = pos(i), b = pos(j); if(a < b or a > b) return a < b; return i < j; } }; inline void check(int i, int j){ frac A = pos(i), B = pos(j); if(A < B) swap(A, B), swap(i, j); if(A <= B && A >= B){ if(ans > TIME) ans = TIME, I = cars[ID][i].x.y, J = cars[ID][j].x.y; return ; } frac dis (cars[ID][i].x.x.y - cars[ID][i].x.x.x); frac T = cars[ID][i].y.y - cars[ID][i].y.x; if(!sign(T)){ return ; } frac VI (sign(dis) * a[cars[ID][i].x.y].c); dis = frac(cars[ID][j].x.x.y - cars[ID][j].x.x.x); T = cars[ID][j].y.y - cars[ID][j].y.x; if(!sign(T)){ return ; } frac VJ (sign(dis) * a[cars[ID][j].x.y].c); if(sign(VI) > 0 && VJ <= VI){ return ; } if(sign(VJ) < 0 && VI >= VJ){ return ; } frac t = TIME + (A-B)/(VJ-VI); frac e = min(cars[ID][i].y.y, cars[ID][j].y.y); if(t > min(cars[ID][i].y.y, cars[ID][j].y.y)) return ; if(t < max(cars[ID][i].y.x, cars[ID][j].y.x)) return ; if(ans > t) ans = t, I = cars[ID][i].x.y, J = cars[ID][j].x.y; } inline void solve(int id){ ID = id; typedef pair<frac, pii> event; set<event> se; set<int, cmp> pp; For(i,0,cars[id].size()){ se.insert({cars[id][i].y.x, {0, i}}); se.insert({cars[id][i].y.y, {1, i}}); } rep(e, se){ if(e.x >= ans) return ; TIME = e.x; int i = e.y.y; if(!e.y.x){ pp.insert(i); auto it = pp.find(i); auto it2 = it; if(it != pp.begin()){ -- it; check(*it, i); } ++ it2; if(it2 != pp.end()){ check(i, *it2); } } else{ auto it = pp.find(i); assert(it != pp.end()); auto it2 = it; ++ it2; if(it != pp.begin() && it2 != pp.end()){ -- it; check(*it, *it2); } pp.erase(i); } } } int no_warn; int main(){ memset(par, -1, sizeof par); no_warn = scanf("%d %d", &n, &m); For(i,1,n){ int v, u; no_warn = scanf("%d %d", &v, &u); -- v, -- u;; adj[v].pb(u), adj[u].pb(v); } DFS(); dfs(); For(i,0,m){ int t; no_warn = scanf("%d %d %d %d", &t, &a[i].c, &a[i].v, &a[i].u); a[i].t = frac(t); int &v = a[i].v, &u = a[i].u; -- v, -- u; int x = lca(v, u); bool V = false, U = false; if(v == u){ add(v, x, i); continue; } if(x != v && (x == u or anc(v, BIG[x]))) V = true; else U = true; if(x != v){ add(v, x, i, V); } if(x != u){ frac T = frac(h[v] + h[u] - 2*h[x])/frac(a[i].c) + a[i].t, tt(a[i].t); a[i].c *= -1; a[i].t = T; add(u, x, i, U, true); a[i].c *= -1; a[i].t = tt; } } For(i,0,n) if(fst[i] == i) solve(i); if(ans >= frac(2e5)){ cout << -1 << endl; return 0; } cout << fixed << setprecision(30) << (double)ans.x/(double)ans.y << endl; return 0; }
705
A
Hulk
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have $n$ layers. The first layer is hate, second one is love, third one is hate and so on... For example if $n = 1$, then his feeling is "I hate it" or if $n = 2$ it's "I hate that I love it", and if $n = 3$ it's "I hate that I love that I hate it" and so on. Please help Dr. Banner.
Just alternatively print "I hate that" and "I love that", and in the last level change "that" to "it". Time Complexity: ${\mathcal{O}}(n)$
[ "implementation" ]
800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} int main(){ iOS; int n; cin >> n; For(i,0,n){ if(i % 2) cout << "I love "; else cout << "I hate "; if(i + 1 == n) cout << "it "; else cout << "that "; } return 0; }
705
B
Spider Man
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex. Initially there are $k$ cycles, $i$-th of them consisting of exactly $v_{i}$ vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least $2$ vertices (for example, $x$ vertices) among all available cycles and replace it by two cycles with $p$ and $x - p$ vertices where $1 ≤ p < x$ is chosen by the player. The player who cannot make a move loses the game (and his life!). Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the $i$-th test he adds a cycle with $a_{i}$ vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.
First of all, instead of cycles, imagine we have bamboos (paths). A valid move in the game is now taking a path and deleting an edge from it (to form two new paths). So, every player in his move can delete an edge in the graph (with components equal to paths). So, no matter how they play, winner is always determined by the parity of number of edges (because it decreases by 1 each time). Second player wins if and only if the number of edges is even. At first it's even (0). In a query that adds a cycle (bamboo) with an odd number of vertices, parity and so winner won't change. When a bamboo with even number of vertices (and so odd number of edges) is added, parity and so the winner will change. Time Complexity: ${\mathcal{O}}(n)$
[ "games", "math" ]
1,100
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} int main(){ iOS; int q; cin >> q; int ans = 0; while(q--){ int a; cin >> a; --a; ans ^= a & 1; cout << 2 - ans << ' '; } return 0; }
706
A
Beru-taxi
Vasiliy lives at point $(a, b)$ of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested $n$ available Beru-taxi nearby. The $i$-th taxi is located at point $(x_{i}, y_{i})$ and moves with a speed $v_{i}$. Consider that each of $n$ drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.
We know that time=distance/speed. For each car we should find $time_{i}$, than if it is less than answer we should update it. Time Complexity: O(n).
[ "brute force", "geometry", "implementation" ]
900
#include <bits/stdc++.h> using namespace std; double dist (int x1, int y1, int x, int y){ return sqrt((x1 - x) * (x1 - x) + (y - y1)*(y - y1)); } int main() { ios_base::sync_with_stdio(false); int n, x, y; cin >> x >> y >> n; long double time = 1e9; for (int i = 0; i < n; i++){ int xi, yi, vi; cin >> xi >> yi >> vi; long double now_time = dist(xi, yi, x, y) / (vi * 1.); time = min(time, now_time); } cout << fixed; cout << setprecision(20) << time; return 0; }
706
B
Interesting drink
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in $n$ different shops in the city. It's known that the price of one bottle in the shop $i$ is equal to $x_{i}$ coins. Vasiliy plans to buy his favorite drink for $q$ consecutive days. He knows, that on the $i$-th day he will be able to spent $m_{i}$ coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
Consider $c[x]$ the number of stores in which the price per drink is $x$. We calculate this array prefix sum. Then the following options: 1) If the current amount of money $m$ is larger than the size of the array with the prefix sums than answer is $n$. 2) Otherwise, the answer is $c[m]$. Time Complexity: O(n+q).
[ "binary search", "dp", "implementation" ]
1,100
#include <iostream> using namespace std; const int N = (int)1e5 + 5; int cost[N], dp[N]; int main() { ios_base::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++){ int x; cin >> x; cost[x]++; } for (int i = 1; i < N; i++){ dp[i] = dp[i - 1] + cost[i]; } int q; cin >> q; for (int i = 0; i < q; i++){ int m; cin >> m; if (m > (N - 1)){ cout << n << endl; } else { cout << dp[m] << endl; } } return 0; }
706
C
Hard problem
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. Vasiliy is given $n$ strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on). To reverse the $i$-th string Vasiliy has to spent $c_{i}$ units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order. String $A$ is lexicographically smaller than string $B$ if it is shorter than $B$ ($|A| < |B|$) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in $A$ is smaller than the character in $B$. For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
We will solve the problem with the help of dynamic programming. $dp[i][j]$ is the minimum amount of energy that should be spent to make first $i$ strings sorted in lexicographical order and $i$-th of them will be reversed if $j$ = 1 and not reversed if $j$ = 0. $dp[i][j]$ is updated by $dp[i - 1][0]$ and $dp[i - 1][1]$. It remains to verify that the $i$-th string is lexicographically greater than $(i - 1)$-th (if $j$ = 1 then we should check reversed $i$-th string, similar to $(i - 1)$-th). Then we update $dp[i][j]$ = min($dp[i][j]$, $dp[i - 1][0]$ + $c[i]$ * $j$), $dp[i][j]$ = min($dp[i][j]$, $dp[i - 1][1]$ + $j$ * $c[i]$). The answer is a minimum of $dp[n][0]$ and $dp[n][1]$. Time Complexity: O(n+sum_length).
[ "dp", "strings" ]
1,600
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stdio.h> using namespace std; int n; vector <string> str; long long c[200000]; long long dp[200000][2]; string rev(string x) { string y; for (int i = x.size() - 1; i >= 0; i--) y += x[i]; return y; } bool check(string a, string b) { for (int i = 0; i < min(a.size(), b.size()); i++) { if (a[i] < b[i]) return 0; if (a[i] > b[i]) return 1; } return a.size() >= b.size(); } int main() { cin >> n; for (int i = 0; i < n; i++) cin >> c[i]; for (int i = 0; i < n; i++) { string s; cin >> s; str.push_back(s); } for (int i = 0; i < 200000; i++) { dp[i][0] = 1000000000000000000; dp[i][1] = 1000000000000000000; } dp[0][0] = 0; dp[0][1] = c[0]; for (int i = 1; i < n; i++) { if (check(str[i], str[i - 1]) && dp[i - 1][0] < dp[i][0]) dp[i][0] = dp[i - 1][0]; if (check(str[i], rev(str[i - 1])) && dp[i - 1][1] < dp[i][0]) dp[i][0] = dp[i - 1][1]; if (check(rev(str[i]), str[i - 1]) && dp[i - 1][0] + c[i] < dp[i][1]) dp[i][1] = dp[i - 1][0] + c[i]; if (check(rev(str[i]), rev(str[i - 1])) && dp[i - 1][1] + c[i] < dp[i][1]) dp[i][1] = dp[i - 1][1] + c[i]; } if (dp[n - 1][0] == 1000000000000000000 && dp[n - 1][1] == 1000000000000000000) { cout << -1 << endl; return 0; } cout << min(dp[n - 1][0], dp[n - 1][1]) << endl; }
706
D
Vasiliy's Multiset
Author has gone out of the stories about Vasiliy, so here is just a formal task description. You are given $q$ queries and a multiset $A$, initially containing only integer $0$. There are three types of queries: - "+ x" — add integer $x$ to multiset $A$. - "- x" — erase one occurrence of integer $x$ from multiset $A$. It's guaranteed that at least one $x$ is present in the multiset $A$ before this query. - "? x" — you are given integer $x$ and need to compute the value $\operatorname*{max}_{y\in A}(x\oplus y)$, i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer $x$ and some integer $y$ from the multiset $A$. Multiset is a set, where equal elements are allowed.
Let's store each number in binary system (each number consists of 32 bits, 0 or 1) in such a data structure as trie.The edges will be the bits 1 and 0, and the vertices will be responsible for whether it is possible to pass the current edge. To reply to a query like "? X" will descend the forest of high-order bits to whether the younger and now we can look XOR in the i-th bit to get one, if we can, then move on, otherwise we go to where we can go. Time Complexity: O(q*log(10^9)).
[ "binary search", "bitmasks", "data structures", "trees" ]
1,800
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stdio.h> using namespace std; int q; int sz = 1; struct node { int zero; int one; int cnt1; int cnt0; }a[10000000]; int main() { cin >> q; for (int i = 0; i <= q; i++) { char c; int x; if(i==0) { c='+'; x=0; } else cin >> c >> x; if (c == '+') { int bit[32]; for (int i = 0; i < 32; i++) { bit[i] = x % 2; x /= 2; } int v = 1; for (int i = 31; i >= 0; i--) { if (bit[i] == 1) { a[v].cnt1++; if (a[v].one == 0) { sz++; a[v].one = sz; } v = a[v].one; } else { a[v].cnt0++; if (a[v].zero == 0) { sz++; a[v].zero = sz; } v = a[v].zero; } } } if (c == '-') { int bit[32]; for (int i = 0; i < 32; i++) { bit[i] = x % 2; x /= 2; } int v = 1; for (int i = 31; i >= 0; i--) { if (bit[i] == 1) { a[v].cnt1--; v = a[v].one; } else { a[v].cnt0--; v = a[v].zero; } } } if (c == '?') { int ans = 0; int bit[32]; for (int i = 0; i < 32; i++) { bit[i] = x % 2; x /= 2; } int v = 1; for (int i = 31; i >= 0; i--) { if (bit[i] == 1) { if (a[v].cnt0 > 0) { ans += (1 << i); v = a[v].zero; } else { v = a[v].one; } } else { if (a[v].cnt1 > 0) { ans += (1 << i); v = a[v].one; } else { v = a[v].zero; } } } cout << ans << endl; } } }
706
E
Working routine
Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of $n$ rows and $m$ columns and $q$ tasks. Each task is to swap two submatrices of the given matrix. For each task Vasiliy knows six integers $a_{i}$, $b_{i}$, $c_{i}$, $d_{i}$, $h_{i}$, $w_{i}$, where $a_{i}$ is the index of the row where the top-left corner of the first rectangle is located, $b_{i}$ is the index of its column, $c_{i}$ is the index of the row of the top-left corner of the second rectangle, $d_{i}$ is the index of its column, $h_{i}$ is the height of the rectangle and $w_{i}$ is its width. It's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles \textbf{share a side}. However, rectangles are allowed to share an angle. Vasiliy wants to know how the matrix will look like after all tasks are performed.
Let's surround the matrix with the frame of elements. In each element of the matrix, and frame we need to store value, the number of the right element and the number of down element. When a request comes we should change only values of the elements along the perimeter of rectangles. Time Complexity: O(q*(n+m)).
[ "data structures", "implementation" ]
2,500
null
707
A
Brain's Photos
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour! As soon as Brain is a photographer not programmer now, he asks you to help him determine for a \textbf{single} photo whether it is colored or black-and-white. Photo can be represented as a matrix sized $n × m$, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only $6$ colors: - 'C' (cyan) - 'M' (magenta) - 'Y' (yellow) - 'W' (white) - 'G' (grey) - 'B' (black) The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
We need to do exactly what is written in the task: to consider all of the characters, and, if there is at least one of the set ${C, M, Y}$ print "#Color" else - "#Black&White"
[ "implementation" ]
800
null
707
B
Bakery
Masha wants to open her own bakery and bake muffins in one of the $n$ cities numbered from $1$ to $n$. There are $m$ bidirectional roads, each of whose connects some pair of cities. To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only $k$ storages, located in different cities numbered $a_{1}, a_{2}, ..., a_{k}$. Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another $n - k$ cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay $1$ ruble. Formally, Masha will pay $x$ roubles, if she will open the bakery in some city $b$ ($a_{i} ≠ b$ for every $1 ≤ i ≤ k$) and choose a storage in some city $s$ ($s = a_{j}$ for some $1 ≤ j ≤ k$) and $b$ and $s$ are connected by some path of roads of summary length $x$ (if there are more than one path, Masha is able to choose which of them should be used). Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of $k$ storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.
Note that it makes no sense to choose the city for bakeries and the city with the warehouse so that had more than one way between them, as every road increases the distance over which you have to pay. So, the problem reduces to the following: select two neighboring cities so that one is a warehouse, and in the other & mdash; no. For doing this, simply iterate through all the city with the warehouse, among the neighbors of each town without looking for a warehouse and update the answer. If there is such a pair of cities, print -1.
[ "graphs" ]
1,300
null
707
D
Persistent Bookcase
Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf. The bookcase consists of $n$ shelves, and each shelf has exactly $m$ positions for books at it. Alina enumerates shelves by integers from $1$ to $n$ and positions at shelves — from $1$ to $m$. Initially the bookcase is empty, thus there is no book at any position at any shelf in it. Alina wrote down $q$ operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: - $1$ $i$ $j$ — Place a book at position $j$ at shelf $i$ if there is no book at it. - $2$ $i$ $j$ — Remove the book from position $j$ at shelf $i$ if there is a book at it. - $3$ $i$ — Invert book placing at shelf $i$. This means that from every position at shelf $i$ which has a book at it, the book should be removed, and at every position at shelf $i$ which has not book at it, a book should be placed. - $4$ $k$ — Return the books in the bookcase in a state they were after applying $k$-th operation. In particular, $k = 0$ means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position. After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?
bookcase Solution No. 1: Note that the data is delivered all at once (offline). Then we can build a tree of versions, then run out of the DFS root and honestly handle each request in the transition from the top to the top. Solution No. 2: Note that Alina uses operations that relate to the columns. We can make an array of versions of the shelves, and each version of the cabinet to provide an array of indices and the corresponding shelves to store it explicitly. Then, for the operation, such as changing wardrobe, shelves, a new version which has been changed, this version of the index is recorded on the same shelf position. This approach eliminates the decision on the use of extra memory for storing unnecessary information.
[ "bitmasks", "data structures", "dfs and similar", "implementation" ]
2,200
null
707
E
Garlands
Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlands — chains consisting of a lightbulbs. Alesha uses a grid field sized $n × m$ for playing. The rows of the field are numbered from $1$ to $n$ from the top to the bottom and columns are numbered from $1$ to $m$ from the left to the right. Alesha has $k$ garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains \textbf{at most one lightbulb}. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side. \begin{center} The example of garland placing. \end{center} Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure. Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially \textbf{all the garlands are turned on}. Alesha is still very little and can't add big numbers. He extremely asks you to help him.
Let us handle each request as follows: Let's go for a "frame" request and remember lamp garlands, which lies on the boundary. Then, in order to find concrete garland, what part of it lies within the query, sum all of its segments, the ends of it are lamps that lie on the "frame". Also, do not forget the garland wich lies entirely within the request. Each garland at the beginning we find the extreme points, and to check whether it lies entirely within the query, check whether the lie inside its extreme points.
[ "data structures" ]
2,400
null
708
A
Letters Cyclic Shift
You are given a non-empty string $s$ consisting of lowercase English letters. You have to pick \textbf{exactly one non-empty substring} of $s$ and shift all its letters 'z' $\to$ 'y' $\to$ 'x' $\to\cdot\cdot\top$ 'b' $\to$ 'a' $\to$ 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from $s$ by performing this shift exactly once?
If string consists only of symbols 'a', then we could only make it lexicographically bigger. To achieve the least change we should shift the last symbol. In any other case we could make string lexicographically less. We should shift first biggest subsegment of string consists only from symbols not equal to 'a'.
[ "constructive algorithms", "greedy", "implementation", "strings" ]
1,200
void solve() { string s; cin >> s; for (int i = 0; i < s.length(); ++i) { if (s[i] == 'a') { continue; } int j = i + 1; while (j < s.length() && s[j] != 'a') { ++j; } for (int r = i; r < j; ++r) { --s[r]; } cout << s << "\n"; return; } s.back() = 'z'; cout << s << "\n"; }
708
B
Recover the String
For each string $s$ consisting of characters '0' and '1' one can define four integers $a_{00}$, $a_{01}$, $a_{10}$ and $a_{11}$, where $a_{xy}$ is the number of \textbf{subsequences} of length $2$ of the string $s$ equal to the sequence ${x, y}$. In these problem you are given four integers $a_{00}$, $a_{01}$, $a_{10}$, $a_{11}$ and have to find any non-empty string $s$ that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than $1 000 000$.
Using $a_{00}$ and $a_{11}$ easy to calculate $c_{0}, c_{1}$ - numbers of 0 and 1 in string (it could be done by binary search or solving quadratic equation $c_{0} \cdot (c_{0} - 1) / 2 = a_{00}$). But in case $a_{00} = 0$, $c_{0}$ is not fixed and could be equal 0 or 1. One could consider both cases for sure (or code several 'if's to throw away one of the variants). If $a_{01} + a_{10} \neq c_{0} \cdot c_{1}$, then answer is impossible. Otherwise it is possible to create such string using greedy algorithm. Consider string $b = string(c_{0}, '0') + string(c_{1}, '1')$, its array of subsequences equals ${a_{00}, a_{01} + a_{10}, 0, a_{11}}$. One could swap neighbouring pairs $01$ one by one and transform it to $string(c_{1}, '1') + string(c_{0}, '0')$ (similar to bubble sorting), its array equals ${a_{00}, 0, a_{01} + a_{10}, a_{11}}$. During this process string corresponding to array ${a_{00}, a_{01}, a_{10}, a_{11}}$ was reproduced exactly once, because every swap reduce $b_{01}$ by one and increase $b_{10}$ by one, so we have $O(n^{2})$ solution. One could make it linear: take string $b = string(c_{0}, '0') + string(c_{1}, '1')$ and move its zeros one by one directly in the end of string while $b_{01} - a_{01} \ge c_{1}$. When $b_{01}$ become $b_{01} - a_{01} < c_{1}$ we will move next zero on $b_{01} - a_{01}$ symbols left and finally get desired string. There is another way to do it, when you build lexicographically smallest string one symbol by one from the beginning.
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,900
void imp() { cout << "Impossible\n"; exit(0); } ll invtriange(ll x) { ll l = 1, r = 1000000; while (r - l > 1) { ll m = (l + r) / 2; if (m * (m - 1) / 2 > x) r = m; else l = m; } if (l * (l - 1) / 2 != x) { imp(); } return l; } int main() { vvl a(2, vl(2)); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { cin >> a[i][j]; } if (a[0][0] + a[0][1] + a[1][0] + a[1][1] == 0) { cout << "0\n"; return 0; } ll c0 = invtriange(a[0][0]); ll c1 = invtriange(a[1][1]); if (a[0][0] == 0 || a[1][1] == 0) { if (a[0][1] + a[1][0] == 0) { if (c0 == 1) c0 = 0; if (c1 == 1) c1 = 0; cout << string(c0, '0') << string(c1, '1'); return 0; } } if (c0 * c1 != a[0][1] + a[1][0]) { imp(); } string s(c0 + c1, '0'); for (int i = 0; i < s.size(); ++i) { if (c0 == 0 || a[0][1] < c1) { s[i] = '1'; a[1][0] -= c0; --c1; } else { a[0][1] -= c1; --c0; } } cout << s << endl; return 0; }
708
C
Centroids
Tree is a connected acyclic graph. Suppose you are given a tree consisting of $n$ vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed $\frac{n t}{2}$. You are given a tree of size $n$ and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
The first observation is that to make vertex $x$ a centroid we need to choose some subtree not containing $x$ with size not exceeding $\frac{n t}{2}$ (assume its root is $w$), remove an edge $uw$ between its subtree and the remaining tree, and add an edge between $x$ and $w$, in such a way that subtrees of all children of $x$ have size not exceeding $\frac{n t}{2}$. Consider $v$ - the centroid of the tree, let's make it a root. Assume $u_{1}, u_{2}, ..., u_{k}$ are the neighbours of $v$, and $T_{1}, ..., T_{k}$ are the subtrees of these vertices. Then it is easy to prove, that if some vertex $x\in T,$ can be made a centroid after replacing one edge of the tree, then it can be done using one of the following options: Remove some edge $vu_{j}$ for $j \neq i$ and add an edge $xu_{j}$. Remove the edge $u_{iv}$ and add edge $xv$. It is possible, if the size of $T_{i}$ is exactly $n-{\frac{n}{2}}$. So we need to calculate the sizes of all subtrees (array $cnt$) and then run dfs from $u_{1}, ..., u_{k}$. Vertex $x\in T,$ can be made a centroid if ether $|T_{i}|=n-{\frac{n}{2}}$, or $c n t[x]+\operatorname*{max}_{j\neq i}|T_{j}|\geq n-{\frac{n}{2}}$ (since we add edge $xu_{j}$ to maximize $|T_{j}|$, if the last condition holds, then the number of vertices in the connected component of $x$, if $x$ is deleted from the tree, will not exceed $\frac{n t}{2}$ - so all the condition for $x$ being centroid will hold). To check the second condition, we need to find two maximums in the set $|T_{1}|, |T_{2}|, ..., |T_{k}|$. The described solution has complexity $O(n)$.
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "trees" ]
2,300
int n; vector<vector<int>> g; vector<int> cnt; int min_mx = 1e9; int center = -1; void dfs(int v, int p) { cnt[v] = 1; int mx = 0; for (int to : g[v]) { if (to == p) { continue; } dfs(to, v); cnt[v] += cnt[to]; mx = max(mx, cnt[to]); } mx = max(mx, n - cnt[v]); if (mx < min_mx) { min_mx = mx; center = v; } } vector<pair<int, int>> subtrees; vector<int> ans; void dfs1(int v, int p, int sum_other, int prev) { if (sum_other <= n / 2) { ans[v] = 1; } for (int i = 0; i < 2 && i < subtrees.size(); ++i) { if (subtrees[i].second == prev) { continue; } if (n - cnt[v] - subtrees[i].first <= n / 2) { ans[v] = 1; } } for (int to : g[v]) { if (to == p) { continue; } dfs1(to, v, sum_other, prev); } } void solve() { cin >> n; g.resize(n); cnt.assign(n, 0); for (int i = 1; i < n; ++i) { int a, b; cin >> a >> b; --a; --b; g[a].push_back(b); g[b].push_back(a); } dfs(0, 0); assert(center != -1); ans.assign(n, 0); ans[center] = 1; dfs(center, center); int sum_all = 0; for (int to : g[center]) { subtrees.emplace_back(cnt[to], to); sum_all += cnt[to]; } sort(all(subtrees)); reverse(all(subtrees)); for (int to : g[center]) { dfs1(to, center, n - cnt[to], to); } for (int i = 0; i < n; ++i) { cout << ans[i] << ' '; } cout << "\n"; }
708
D
Incorrect Flow
At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to use in order to demonstrate the workflow of the algorithm. He quickly finished to write the text and took a look at the problem only to understand that the given network is incorrect! Suppose you are given a directed graph $G(V, E)$ with two special nodes $s$ and $t$ called source and sink. We denote as $n$ the number of nodes in the graph, i.e. $n = |V|$ and $m$ stands for the number of directed edges in the graph, i.e. $m = |E|$. For the purpose of this problem we always consider node $1$ to be the source and node $n$ to be the sink. In addition, for each edge of the graph $e$ we define the capacity function $c(e)$ and flow function $f(e)$. Function $f(e)$ represents the correct flow if the following conditions are satisfied: - For each edge $e\in E$ the flow is non-negative and does not exceed capacity $c(e)$, i.e. $0 ≤ f(e) ≤ c(e)$. - For each node $v\in V$, that is not source or sink ($v ≠ s$ and $v ≠ t$) the sum of flows of all edges going in $v$ is equal to the sum of the flows among all edges going out from $v$. In other words, there is no flow stuck in $v$. It was clear that as the exam was prepared last night and there are plenty of mistakes in the tasks. Sasha asked one of the professors to fix the network or give the correct task, but the reply was that the magistrate student should be able to fix the network himself. As the professor doesn't want the task to become easier, he asks Sasha to fix the network in a such way that the total number of changes is minimum possible. Sasha is not allowed to remove edges, add new ones or reverse the direction of existing edges. The only thing he is able to do is to change capacity function $c(e)$ and flow function $f(e)$. Moreover, all the values should remain non-negative integers. There is no requirement on the flow to be maximum in any sense. Find the minimum possible total change of the functions $f(e)$ and $c(e)$ that Sasha has to make in order to make the flow correct. The total change is defined as the sum of absolute differences, i.e. if new functions are $f^{ * }(e)$ and $c^{ * }(e)$, then the total change is $\textstyle\sum_{e\in E}|f(e)-f^{*}(e)|+|c(e)-c^{*}(e)|$.
This problem could be solved by max-flow-min-cost algorithm. At first we will fix edges with flow exceeding capacity. We will just increase capacity to the flow value and add sum of all these changes to the answer. Now we need to get rid of excess incoming flow in some vertices and excess outcoming flow in some other vertices. Consider new flow-cost network, source and sink will be new vertices. We add edge from new source into every vertex with excess of incoming flow with zero cost and capacity equals to the excess flow. We add edge into new sink every vertex with excess of outcoming flow with zero cost and capacity equals to the excess flow. We add edge from old sink to the old source with zero cost and infinite capacity. Instead of every edge of the initial graph (denote its capacity as $c$, flow as $f$) we will create three edges: the first one could decrease flow in the initial graph without change of capacity (its cost equals 1, capacity equals $f$, it has opposite direction), the second one could increase flow without change of capacity (its cost equals 1, capacity equals $c - f$, it has same direction), the third one could increase flow and capacity as much as you need (its cost equals 1, capacity equals infinity, it has same direction). One more trick is that cost of part of the second type edge should be zero instead of one if it had $f > c$, because in this case we make changes which have already pay.
[ "flows" ]
2,900
class FixFlow { public: void solve(std::istream& in, std::ostream& out) { int n, m; in >> n >> m; int s = n; int t = n + 1; MinCostFlow<int, int> flow(n + 2); vector<int> balance(n); int INF = 1000000000; flow.addEdge((size_t) (n - 1), 0, INF, 0); int defaultAnswer = 0; for (int i: range(m)) { int a, b, c, f; in >> a >> b >> c >> f; --a, --b; balance[a] += f; balance[b] -= f; if (f <= c) { flow.addEdge(a, b, c - f, 1); flow.addEdge(a, b, INF, 2); flow.addEdge(b, a, f, 1); } else { // f > c defaultAnswer += f - c; flow.addEdge(a, b, INF, 2); flow.addEdge(b, a, f - c, 0); flow.addEdge(b, a, c, 1); } } int sumB = 0; for (int i: range(n)) { if (balance[i] > 0) { flow.addEdge(i, t, balance[i], 0); sumB += balance[i]; } else { flow.addEdge(s, i, -balance[i], 0); } } auto res = flow.findFlow(s, t, MinCostMaxFlowStrategy()); assert(res.flow == sumB); out << res.cost + defaultAnswer << "\n"; } };
708
E
Student's Camp
Alex studied well and won the trip to student camp Alushta, located on the seashore. Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of $n + 2$ concrete blocks height and $m$ blocks width. Every day there is a breeze blowing from the sea. Each block, except for the blocks of the upper and lower levers, such that there is no block to the left of it is destroyed with the probability $p={\frac{a}{b}}$. Similarly, each night the breeze blows in the direction to the sea. Thus, each block (again, except for the blocks of the upper and lower levers) such that there is no block to the right of it is destroyed with the same probability $p$. Note, that blocks of the upper and lower level are \textbf{indestructible}, so there are only $n·m$ blocks that can be destroyed. The period of the strong winds will last for $k$ days and $k$ nights. If during this period the building will split in at least two connected components, it will collapse and Alex will have to find another place to spend summer. Find the probability that Alex won't have to look for other opportunities and will be able to spend the summer in this camp.
Let $dp[t][l][r]$ is probability that first $t$ rows are connected and $t$-th row is $[l;r)$ (it's always a segment). We can write a simple equation: $d p[t][l][r]=p_{l,r}\sum_{l p,r p}d p[t-1][l p][r p]$ $p_{l}={\binom{k}{l}}p^{l}(1-p)^{k-l}.$ $d p_{r}[t][r]=\sum_{l<r}d p[t][l][r]$ $s u m_{-}d p_{r}[t][r]=\sum_{a\leq r}d p_{r}[t][a]$ $sum_dp_{l}[t][l] = sum_dp_{r}[t][n - r].$ Now $dp[t][l][r] = p_{l, r}(sum_dp_{r}[t - 1][n] - sum_dp_{r}[t - 1][l] - sum_dp_{l}[t - 1][r]).$ Here we subtract from probability of all segments the segments on the left and on the right. Now we won't calculate $dp[t][l][r]$ but $dp_{r}[t][r]$. $\begin{array}{c}{{d p_{r}[t][r]=\sum_{l<r}p_{l,r}(s u m_{-}d p_{r}[t-1][n]-s u m_{-}d p_{r}[t-1][l]-s u m_{-}d p_{l}[t-1].}}\end{array}$ It's $O(n)$ to calculate each separate value, but it's also possible to calculate them all in $O(n)$ if we iterate over $r$ from $0$ to $m$ and hold several values during this process. Particularly, we need precalculated sums of $p_{l, r}$ with fixed $r$ and to hold the sum of $p_{l} \cdot sum_dp_{r}[t - 1][l]$ for $l < r$ (recall that $p_{l, r} = p_{l} \cdot p_{n - r}$. See code for details. $sum_dp_{r}[t][r]$ is just prefix sums of what we calculated. So we obtain the solution with $O(nm)$ complexity.
[ "dp", "math" ]
3,100
class MAI { public: void solve(std::istream& in, std::ostream& out) { int N, m; int a, b; int k; in >> N >> m >> a >> b >> k; using Z = ZnConst<1000000007>; Z p = Z::valueOf(a) / b; Z q = 1 - p; // dp[r'] = sum l < r <= r' d[l][r] vector<Z> dp(m + 1, Z()); dp[m] = 1; vector<Z> powersP(k + 1), powersQ(k + 1); powersP[0] = powersQ[0] = 1; for (int i: range(k)) { powersP[i + 1] = powersP[i] * p; powersQ[i + 1] = powersQ[i] * q; } vector<Z> fact = factorials<Z>(k + 1); vector<Z> invfact = fact; for (auto& x: invfact) { x = 1 / x; } auto get_p_one_side = [&](int l) { if (l > k) { return Z(); } return powersP[l] * powersQ[k - l] * fact[k] * invfact[l] * invfact[k - l]; }; for (int iter: range(N)) { vector<Z> dp_one(m + 1, Z()); Z sumPl, sumPlDpl; for (int r: inclusiveRange(m)) { //new_d[l][r] = p[l] * p[n - r] * (have_something - dp[l] - dp[n - r]) Z have_something = dp.back(); dp_one[r] = get_p_one_side(m - r) * ( have_something * sumPl - sumPlDpl - sumPl * dp[m - r] ); sumPl += get_p_one_side(r); sumPlDpl += get_p_one_side(r) * dp[r]; } for (int i: range(m)) { dp_one[i + 1] += dp_one[i]; } dp = move(dp_one); } out << dp.back(); } };
709
A
Juicer
Kolya is going to make fresh orange juice. He has $n$ oranges of sizes $a_{1}, a_{2}, ..., a_{n}$. Kolya will put them in the juicer in the fixed order, starting with orange of size $a_{1}$, then orange of size $a_{2}$ and so on. To be put in the juicer the orange must have size not exceeding $b$, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one. The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than $d$. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
In this problem you have to carefully implement exactly what it written in the statement. Pay attention to some details: Don't forget to throw away too large oranges. Don't mix up strict and not-strict inequalities.
[ "implementation" ]
900
int main() { int n, b, d; std::cin >> n >> b >> d; int current_size = 0; int result = 0; int x; for (; n > 0; --n) { std::cin >> x; if (x > b) { continue; } current_size += x; if (current_size > d) { ++result; current_size = 0; } } std::cout << result << "\n"; return 0; }
709
B
Checkpoints
Vasya takes part in the orienteering competition. There are $n$ checkpoints located along the line at coordinates $x_{1}, x_{2}, ..., x_{n}$. Vasya starts at the point with coordinate $a$. His goal is to visit at least $n - 1$ checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order. Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Sort all point by $x$-coordinate. If we've chosen the set of points we want to visit, then we must go either to the leftmost of them and then to the rightmost, or to the rightmost and then to the leftmost, the others will be visited automatically during this process. The other observation is that it makes sense to not visit only either the leftmost or the rightmost point - otherwise this point will be visited during any walk which visits $n - 1$ points. So, the solution is to fix the points which we don't want to visit - either the leftmost or the rightmost, after that iterate over two possible orders of visits of the lefmost and rightmost points of the remaining set of $n - 1$ points and relax the answer. Also don't forget the case $n = 1$ - then you don't need to visit any point.
[ "greedy", "implementation", "sortings" ]
1,500
const int MAXN = 100000; int x[MAXN]; int main() { int n, A; scanf("%d %d", &n, &A); if (n == 1) { printf("0\n"); return 0; } for (int i = 0; i < n; i++) { scanf("%d", &x[i]); } int first_max = -2e6; int second_max = -2e6; int first_min = 2e6; int second_min = 2e6; for (int i = 0; i < n; i++) { if (x[i] > second_max) { second_max = x[i]; if (second_max > first_max) { swap(second_max, first_max); } } if (x[i] < second_min) { second_min = x[i]; if (second_min < first_min) { swap(second_min, first_min); } } } printf("%d\n", min(first_max - second_min + min(abs(A - first_max), abs(A - second_min)), second_max - first_min + min(abs(A - second_max), abs(A - first_min)))); return 0; }
710
A
King Moves
The only king stands on the standard chess board. You are given his position in format "cd", where $c$ is the column from 'a' to 'h' and $d$ is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here https://en.wikipedia.org/wiki/King_(chess). \begin{center} {\small King moves from the position e4} \end{center}
Easy to see that there are only three cases in this problem. If the king is in the corner of the board the answer is $3$. If the king is on the border of the board but not in a corner then the answer is $5$. Otherwise the answer is $8$. Complexity: $O(1)$.
[ "implementation" ]
800
char c, d; bool read() { return !!(cin >> c >> d); } void solve() { int cnt = 0; if (c == 'a' || c == 'h') cnt++; if (d == '1' || d == '8') cnt++; if (cnt == 0) puts("8"); else if (cnt == 1) puts("5"); else if (cnt == 2) puts("3"); else throw; }
710
B
Optimal Point on a Line
You are given $n$ points on a line with their coordinates $x_{i}$. Find the point $x$ so the sum of distances to the given points is minimal.
The function of the total distance is monotonic between any pair of adjacent points from the input, so the answer is always in some of the given points. We can use that observation to solve the problem by calculating the total distance for each point from the input and finding the optimal point. The other solution uses the observation that the answer is always is the middle point (by index) in the sorted list of the given points. The last fact is also can be easily proven. Complexity: $O(nlogn)$.
[ "brute force", "sortings" ]
1,400
const int N = 300300; int n, a[N]; bool read() { if (!(cin >> n)) return false; forn(i, n) assert(scanf("%d", &a[i]) == 1); return true; } void solve() { sort(a, a + n); li suml = 0, sumr = accumulate(a, a + n, 0ll); li ansv = LLONG_MAX, ansp = LLONG_MIN; forn(i, n) { li curv = li(i) * a[i] - suml; curv += sumr - li(n - i) * a[i]; if (ansv > curv) { ansv = curv; ansp = a[i]; } suml += a[i]; sumr -= a[i]; } assert(sumr == 0); assert(ansv != LLONG_MAX); cerr << "ansv: " << ansv << endl; cout << ansp << endl; }
710
C
Magic Odd Square
Find an $n × n$ matrix with different numbers from $1$ to $n^{2}$, so the sum in each row, column and both main diagonals are odd.
The solution can be got from the second sample testcase. Easy to see that if we place all odd numbers in the center in form of rhombus we will get a magic square. Complexity: $O(n^{2})$.
[ "constructive algorithms", "math" ]
1,500
int n; bool read() { return !!(cin >> n); } const int N = 101; int a[N][N]; void solve() { memset(a, 0, sizeof(a)); forn(i, n / 2) { int len = n / 2 - i; forn(j, len) { int x1 = i, x2 = n - 1 - i; int y1 = j, y2 = n - 1 - j; a[x1][y1] = 1; a[x1][y2] = 1; a[x2][y1] = 1; a[x2][y2] = 1; } } int odd = 1, even = 2; forn(i, n) forn(j, n) if (a[i][j]) a[i][j] = even, even += 2; else a[i][j] = odd, odd += 2; forn(i, n) { forn(j, n) { if (j) putchar(' '); printf("%d", a[i][j]); } puts(""); } }
710
D
Two Arithmetic Progressions
You are given two arithmetic progressions: $a_{1}k + b_{1}$ and $a_{2}l + b_{2}$. Find the number of integers $x$ such that $L ≤ x ≤ R$ and $x = a_{1}k' + b_{1} = a_{2}l' + b_{2}$, for some integers $k', l' ≥ 0$.
Let's write down the equation describing the problem: $a_{1}k + b_{1} = a_{2}l + b_{2} \rightarrow a_{1}k - a_{2}l = b_{2} - b_{1}$. So we have linear Diofant equation with two variables: $Ax + By = C, A = a_{1}, B = - a_{2}, C = b_{2} - b_{1}$. The solution has the form: $A{\frac{C x_{0}+B p}{g}}+B{\frac{C y_{0}-A p}{g}}=C,g=g c d(A,B),A x_{0}+B y_{0}=C$, where the last equation can be solved by extended Euclid algorithm and $p$ is any integral number. The variable $p$ should satisfy two conditions: $m a x(0,L)\leq{\frac{c x_{0}+B p}{g}}\leq R$ and $m a x(0,L)\leq{\frac{c y_{00}-A_{P}}{g}}\leq R$. The values $A$ and $B$ are fixed, so we can get the segment of possible values for the values $p$. The length of the segment is the answer for the problem. Complexity: $O(log(max(a_{1}, a_{2})))$.
[ "math", "number theory" ]
2,500
li a1, b1, a2, b2, l, r; bool read() { return !!(cin >> a1 >> b1 >> a2 >> b2 >> l >> r); } li _ceil(li, li); li _floor(li a, li b) { return b < 0 ? _floor(-a, -b) : a < 0 ? -_ceil(-a, b) : a / b; } li _ceil(li a, li b) { return b < 0 ? _ceil(-a, -b) : a < 0 ? -_floor(-a, b) : (a + b - 1) / b; } li gcd(li a, li b, li& x, li& y) { if (!a) { x = 0, y = 1; return b; } li xx, yy, g = gcd(b % a, a, xx, yy); x = yy - b / a * xx; y = xx; return g; } void solve() { l = max(0ll, _ceil(l - b1, a1)); r = _floor(r - b1, a1); if (l > r) { puts("0"); return; } li A = a1, B = -a2, C = b2 - b1; li x0, y0; li g = gcd(A, B, x0, y0); if (C % g) { puts("0"); return; } if (g < 0) { g = -g; x0 = -x0; y0 = -y0; } li L = _ceil(r * g - x0 * C, B); li R = _floor(l * g - x0 * C, B); R = min(R, _floor(y0 * C, A)); li ans = max(0ll, R - L + 1); cout << ans << endl; }
710
E
Generate a String
zscoder wants to generate an input file for some programming competition problem. His input is a string consisting of $n$ letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor. Initially, the text editor is empty. It takes him $x$ seconds to insert or delete a letter 'a' from the text file and $y$ seconds to copy the contents of the entire text file, and duplicate it. zscoder wants to find the minimum amount of time needed for him to create the input file of exactly $n$ letters 'a'. Help him to determine the amount of time needed to generate the input.
This problem has a simple solution described by participants in the comments. My solution is a little harder. Let's solve it using dynamic programming. Let $z_{n}$ be the smallest amount of time needed to get $n$ letters 'a'. Let's consider transitions: the transition for adding one letter 'a' can be simply done. Let's process transitions for multiplying by two and subtraction by one simultaneously: let's decrease the number $2 \cdot i$ $i$ times by one right after getting it. Easy to see that such updates never include each other, so we can store them in queue by adding the new update at the tail of the queue and taking the best update from the head. The solution is hard to describe, but it is very simple in the code, so please check it to understand the idea :-) Complexity: $O(n)$.
[ "dfs and similar", "dp" ]
2,000
int n; li x, y; bool read() { return !!(cin >> n >> x >> y); } const int N = 20 * 1000 * 1000 + 13; li z[N]; void solve() { forn(i, N) z[i] = LLONG_MAX; list<pair<li, int>> q; z[0] = 0; forn(i, n + 1) { while (!q.empty() && q.front().y < i) q.pop_front(); if (!q.empty()) z[i] = min(z[i], q.front().x - i * x); assert(z[i] != LLONG_MAX); pair<li, int> cur(z[i] + y + 2 * i * x, 2 * i); while (!q.empty() && q.back().x > cur.x) q.pop_back(); q.pb(cur); z[i + 1] = min(z[i + 1], z[i] + x); } cout << z[n] << endl; }
710
F
String Set Queries
You should process $m$ queries over a set $D$ of strings. Each query is one of three kinds: - Add a string $s$ to the set $D$. It is guaranteed that the string $s$ was not added before. - Delete a string $s$ from the set $D$. It is guaranteed that the string $s$ is in the set $D$. - For the given string $s$ find the number of occurrences of the strings from the set $D$. If some string $p$ from $D$ has several occurrences in $s$ you should count all of them. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query of the third type. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
Let's get rid of the queries for deleting a string. There are no strings that will be added two times, so we can calculate the answer for the added (but not deleted strings) and for the deleted separately and subtract the second from the first to get the answer. So we can consider that there are no queries of deletion. Now let's use Aho-Corasik algorithm. The only difficulty is that the strings are adding in online mode, but Aho-Corasik algorithm works only after adding all the strings. Note that the answer for the given set of strings equal to the answer for any part of the set plus the answer for the remaining part. Let's use the trick with converting the static data structure (Aho-Corasik in this case) to the dynamic one. For the set of $n$ strings let's maintain a set of no more than $logn$ sets of the strings with sizes of different powers of two. After adding new string we should move the sets from the lowest powers of two to the largest until we got an invariant set of sets. Easy to see that each string will be moved no more than $logm$ times, so we can process each query in $O(logn)$ time. Complexity: $O((slen + m)logm)$, where $slen$ is the total length of the string from the input.
[ "brute force", "data structures", "hashing", "interactive", "string suffix structures", "strings" ]
2,400
const int N = 4 * 300300, A = 26, LOGN = 20; struct node { char c; int parent, link, output; int next[A], automata[A]; int cnt; node(char c = -1, int parent = -1, int link = -1, int output = -1, int cnt = -1): c(c), parent(parent), link(link), output(output), cnt(cnt) { memset(next, -1, sizeof(next)); memset(automata, -1, sizeof(automata)); } }; node t[N]; vector<int> ids; inline int get_idx() { assert(!ids.empty()); int ans = ids.back(); ids.pop_back(); t[ans] = node(); return ans; } inline void return_idx(int idx) { ids.pb(idx); } inline int add(const string& s, int root) { int v = root; forn(i, sz(s)) { if (t[v].next[s[i] - 'a'] == -1) { int idx = get_idx(); t[v].next[s[i] - 'a'] = idx; t[idx] = node(s[i], v, -1, -1); } v = t[v].next[s[i] - 'a']; } t[v].output = v; return v; } int link(int v, int root) { int& ans = t[v].link; if (ans != -1) return ans; if (v == root || t[v].parent == root) return ans = root; char c = t[v].c; int vv = link(t[v].parent, root); while (vv != root && t[vv].next[c - 'a'] == -1) vv = link(vv, root); return ans = (t[vv].next[c - 'a'] == -1? root: t[vv].next[c - 'a']); } int output(int v, int root) { int& ans = t[v].output; if (ans != -1) return ans; return ans = (v == root? root: output(link(v, root), root)); } int cnt(int v, int root) { int& ans = t[v].cnt; if (ans != -1) return ans; v = output(v, root); if (v == root) return ans = 0; return ans = 1 + cnt(link(v, root), root); } int next(int v, char c, int root) { int& ans = t[v].automata[c - 'a']; if (ans != -1) return ans; if (t[v].next[c - 'a'] != -1) return ans = t[v].next[c - 'a']; return ans = (v == root? root: next(link(v, root), c, root)); } void dfs_clear(int v) { forn(i, A) if (t[v].next[i] != -1) dfs_clear(t[v].next[i]); return_idx(v); } string a[N]; int build(int root, const vector<int>& ids) { dfs_clear(root); root = get_idx(); forn(i, sz(ids)) add(a[ids[i]], root); return root; } int calc(int root, int idx) { int ans = 0; const string& s = a[idx]; int v = root; forn(i, sz(s)) { v = next(v, s[i], root); ans += cnt(v, root); } return ans; } int m; bool read() { return !!(cin >> m); } struct blocks { int root[LOGN]; vector<int> block[LOGN]; void clear() { forn(i, LOGN) { block[i].clear(); root[i] = get_idx(); } } void insert(int i) { vector<int> cur(1, i); forn(i, LOGN) if (sz(block[i]) == sz(cur)) { cur.insert(cur.end(), all(block[i])); block[i].clear(); root[i] = build(root[i], block[i]); } else { block[i] = cur; root[i] = build(root[i], block[i]); break; } } li calc2(int idx) { li ans = 0; forn(i, LOGN) { ans += calc(root[i], idx); } return ans; } }; char buf[N]; blocks z1, z2; void solve() { ids.clear(); nfor(i, N) ids.pb(i); z1.clear(); z2.clear(); forn(i, m) { int type; assert(scanf("%d%s", &type, buf) == 2); a[i] = buf; if (type == 1) { z1.insert(i); } else if (type == 2) { z2.insert(i); } else if (type == 3) { li ans = z1.calc2(i) - z2.calc2(i); printf("%lld\n", ans); fflush(stdout); } else throw; } }
711
A
Bus to Udayland
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has $n$ rows of seats. There are $4$ seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are good friends. They insist to get \textbf{a pair of neighbouring empty seats}. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
For each row, check whether there exists two consecutive Os. Once you find a pair of consecutive Os, you can replace them with +s and output the bus. If no such pair exists, output NO. Time Complexity : $O(n)$
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int INF = 1e9 + 7; const int MOD = 1e9 + 7; const int N = 1000; char bus[N][5]; void printbus(int n) { for(int i = 0; i < n; i++) { for(int j = 0; j < 5; j++) { cout << bus[i][j]; } cout << '\n'; } } void yes() { cout << "YES" << '\n'; } void no() { cout << "NO" << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for(int i = 0; i < n; i++) { for(int j = 0; j < 5; j++) { cin >> bus[i][j]; } } bool possible = false; for(int i = 0; i < n; i++) { for(int j = 0; j < 2; j++) { if(bus[i][j*3] == 'O' && bus[i][j*3+1] == 'O') { bus[i][j*3] = '+'; bus[i][j*3+1] = '+'; possible = true; break; } } if(possible) break; } if(!possible) { no(); return 0; } else { yes(); printbus(n); return 0; } return 0; }
711
B
Chris and Magic Square
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a $n × n$ magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a \textbf{positive integer} into the empty cell. Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid ($\textstyle\sum a_{r,i}$), each column of the grid ($\textstyle\sum a_{i,c}$), and the two long diagonals of the grid (the main diagonal — $\textstyle\sum a_{i,i}$ and the secondary diagonal — $\textstyle\sum a_{i,n-i+1}$) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?
Firstly, when $n = 1$, output any positive integer in the range will work. Otherwise, we calculate the sum of the values in each row, column and the two long diagonals, and also keep track which row and column the empty square is in and also which diagonals it lies on. Finally, we can use the sums to determine the value of the empty square or that it is impossible to make the square magic. Keep in mind that the blank must be filled with a positive integer, so $0$ doesn't work. Also, remember to use 64-bit integers to store the sums or it will overflow. (and will fail on the overflow test) Time Complexity : $O(n^{2})$
[ "constructive algorithms", "implementation" ]
1,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int INF = 1e9 + 7; const int MOD = 1e9 + 7; const int LG = 20; ll a[1001][1001]; ll r[1001]; //row sum ll c[1001]; //column sum int n; void no() { cout << -1 << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; int x, y; ll diagonal1 = 0; ll diagonal2 = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> a[i][j]; if(a[i][j] == 0) { x = i; y = j; } else { r[i] += a[i][j]; c[j] += a[i][j]; if(i == j) { diagonal1 += a[i][j]; } if(i + j == n - 1) { diagonal2 += a[i][j]; } } } } if(n == 1) { cout << 1 << '\n'; return 0; } ll commonsum = r[0]; if(x == 0) commonsum = r[1]; //cout << commonsum << '\n'; ll rowsum = -1; ll colsum = -1; ll d1sum = -1; ll d2sum = -1; for(int i = 0; i < n; i++) { if(i != x) { if(r[i] != commonsum) { no(); return 0; } } else { rowsum = r[i]; } } for(int i = 0; i < n; i++) { if(i != y) { if(c[i] != commonsum) { no(); return 0; } } else { colsum = c[i]; } } bool isdiagonal1 = false; bool isdiagonal2 = false; if(x == y) isdiagonal1 = true; if(x + y == n - 1) isdiagonal2 = true; if(!isdiagonal1) { if(diagonal1 != commonsum) { no(); return 0; } } else { d1sum = diagonal1; } if(!isdiagonal2) { if(diagonal2 != commonsum) { no(); return 0; } } else { d2sum = diagonal2; } if(rowsum == colsum) { if(isdiagonal1 && d1sum != rowsum) { no(); return 0; } if(isdiagonal2 && d2sum != rowsum) { no(); return 0; } ll value = commonsum - rowsum; if(value > 0) { cout << value << '\n'; return 0; } else { no(); return 0; } } else { no(); return 0; } }
711
C
Coloring Trees
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where $n$ trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from $1$ to $n$ from left to right. Initially, tree $i$ has color $c_{i}$. ZS the Coder and Chris the Baboon recognizes only $m$ different colors, so $0 ≤ c_{i} ≤ m$, where $c_{i} = 0$ means that tree $i$ is uncolored. ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with $c_{i} = 0$. They can color each of them them in any of the $m$ colors from $1$ to $m$. Coloring the $i$-th tree with color $j$ requires exactly $p_{i, j}$ litres of paint. The two friends define the beauty of a coloring of the trees as the \textbf{minimum} number of contiguous groups (each group contains some subsegment of trees) you can split all the $n$ trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are $2, 1, 1, 1, 3, 2, 2, 3, 1, 3$, the beauty of the coloring is $7$, since we can partition the trees into $7$ contiguous groups of the same color : ${2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}$. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is \textbf{exactly} $k$. They need your help to determine the minimum amount of paint (in litres) needed to finish the job. Please note that the friends can't color the trees that are already colored.
We compute the following array : $dp[i][j][k]$ denoting the minimum amount of paint needed to color the first $i$ trees such that it has beauty $j$ and the $i$-th tree is colored by color $k$, and initialize all these values to $ \infty $. We can compute this dp array easily by considering two cases : 1. When the last color used is equal to the current color, then we should compare it with $dp[i - 1][j][k] + cost[i][k]$ if it was originally uncolored or $dp[i - 1][j][k]$ otherwise, since the beauty of the coloring is the same. 2. When the last color used is different from the current color, then we should compare it with $dp[i - 1][j - 1][l] + cost[i][k]$ or $dp[i - 1][j - 1][l]$ for all $1 \le l \le m$ except when $l$ is equal to the current color, by similar reasoning. If the current tree is uncolored, we loop through all the $m$ possible colors to color it. Naively implementing this dp will give an $O(nkm^{2})$, which is sufficient to pass for this problem. However, it is possible to optimize it into $O(nkm)$ by avoiding iterating through all colors when considering the last color used and store two global minimums. See the code for more the details. Time Complexity : $O(nkm^{2})$ or $O(nkm)$
[ "dp" ]
1,700
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 101; const int MOD = 1e9 + 7; const ll INF = ll(1e18); ll dp[N][N][N]; int c[N]; ll cost[N][N]; ll idx[N][N]; ll m1[N][N]; ll m2[N][N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, k; cin >> n >> m >> k; for(int i = 1; i <= n; i++) { cin >> c[i]; } for(int i = 0; i <= n; i++) { for(int j = 0; j <= k; j++) { m1[i][j] = INF; m2[i][j] = INF; idx[i][j] = -1; for(int a = 0; a <= m; a++) { dp[i][j][a] = INF; } } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> cost[i][j]; } } if(c[1] == 0) { for(int i = 1; i <= m; i++) { dp[1][1][i] = cost[1][i]; if(dp[1][1][i] <= m1[1][1]) { if(dp[1][1][i] == m1[1][1]) { idx[1][1] = -2; } else { idx[1][1] = i; } m2[1][1] = m1[1][1]; m1[1][1] = dp[1][1][i]; } else if(dp[1][1][i] <= m2[1][1]) { m2[1][1] = dp[1][1][i]; } } } else { dp[1][1][c[1]] = 0; m1[1][1] = 0; idx[1][1] = c[1]; } for(int i = 2; i <= n; i++) { for(int j = 1; j <= k; j++) { if(c[i] == 0) { for(int a = 1; a <= m; a++) { dp[i][j][a] = min(dp[i][j][a], dp[i-1][j][a] + cost[i][a]); ll tmp = INF; if(a == idx[i-1][j-1]) { tmp = m2[i-1][j-1]; } else { tmp = m1[i-1][j-1]; } dp[i][j][a] = min(dp[i][j][a], tmp + cost[i][a]); } } else { dp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][j][c[i]]); for(int b = 1; b <= m; b++) { if(b != c[i]) dp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][j-1][b]); } //cout << i << ' ' << j << ' ' << c[i] << ' ' << dp[i][j][c[i]] << '\n'; } for(int a = 1; a <= m; a++) { if(dp[i][j][a] <= m1[i][j]) { if(dp[i][j][a] == m1[i][j]) { idx[i][j] = -2; } else { idx[i][j] = a; } m2[i][j] = m1[i][j]; m1[i][j] = dp[i][j][a]; } else if(dp[i][j][a] <= m2[i][j]) { m2[i][j] = dp[i][j][a]; } } } } ll ans = INF; for(int i = 1; i <= m; i++) { ans = min(ans, dp[n][k][i]); } if(ans >= INF) ans = -1; cout << ans; }
711
D
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of $n$ towns numbered from $1$ to $n$. There are $n$ directed roads in the Udayland. $i$-th of them goes from town $i$ to some other town $a_{i}$ ($a_{i} ≠ i$). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town $A$ to town $B$ before the flip, it will go from town $B$ to town $A$ after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns $A_{1}, A_{2}, ..., A_{k}$ ($k > 1$) such that for every $1 ≤ i < k$ there is a road from town $A_{i}$ to town $A_{i + 1}$ and another road from town $A_{k}$ to town $A_{1}$. In other words, the roads are confusing if \textbf{some of them} form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are $2^{n}$ variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will \textbf{not} be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
We want to find the number of ways to assign directions to the edges of the graph so that it is acyclic, i.e. contains no cycles. First, we investigate what the graph looks like. It can be easily seen that the graph consists of several connected components, where each component is either a path or a cycle with some paths connected to some of the vertices. We'll solve the problem for each component and multiply the result for each component. If the component is a path, then however we orient the edges we won't form a cycle. So, if there are $x$ edges in the component, there are $2^{x}$ ways to orient the edges. Next, if the component has a cycle, then we can orient the remaining edges in any way (it will not affect the existence of cycles), then for the $x$ edges on the cycle, we have $2^{x} - 2$ ways to orient them. This is because there are a total of $2^{x}$ ways to orient the edges, but only $2$ ways gives a directed cycle. (fix the direction of one of the edges, then the directions of the other edges are uniquely determined to form a directed cycle) Thus, if there are $t$ edges not on the cycle and $x$ edges on the cycle, the total number of ways for this component is $2^{t}(2^{x} - 2)$. Finally, to compute the final answer we multiply the answers for each component. Computing the powers of $2$ can be done by a simple precomputation or using binary exponentiation. (the former works because the number of vertices is small) Finding the cycles can be easily done with a dfs. Time Complexity : $O(n)$
[ "combinatorics", "dfs and similar", "graphs", "math" ]
1,900
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int INF = 1e9 + 7; const int MOD = 1e9 + 7; const int N = 1e6 + 3; int a[N]; int visited[N]; ll ans; vector<int> cycles; ll dp[N]; int cyclecnt; void dfs2(int u) { cycles[cyclecnt]++; visited[u] = 3; if(visited[a[u]] == 3) return ; dfs2(a[u]); } void dfs(int u) { visited[u] = 2; if(visited[a[u]] == 0) { dfs(a[u]); } else if(visited[a[u]] == 1) { visited[u] = 1; return ; } else { cycles.pb(0); dfs2(u); cyclecnt++; } visited[u] = 1; } int main() { //ios_base::sync_with_stdio(0); cin.tie(0); int n; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", a + i); } dp[0] = 1; for(int i = 1; i <= n; i++) { dp[i] = (dp[i-1]*2LL)%MOD; } ans = 1; memset(visited, 0, sizeof(visited)); for(int i = 1; i <= n; i++) { if(visited[i] == 0) { dfs(i); } } ll cnt = n; for(int i = 0; i < cycles.size(); i++) { cnt -= cycles[i]; ans = (ans*(dp[cycles[i]]-2+MOD))%MOD; } ans = (ans*dp[cnt])%MOD; if(ans < 0) ans += MOD; int ans2 = ans; printf("%d\n", ans2); return 0; }
711
E
ZS and The Birthday Paradox
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of $23$ people, there is around $50%$ chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland, there are $2^{n}$ days in a year. ZS the Coder wants to interview $k$ people from Udayland, each of them has birthday in one of $2^{n}$ days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction $\underline{{A}}$. He wants to find the values of $A$ and $B$ (he does not like to deal with floating point numbers). Can you help him?
Note that $MOD = 10^{6} + 3$ is a prime. Firstly, if we have $k > 2^{n}$, then by pigeonhole principle we must have $2$ people with the same birthday. Thus, we can directly output $1$ $1$. Thus, now we suppose $k \le 2^{n}$. Then, instead of computing the probability directly, we compute the complement, i.e. the probability that all the people have distinct birthdays. This probability turns out to be much simpler to calculate, as it is just $\frac{(\dot{2}^{n}-\dot{1})(\dot{2}^{n}-\dot{2})_{\omega}(\dot{2}^{n}-(k-1))}{2^{(k-1)n}}$. (Fix the birthday of the first person, the probability that the second person has different birthday is $\scriptstyle{\frac{2^{n}-1}{2^{n}}}$, and for the next person it's $\frac{2^{n}-2}{2^{n}}$ and so on. Now, we know that the denominator is just a power of $2$. However, we still have to reduce the fraction to the lowest terms. Note that $\overset{\stackrel{\rightarrow}}{b}$ is in the lowest terms if and only if $1-{\frac{a}{b}}={\frac{b-a}{b}}$ is in the lowest terms, since $\operatorname*{gcd}(a,b)=\operatorname*{gcd}(b-a,b)$. Also, note that the gcd is a power of $2$ since the denominator is a power of $2$. Thus, we need to find the highest power of $2$ that divides $(2^{n} - 1)(2^{n} - 2)...(2^{n} - (k - 1))$. This is also equal to the sum of the highest power of $2$ that divides $2^{n} - 1$, $2^{n} - 2$, ..., $2^{n} - (k - 1)$. Now, if a power of $2$ divides $x < 2^{n}$, then it must also divides $2^{n} - x$ and vice versa. So, we can actually translate this to finding the sum of highest power of $2$ that divides $1, 2, ..., k - 1$, or the highest power of $2$ that divides $(k - 1)!$. Now, this is simple to calculate by Legendre's formula (which is quite easy to prove) in $O(\log k)$. Now that we find the gcd of the numerator and denominator, we can immediately find the reduced denominator by binary exponentiation. For the numerator, we need a bit more work, since we have to deal with $(2^{n} - 1)(2^{n} - 2)...(2^{n} - (k - 1))$. However, it is not hard either. The key fact is that $MOD$ is small, so if $k - 1 \ge MOD$, the product above is equal to $0$ modulo $MOD$, because among $MOD$ consecutive integers there must be one that is a multiple of $MOD$. Thus, the above product can be calculated in $O(MOD)$ if $k - 1 \le MOD$ and $O(1)$ otherwise. The remaining parts can be calculated using direct binary exponentiation. One minor note is that when we're calculating $2^{(k - 1)n}$, the value of $(k - 1)n$ might overflow. One way to resolve this is to reduce it modulo $MOD - 1$, since $2^{MOD - 1} \equiv 1$ modulo $MOD$ by Fermat's Little Theorem. Another way is to just evaluate $2^{k - 1}$ first, then take the result and raise it to the $n$-th power. Time Complexity : $O(M O D+\log k+\log n)$
[ "math", "number theory", "probabilities" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; const int MOD = 1e6 + 3; ll power(ll base, ll exp) { ll ans = 1; while(exp) { if(exp&1) ans = (ans*base)%MOD; base = (base*base)%MOD; exp>>=1; } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll n, k; cin >> n >> k; if(n <= 63 && k > (1LL<<n)) { cout << 1 << " " << 1; return 0; } ll v2 = 0; int digits = __builtin_popcountll(k - 1); v2 = k - 1 - digits; ll ntmp = n % (MOD - 1); if(ntmp < 0) ntmp += (MOD - 1); ll ktmp = k % (MOD - 1); if(ktmp < 0) ktmp += (MOD - 1); ll v2tmp = v2 % (MOD - 1); if(v2tmp < 0) v2tmp += (MOD - 1); ll exponent = ntmp*(ktmp - 1) - v2tmp; exponent %= (MOD - 1); if(exponent < 0) exponent += MOD - 1; ll denom = power(2, exponent); ll numpart = 0; if(k - 1 >= MOD) { numpart = 0; } else { ll prod = 1; ll ntmp2 = power(2, ntmp); prod = power(2, v2tmp); prod = power(prod, MOD - 2); if(prod < 0) prod += MOD; for(ll y = 1; y <= k - 1; y++) { prod = (prod * (ntmp2 - y))%MOD; } numpart = prod; } ll num = (denom - numpart)%MOD; num %= MOD; denom %= MOD; if(num < 0) num += MOD; if(denom < 0) denom += MOD; cout << num << " " << denom; return 0; }
712
A
Memory and Crow
There are $n$ integers $b_{1}, b_{2}, ..., b_{n}$ written in a row. For all $i$ from $1$ to $n$, values $a_{i}$ are defined by the crows performing the following procedure: - The crow sets $a_{i}$ initially $0$. - The crow then adds $b_{i}$ to $a_{i}$, subtracts $b_{i + 1}$, adds the $b_{i + 2}$ number, and so on until the $n$'th number. Thus, $a_{i} = b_{i} - b_{i + 1} + b_{i + 2} - b_{i + 3}...$. Memory gives you the values $a_{1}, a_{2}, ..., a_{n}$, and he now wants you to find the initial numbers $b_{1}, b_{2}, ..., b_{n}$ written in the row? Can you do it?
Note that $a[i] + a[i + 1] = b[i]$. Use the initial condition $b[n] = a[n]$ and we can figure out the entire array $b$. Time Complexity: $O(n)$
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int arr[100000]; int ans[100000]; int main() { int n; cin >> n; for(int i=0; i < n; i++){ cin >> arr[i]; } for(int i = n-1; i >=0; i--){ if(i==n-1) ans[i] = arr[i]; else ans[i] = arr[i] + arr[i+1]; } for(int i=0; i < n; i++){ cout << ans[i] << " "; } cout << endl; return 0; }
712
B
Memory and Trident
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string $s$ with his directions for motion: - An 'L' indicates he should move one unit left. - An 'R' indicates he should move one unit right. - A 'U' indicates he should move one unit up. - A 'D' indicates he should move one unit down. But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in $s$ with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.
First, if $S$ has odd length, there is no possible string because letters must come in opposite pairs. Now, let's denote the ending coordinate after following $S$ as $(x, y)$. Since $S$ has even length, $|x|$ has the same parity as $|y|$. Suppose they are both even. Then clearly, we can make $x = 0$ in exactly $\frac{|x|}{2}$ moves, and same for $y$. If instead they are both odd, then we can change exactly one x-character into a y-character. With the correct choices of these characters, now our string has $|x|$ and $|y|$ with even parity, thus reducing to the problem above. Therefore, the answer is $(|x| + |y|) / 2$. Time Complexity: $O(|S|)$
[ "implementation", "strings" ]
1,100
#include <string> #include <iostream> #include <stdlib.h> using namespace std; int main() { string str; cin >> str; if(str.length()%2==1){ cout << -1 << endl; return 0; } int x=0,y=0; for(int i=0; i < str.length(); i++){ if(str[i]=='U')y++; if(str[i]=='D')y--; if(str[i]=='L')x--; if(str[i]=='R')x++; } cout << (abs(x)+abs(y))/2 << endl; }
712
C
Memory and De-Evolution
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length $x$, and he wishes to perform operations to obtain an equilateral triangle of side length $y$. In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer. What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length $y$?
Let's reverse the process: start with an equilateral triangle with side length $y$, and lets get to an equilateral triangle with side length $x$. In each step, we can act greedily while obeying the triangle inequality. This will give us our desired answer. Time Complexity: $O(log$ $x)$
[ "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int x,y; cin >> x >> y; int besta=y,bestb=y,bestc=y; int turns = 0; while(true){ //check the current if(besta>=x && bestb>=x && bestc>=x){ cout << turns << endl; break; } turns++; if(turns%3==1){ //update a besta = bestb+bestc-1; } if(turns%3==2){ //update b bestb = besta+bestc-1; } if(turns%3==0){ //update c bestc = besta+bestb-1; } } return 0; }
712
D
Memory and Scores
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score $a$ and Lexa starts with score $b$. In a single turn, both Memory and Lexa get some integer in the range $[ - k;k]$ (i.e. one integer among $ - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k$) and add them to their current scores. The game has exactly $t$ turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn. Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are $(2k + 1)^{2t}$ games in total. Since the answer can be very large, you should print it modulo $10^{9} + 7$. Please solve this problem for Memory.
One approach to this problem is by first implementing naive DP in $O((kt)^{2})$. The state for this is $(diff, turn)$, and transitions for $(diff, turn)$ is the sum $(diff - 2k, turn - 1) + 2(diff - 2k + 1, turn - 1) + 3(diff - 2k + 2, turn - 1) + ... + (2k + 1)(diff, turn - 1) + 2k(diff + 1, turn - 1) + ...$ $+ diff( + 2k, turn - 1)$. Now, if we use prefix sums of all differences in (turn-1), along with a sliding window technique across the differences, we can cut a factor of $k$, to achieve desired complexity $O(kt^{2})$. However, there is a much nicer solution in $O(kt$ $log$ $kt)$ using generating functions(thanks to minimario). We can compute the coefficients of $\begin{array}{r}{\left({\frac{(1+x+x^{2}+\cdots+x^{2k})}{x^{k}}}\right)^{2l}}\end{array}$, and the coefficient to $x^{i}$ corresponds to the number of ways we can form the difference $i$. To compute these coefficients, we can use the binomial theorem. Time Complexity: $O(kt^{2})$ Time Complexity: $O(kt$ $log$ $kt)$
[ "combinatorics", "dp", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; #define f first #define s second #define pb push_back #define mp make_pair #define FOR(i, a, b) for (int i=a; i<b; i++) #define F0R(i, a) FOR(i, 0, a) const int MAX = 1000005; const int MOD = 1000000007; int f[MAX]; int fi[MAX]; int pos(int a) { return ((ll)a%MOD+MOD)%MOD; } int add(int a, int b) { return ((ll)a+(ll)b)%MOD; } int sub(int a, int b) { return pos(a-b); } int mult(int a, int b) { return (ll)pos(a)*b%MOD; } int sq(int a) { return (ll)a*a%MOD; } int expo(int a, int b) { if (b == 0) { return 1; } if (b%2) { return mult(a, sq(expo(a, b/2))); } else { return sq(expo(a, b/2)); } } int inv(int a) { return expo(a, MOD-2); } int c(int n, int k) { return mult(f[n], mult(fi[k], fi[n-k])); } int poly1[MAX]; int pref2[MAX]; int main() { f[0] = fi[0] = 1; FOR(i, 1, MAX) { f[i] = mult(f[i-1], i); fi[i] = inv(f[i]); } int a, b, k, t; cin >> a >> b >> k >> t; if(b-a > 2*k*t){ cout << 0 << endl; return 0; } F0R(i, 2*t+1) { poly1[(2*k+1)*i] = ((i%2==0)?1:-1)*c(2*t, i); } F0R(i, MAX) { pref2[i] = c(2*t-1+i+1, 2*t); } int lb = 2*k*t+b-a+1; int ub = 4*k*t; int ans = 0; F0R(i, 2*t+1) { int l = lb-(2*k+1)*i; int u = ub-(2*k+1)*i; if (u < 0) { break; } if (l < 0) { ans = add(ans, mult(poly1[(2*k+1)*i], pref2[u])); } else { ans = add(ans, mult(poly1[(2*k+1)*i], sub(pref2[u], pref2[l-1]))); } } cout << ans << endl; }
712
E
Memory and Casinos
There are $n$ casinos lined in a row. If Memory plays at casino $i$, he has probability $p_{i}$ to win and move to the casino on the right ($i + 1$) or exit the row (if $i = n$), and a probability $1 - p_{i}$ to lose and move to the casino on the left ($i - 1$) or also exit the row (if $i = 1$). We say that Memory dominates on the interval $i... j$ if he completes a walk such that, - He starts on casino $i$. - He never looses in casino $i$. - He finishes his walk by winning in casino $j$. Note that Memory can still walk left of the $1$-st casino and right of the casino $n$ and that always finishes the process. Now Memory has some requests, in one of the following forms: - $1$ $i$ $a$ $b$: Set $p_{i}={\frac{a}{b}}$. - $2$ $l$ $r$: Print the probability that Memory will dominate on the interval $l... r$, i.e. compute the probability that Memory will first leave the segment $l... r$ after winning at casino $r$, if she starts in casino $l$. It is guaranteed that at any moment of time $p$ is a \textbf{non-decreasing sequence}, i.e. $p_{i} ≤ p_{i + 1}$ for all $i$ from $1$ to $n - 1$. Please help Memory by answering all his requests!
Lets think about two segments of casinos $[i, j]$ and $[j + 1, n]$. Let $L([a, b])$ denote the probability we dominate on $[a, b]$, and let $R([a, b])$ denote the probability we start on $b$ and end by moving right of $b$. Let $l_{1} = L([i, j])$, $l_{2} = L([j + 1, n])$, $r_{1} = R([i, j])$, $r_{2} = R([j + 1, n])$. You can use a geometric series to figure out both $L([i, n])$ and $R([i, n])$ using only $l_{1}$,$l_{2}$,$r_{1}$, and $r_{2}$. To derive these series, think about the probability we cross over from $j$ to $j + 1$ once, twice, three times, and so on. The actual formulas are, $L([i,n])=\frac{l_{1}l_{2}}{1+r_{1}(l_{2}-1)}$ $R([i,n])=r_{2}+\frac{r_{1}l_{2}(1-r_{2})}{1-r_{1}(1-l_{2})}$ Now we can build a segment tree on the casinos, and use the above to merge segments. Time Complexity: $O(N + QlogN)$
[ "data structures", "math", "probabilities" ]
2,500
#include <bits/stdc++.h> using namespace std; int n; double pr[100000]; pair<double,double> seg[400000]; bool ze(double d){ return (abs(d) <= 0.0000000001); } pair<double,double> merge(pair<double,double> a, pair<double,double> b){ if(ze(a.first+1) && ze(a.second+1)) return b; if(ze(b.first+1) && ze(b.second+1)) return a; double l1 = a.first; double r1 = a.second; double l2 = b.first; double r2 = b.second; if(ze(((l2-1)*r1+1))) return make_pair(0,0); double le = l1*l2/((l2-1)*r1+1); double ri = r2+(r1*l2*(-r2+1))/(-r1*(-l2+1)+1); return make_pair(le,ri); } void build(int no, int b, int e){ if(b==e){ seg[no] = make_pair(pr[b],pr[b]); return; } int mid = (b+e)/2; build(2*no,b,mid); build(2*no+1,mid+1,e); seg[no] = merge(seg[2*no],seg[2*no+1]); } void upd(int no, int b, int e, int i, double val){ if(i<b || i>e) return; if(b==e){ seg[no] = make_pair(val,val); return; } int mid = (b+e)/2; upd(2*no,b,mid,i,val); upd(2*no+1,mid+1,e,i,val); seg[no] = merge(seg[2*no],seg[2*no+1]); } pair<double,double> query(int no, int b, int e, int l, int r){ if(b>r || e<l) return make_pair(-1,-1); if(l<=b && e<=r) return seg[no]; int mid = (b+e)/2; return merge(query(2*no,b,mid,l,r),query(2*no+1,mid+1,e,l,r)); } int main(){ int q; scanf("%d %d", &n, &q); for(int i=0; i < n; i++){ int a,b; scanf("%d %d", &a, &b); pr[i] = (double)a / (double)b; } build(1,0,n-1); for(int que = 0; que < q; que++){ int ty; int a; int b; scanf("%d %d %d", &ty, &a, &b); if(ty==1){ int c; scanf("%d", &c); upd(1,0,n-1,a-1, (double)b / (double)c); } else{ printf("%.20f\n", query(1,0,n-1,a-1,b-1).first); } } return 0; }
713
A
Sonya and Queries
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her $t$ queries, each of one of the following type: - $ + $ $a_{i}$ — add non-negative integer $a_{i}$ to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. - $ - $ $a_{i}$ — delete a single occurrence of non-negative integer $a_{i}$ from the multiset. It's guaranteed, that there is at least one $a_{i}$ in the multiset. - $?$ $s$ — count the number of integers in the multiset (with repetitions) that match some pattern $s$ consisting of $0$ and $1$. In the pattern, $0$ stands for the even digits, while $1$ stands for the odd. Integer $x$ matches the pattern $s$, if the parity of the $i$-th from the right digit in decimal notation matches the $i$-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with $0$-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the $0$-s from the left. For example, if the pattern is $s = 010$, than integers $92$, $2212$, $50$ and $414$ match the pattern, while integers $3$, $110$, $25$ and $1030$ do not.
Lets exchange every digit by value of digit modulo $2$ and receive binary string. We will convert it to binary form in number $r$. $G$ - array for counts. If we have '+' query we increase $G$[$r$]. If we have '-' query we decrease $G$[$r$]. Otherwise we output $G$[$r$].
[ "data structures", "implementation" ]
1,400
null
713
B
Searching Rectangles
Filya just learned new geometry object — rectangle. He is given a field consisting of $n × n$ unit cells. Rows are numbered from bottom to top with integer from $1$ to $n$. Columns are numbered from left to right with integers from $1$ to $n$. Cell, located at the intersection of the row $r$ and column $c$ is denoted as $(r, c)$. Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles. Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie \textbf{fully inside} the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query. Filya knows Sonya really well, so is sure that if he asks more than $200$ questions she will stop to reply.
Assume we have just one rectangle. First we can find its right side. In binary search we check is out rectangle to the left of some line $x_{2}$ using function $get$($1$,$1$,$x_{2}$,$n$). As soon as we found right coordinate we can 'cut' everything to the right of the line, because there is nothing to look. In the same way we will find all sides. $O$($12 * logN$): Main idea is to find a line which will split space in the way that rectangles will lie in different parts, as rectangles are not intersected it is always possible. We can assume that intersected line is parallel to y coordinate and use binary search by $x$. On each step of search we will count amount of rectangles on each side. If we have pair ($1$, $1$) then line is found. If we have pair ($0$, $0$) then intersected line is parallel to $x$ coordinate. Otherwise we should search in the half where we have some rectangles. In worst case we will have $2$ searches each will take $2 * log$($n$) time, also we have $4 * log$($n$) time to find separated rectangle. In total we $2 * 2 * log$($n$) + $2 * 4 * log$($n$)$= 12 * log$($n$). $O$($8 * logN$): We can find first rectangle assuming that here is just one rectangle. In each of four of our search we will assume that rectangle is present if get will return $1$ or $2$. When we have one rectangle we can search second assuming that we can modify get function to $get2$, which will assume coordinates of first rectangle and decrease original value if it is required.
[ "binary search", "constructive algorithms", "interactive" ]
2,200
null
713
C
Sonya and Problem Wihtout a Legend
Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing $n$ positive integers. At one turn you can pick any element and increase or decrease it by $1$. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to $0$.
Lets first solve easier problem. Given an array of number what it is minimal amount of operations ($+ 1$ to element, $- 1$ to element) to make all numbers in array equal? We need to solve this problem for each prefix. Optimal solution would be making all numbers equal to median value of the prefix (middle element in sorted list). For this problem we can simply use two heaps and insert element in right one (removing elements from inserted if need) to keep heaps equal and fit the constraint max_value(Heap1) $ \le $ min_value(Heap2). Now lets solve harder problem. What is minimal amount of operations ($+ 1$ to element, $- 1$ to element) to make array be arithmetics progression with step $1$? We can just reduce number $a_{i}$ in array by value $i$ and will receive previous problem. Finally we have original problem. $Dp_{i}$ - answer for prefix ending in $i$, i.e. number of operations to make prefix of first $i$ elements in increasing order. Also for each $i$ will remember minimal last number in resulting sequence. For each $i$ will bruteforce value $j$ ($i > j$) and calculate answer for $j$ if [$i + 1$, $j$] if arithmetics progression with step $1$. Also we need to assume if median value in [$i + 1$, $j$] is lower than minimal value at i than we cannot update answer for $j$ by answer for $i$.
[ "dp", "sortings" ]
2,300
null
713
D
Animals and Puzzle
Owl Sonya gave a huge lake puzzle of size $n × m$ to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be empty — there was no picture on them. Parts with picture on it are denoted by $1$, while empty parts are denoted by $0$. Rows of the puzzle are numbered from top to bottom with integers from $1$ to $n$, while columns are numbered from left to right with integers from $1$ to $m$. Animals decided to complete the picture and play with it, as it might be even more fun! Owl and hedgehog ask each other some queries. Each query is provided by four integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ which define the rectangle, where $(x_{1}, y_{1})$ stands for the coordinates of the up left cell of the rectangle, while $(x_{2}, y_{2})$ stands for the coordinates of the bottom right cell. The answer to the query is the size of the maximum \textbf{square} consisting of picture parts only (only parts denoted by $1$) and located fully inside the query rectangle. Help Sonya and Filya answer $t$ queries.
First lets calculate $dp[i][j]$ - maximum square ending in cell ($i$, $j$). For each cell if input matrix contain $0$ then $dp[i][j] = 0$ else $dp_{}[i][j] = min$($dp[i - 1][j - 1]$, $dp[i-1][j]$, $dp[i][j-1]$)$+ 1$. We will use binary search to find the answer. Lets fix some value $x$. For each square ($i$, $j$)..($i + x - 1$, $j + x - 1$) we need to find maximum and compare it to $x$. To find maximum we can use $2D$ $sparse$ $table$. So preprocessing takes $O$($NMlogNlogM$), and query works in $O$($logN$).
[ "binary search", "data structures" ]
2,700
null
713
E
Sonya Partymaker
Owl Sonya decided to become a partymaker. To train for this role she gather all her owl friends in the country house. There are $m$ chairs located in a circle and consequently numbered with integers from $1$ to $m$. Thus, chairs $i$ and $i + 1$ are neighbouring for all $i$ from $1$ to $m - 1$. Chairs $1$ and $m$ are also neighbouring. Some chairs are occupied by her friends. There are $n$ friends in total. No two friends occupy the same chair. Rules are the following: - Each participant removes from the game the chair he is currently sitting on. - Each of the participants choose a direction that she will follow: clockwise (indices increase, from $m$ goes to $1$) and counter-clockwise (indices decrease, from $1$ goes to $m$). This direction may coincide or be different for any pair of owls. - Each turn all guests move one step in the chosen directions. If some guest move to the position with a chair there, he removes this chair from the game. - Game ends if there are no more chairs left in the game. Owls are very busy and want to get rid of the game as soon as possible. They cooperate to pick the direction. Your goal is to find the minimum number o moves required to finish the game.
Will use binary search to find the answer. Assume that we need to know if it is enough $x$ minutes to visit each vertex. Lets $dp[i][0...1]$ is equal to minimum number of vertices to the left of $i$, which wasn't visited yet, second parameter is equal to $1$, if we have't launched robot from vertex $i$. I.e. when $dp[i][j] > 0$ vertices $[i-dp[i][j], i-1]$ haven't been visited, and if $dp[i][j] < 0$ then $dp[i][j]$ vertices to the right we still can visit. We need to calculate such DP for two starting states ($dp[0][0] = 0$, $dp[0][1] = 0$). Now we need to implement next: - if $0 < dp[i][1] \le x$ then distance can be walked and we need to update $dp[i][0]$ by $0$ - if $dp[i][1] \le 0$ then we can update $dp[i][0]$ by $-x$ - using $dp[i][0]$, update $dp[i + 1][1]$ - using $dp[i][1]$, update $dp[i + 1][0]$ Walk in time $x$ is also possible if $dp[n][0..1$ (depending on start state)] $ \le 0$. Need to assume few other facts: if $dp[n][j] \neq 0$ then we can repeat $DP$ with param $dp[0][j] = dp[n][j]$, and if, $dp[n][j] \le dp[0][j]$, then distance can be walked To assume every case we need to calculate this DP for each pair of sequent vertices
[ "binary search", "dp" ]
3,300
null
714
A
Meeting of Old Friends
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute $l_{1}$ to minute $r_{1}$ inclusive. Also, during the minute $k$ she prinks and is unavailable for Filya. Filya works a lot and he plans to visit Sonya from minute $l_{2}$ to minute $r_{2}$ inclusive. Calculate the number of minutes they will be able to spend together.
Lets find two numbers $l$ and $r$ - lower and upper bound on time which guys can spend together. $l =$ $max$($l_{1}$, $l_{2}$), $r =$ $min$($r_{1}$,$r_{2}$). If $l > r$ then answer is definitely $0$. In case $l \le r$ we need to number $k$ belongs to the interval. If is it true - answer is $r - l$, otherwise it is $r - l + 1$.
[ "implementation", "math" ]
1,100
null
714
B
Filya and Homework
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. First, he pick an integer $x$ and then he adds $x$ to some elements of the array (no more than once), subtract $x$ from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal. Now he wonders if it's possible to pick such integer $x$ and change some elements of the array using this $x$ in order to make all elements equal.
Answer can be calculated according to next options: 1). If all numbers are equal - answer is <<Yes>> 2). If there are two distinct numbers in the array - answer is <<Yes>> 3). If there are at least four distinct numbers in the array - answer is <<No>> 4). In other case lets there are three distinct numbers $q < w < e$, answer is <<Yes>> if and only if $2 * w = q + e$.
[ "implementation", "sortings" ]
1,200
null
715
A
Plus and Square Root
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '$ + $' (plus) and '$\lor$' (square root). Initially, the number $2$ is displayed on the screen. There are $n + 1$ levels in the game and ZS the Coder start at the level $1$. When ZS the Coder is at level $k$, he can : - Press the '$ + $' button. This increases the number on the screen by exactly $k$. So, if the number on the screen was $x$, it becomes $x + k$. - {Press the '$\lor\overset{\lor}{\to}$' button}. Let the number on the screen be $x$. After pressing this button, the number becomes $\sqrt{x}$. After that, ZS the Coder levels up, so his current level becomes $k + 1$. This button can only be pressed when $x$ is a \textbf{perfect square}, i.e. $x = m^{2}$ for some positive integer $m$. Additionally, after each move, if ZS the Coder is at level $k$, and the number on the screen is $m$, then \textbf{$m$ must be a multiple of $k$}. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level $4$ and current number is $100$, he presses the '$\lor\overset{\lor}{\to}$' button and the number turns into $10$. Note that at this moment, $10$ is not divisible by $4$, but this press is still valid, because after it, ZS the Coder is at level $5$, and $10$ is divisible by $5$. ZS the Coder needs your help in beating the game — he wants to reach level $n + 1$. In other words, he needs to press the '$\lor$' button $n$ times. Help him determine the number of times he should press the '$ + $' button before pressing the '$\lor\overset{\lor}{\to}$' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level $n + 1$, but not necessarily a sequence minimizing the number of presses.
Firstly, let $a_{i}(1 \le i \le n)$ be the number on the screen before we level up from level $i$ to $i + 1$. Thus, we require all the $a_{i}$s to be perfect square and additionally to reach the next $a_{i}$ via pressing the plus button, we require $a_{i+1}\equiv\sqrt{a_{i}}(m o d(i+1))$ and $a_{i+1}\geq{\sqrt{a_{i}}}$ for all $1 \le i < n$. Additionally, we also require $a_{i}$ to be a multiple of $i$. Thus, we just need to construct a sequence of such integers so that the output numbers does not exceed the limit $10^{18}$. There are many ways to do this. The third sample actually gave a large hint on my approach. If you were to find the values of $a_{i}$ from the second sample, you'll realize that it is equal to $4, 36, 144, 400$. You can try to find the pattern from here. My approach is to use $a_{i} = [i(i + 1)]^{2}$. Clearly, it is a perfect square for all $1 \le i \le n$ and when $n = 100000$, the output values can be checked to be less than $10^{18}$ Unable to parse markup [type=CF_TEX] The constraints $a_{i}$ must be a multiple of $i$ was added to make the problem easier for Div. 1 A. Time Complexity : $O(n)$
[ "constructive algorithms", "math" ]
1,600
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll n; cin >> n; for(ll i = 1; i <= n; i++) { if(i == 1) cout << 2 << '\n'; else cout << i*(i+1)*(i+1)-(i-1) << '\n'; } return 0; }
715
B
Complete The Graph
ZS the Coder has drawn an undirected graph of $n$ vertices numbered from $0$ to $n - 1$ and $m$ edges between them. Each edge of the graph is weighted, each weight is a \textbf{positive integer}. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign \textbf{positive integer} weight to each of the edges which weights were erased, so that the length of the shortest path between vertices $s$ and $t$ in the resulting graph is exactly $L$. Can you help him?
This problem is actually quite simple if you rule out the impossible conditions. Call the edges that does not have fixed weight variable edges. First, we'll determine when a solution exists. Firstly, we ignore the variable edges. Now, find the length of the shortest path from $s$ to $e$. If this length is $< L$, there is no solution, since even if we replace the $0$ weights with any positive weight the shortest path will never exceed this shortest path. Thus, if the length of this shortest path is $< L$, there is no solution. (If no path exists we treat the length as $ \infty $.) Next, we replace the edges with $0$ weight with weight $1$. Clearly, among all the possible graphs you can generate by replacing the weights, this graph will give the minimum possible shortest path from $s$ to $e$, since increasing any weight will not decrease the length of the shortest path. Thus, if the shortest path of this graph is $> L$, there is no solution, since the shortest path will always be $> L$. If no path exists we treat the length as $ \infty $. Other than these two conditions, there will always be a way to assign the weights so that the shortest path from $s$ to $e$ is exactly $L$! How do we prove this? First, consider all paths from $s$ to $e$ that has at least one $0$ weight edge, as changing weights won't affect the other paths. Now, we repeat this algorithm. Initially, assign all the weights as $1$. Then, sort the paths in increasing order of length. If the length of the shortest path is equal to $L$, we're done. Otherwise, increase the weight of one of the variable edges on the shortest path by $1$. Note that this will increase the lengths of some of the paths by $1$. It is not hard to see that by repeating these operations the shortest path will eventually have length $L$, so an assignment indeed exists. Now, we still have to find a valid assignment of weights. We can use a similar algorithm as our proof above. Assign $1$ to all variable edges first. Next, we first find and keep track of the shortest path from $s$ to $e$. Note that if this path has no variable edges it must have length exactly $L$ or strictly more than $L$, so either we're already done or the shortest path contains variable edges and the length is strictly less than $L$. (otherwise we're done) From now on, whenever we assign weight to a variable edge (after assigning $1$ to every variable edge), we call the edge assigned. Now, mark all variable edges not on the shortest path we found as $ \infty $ weight. (we can choose any number greater than $L$ as $ \infty $) Next, we will find the shortest path from $s$ to $e$, and replace the weight of an unassigned variable edge such that the length of the path becomes equal to $L$. Now, we don't touch the assigned edges again. While the shortest path from $s$ to $e$ is still strictly less than $L$, we repeat the process and replace a variable edge that is not assigned such that the path length is equal to $L$. Note that this is always possible, since otherwise this would've been the shortest path in one of the previous steps. Eventually, the shortest path from $s$ to $e$ will have length exactly $L$. It is easy to see that we can repeat this process at most $n$ times because we are only replacing the edges which are on the initial shortest path we found and there are less than $n$ edges to replace (we only touch each edge at most once). Thus, we can find a solution after less than $n$ iterations. So, the complexity becomes $O(m n\log n)$. This is sufficient to pass all tests. What if the constraints were $n, m \le 10^{5}$? Can we do better? Yes! Thanks to HellKitsune who found this solution during testing. First, we rule out the impossible conditions like we did above. Then, we assign all the variable edges with $ \infty $ weight. We enumerate the variable edges arbitarily. Now, we binary search to find the minimal value $p$ such that if we make all the variable edges numbered from $1$ to $p$ have weight $1$ and the rest $ \infty $, then the shortest path from $s$ to $e$ has length $ \le L$. Now, note that if we change the weight of $p$ to $ \infty $ the length of shortest path will be more than $L$. (if $p$ equals the number of variable edges, the length of the shortest path is still more than $L$ or it will contradict the impossible conditions) If the weight is $1$, the length of the shortest path is $ \le L$. So, if we increase the weight of edge $p$ by $1$ repeatedly, the length of the shortest path from $s$ to $e$ will eventually reach $L$, since this length can increase by at most $1$ in each move. So, since the length of shortest path is non-decreasing when we increase the weight of this edge, we can binary search for the correct weight. This gives an $O(m\log n(\log m+\log L))$ solution. Time Complexity : $O(m n\log n)$ or $O(m\log n(\log m+\log L))$
[ "binary search", "constructive algorithms", "graphs", "shortest paths" ]
2,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 1001; const int M = 10001; const ll INF = ll(1e18); int n, m, l, s, e; struct edge { int to; ll w; int label; edge(int _to, int _w, int _label){to = _to, w = _w, label = _label;} }; int edgecnt = -1; vector<edge> adj[N]; ll dist[N]; set<ii> used; ll dijk(int p, ll val) { for(int i = 0; i < n; i++) dist[i] = INF; dist[s] = 0; priority_queue<ii, vector<ii>, greater<ii> > pq; pq.push(ii(0, s)); while(!pq.empty()) { int u = pq.top().se; ll d = pq.top().fi; pq.pop(); for(int i = 0; i < adj[u].size(); i++) { edge tmp = adj[u][i]; int v = tmp.to; ll w = tmp.w; int lab = tmp.label; if(lab >= 0) { if(lab < p) w = 1; else if(lab == p) w = val; else w = ll(1e14); } if(d + w < dist[v]) { dist[v] = d + w; pq.push(ii(dist[v], v)); } } } return dist[e]; } void setw(int p, ll val) { for(int i = 0; i < n; i++) { for(int j = 0; j < adj[i].size(); j++) { int lab = adj[i][j].label; if(lab >= 0) { if(lab < p) { adj[i][j].w = 1; } else if(lab == p) { adj[i][j].w = val; } else { adj[i][j].w = INF; } } } } } void print() { cout << "YES\n"; for(int i = 0; i < n; i++) { for(int j = 0; j < adj[i].size(); j++) { edge tmp = adj[i][j]; int v = tmp.to; ll w = tmp.w; if(used.find(ii(i, v)) == used.end()) { cout << i << ' ' << v << ' ' << w << '\n'; used.insert(ii(i, v)); used.insert(ii(v, i)); } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> l >> s >> e; for(int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; int lab = -1; if(w == 0) { lab = ++edgecnt; } adj[u].pb(edge(v, w, lab)); adj[v].pb(edge(u, w, lab)); } ll x = dijk(edgecnt, 1); ll y = dijk(-1, 1); if(!(x <= l && l <= y)) { cout << "NO\n"; return 0; } ll lo = -1; ll hi = edgecnt; ll mid, ans; while(lo <= hi) { mid = (lo+hi)/2; if(dijk(mid, 1) <= l) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } //now [0..ans] as 1 will give <= L whereas [0..ans - 1] as 1 will give > L if(ans == -1) { setw(-1, 0); print(); return 0; } lo = 1; hi = INF; int ans2 = 0; while(lo <= hi) { mid = (lo+hi)>>1; if(dijk(ans, mid) <= l) { ans2 = mid; lo = mid + 1; } else { hi = mid - 1; } } //cerr << ans << ' ' << ans2 << '\n'; setw(ans, ans2); print(); }
715
C
Digit Tree
ZS the Coder has a large tree. It can be represented as an undirected connected graph of $n$ vertices numbered from $0$ to $n - 1$ and $n - 1$ edges between them. There is a single \textbf{nonzero} digit written on each edge. One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive integer $M$, which is \textbf{coprime} to $10$, i.e. $\operatorname*{gcd}(M,10)=1$. ZS consider an \textbf{ordered pair} of distinct vertices $(u, v)$ interesting when if he would follow the shortest path from vertex $u$ to vertex $v$ and write down all the digits he encounters on his path in the same order, he will get a decimal representaion of an integer divisible by $M$. Formally, ZS consider an ordered pair of distinct vertices $(u, v)$ interesting if the following states true: - Let $a_{1} = u, a_{2}, ..., a_{k} = v$ be the sequence of vertices on the shortest path from $u$ to $v$ in the order of encountering them; - Let $d_{i}$ ($1 ≤ i < k$) be the digit written on the edge between vertices $a_{i}$ and $a_{i + 1}$; - The integer $\overline{{{d_{1}d_{2}\cdot\cdot\cdot\cdot d_{k-1}}}}=\sum_{i=1}^{k-1}d_{i}\cdot10^{k-1-i}$ is divisible by $M$. Help ZS the Coder find the number of interesting pairs!
Compared to the other problems, this one is more standard. The trick is to first solve the problem if we have a fixed vertex $r$ as root and we want to find the number of paths passing through $r$ that works. This can be done with a simple tree dp. For each node $u$, compute the number obtained when going from $r$ down to $u$ and the number obtained when going from $u$ up to $r$, where each number is taken modulo $M$. This can be done with a simple dfs. To calculate the down value, just multiply the value of the parent node by $10$ and add the value on the edge to it. To calculate the up value, we also need to calculate the height of the node. (i.e. the distance from $u$ to $r$) Then, if we let $h$ be the height of $u$, $d$ be the digit on the edge connecting $u$ to its parent and $val$ be the up value of the parent of $u$, then the up value for $u$ is equal to $10^{h - 1} \cdot d + val$. Thus, we can calculate the up and down value for each node with a single dfs. Next, we have to figure out how to combine the up values and down values to find the number of paths passing through $r$ that are divisible by $M$. For this, note that each path is the concatenation of a path from $u$ to $r$ and $r$ to $v$, where $u$ and $v$ are pairs of vertices from different subtrees, and the paths that start from $r$ and end at $r$. For the paths that start and end at $r$ the answer can be easily calculated with the up and down values (just iterate through all nodes as the other endpoint). For the other paths, we iterate through all possible $v$, and find the number of vertices $u$ such that going from $u$ to $v$ will give a multiple of $M$. Since $v$ is fixed, we know its height and down value, which we denote as $h$ and $d$ respectively. So, if the up value of $u$ is equal to $up$, then $up \cdot 10^{h} + d$ must be a multiple of $M$. So, we can solve for $up$ to be $- d \cdot 10^{ - h}$ modulo $M$. Note that in this case the multiplicative inverse of $10$ modulo $M$ is well-defined, as we have the condition $\operatorname*{gcd}(M,10)=1$. To find the multiplicative inverse of $10$, we can find $ \phi (M)$ and since by Euler's Formula we have $x^{ \phi (M)} \equiv 1(modM)$ if $\operatorname*{gcd}(x,M)=1$, we have $x^{ \phi (M) - 1} \equiv x^{ - 1}(modM)$, which is the multiplicative inverse of $x$ (in this case we have $x = 10$) modulo $M$. After that, finding the $up$ value can be done by binary exponentiation. Thus, we can find the unique value of $up$ such that the path from $u$ to $v$ is a multiple of $M$. This means that we can just use a map to store the up values of all nodes and also the up values for each subtree. Then, to find the number of viable nodes $u$, find the required value of $up$ and subtract the number of suitable nodes that are in the same subtree as $v$ from the total number of suitable nodes. Thus, for each node $v$, we can find the number of suitable nodes $u$ in $O(\log M O D)$ time. Now, we have to generalize this for the whole tree. We can use centroid decomposition. We pick the centroid as the root $r$ and find the number of paths passing through $r$ as above. Then, the other paths won't pass through $r$, so we can remove $r$ and split the tree into more subtrees, and recursively solve for each subtree as well. Since each subtree is at most half the size of the original tree, and the time taken to solve the problem where the path must pass through the root for a single tree takes time proportional to the size of the tree, this solution works in $O(n\log n(\log n+\log M O D))$ time, where the other $\log n$ comes from using maps. Time Complexity : $O(n\log n(\log n+\log M O D))$
[ "dfs and similar", "divide and conquer", "dsu", "trees" ]
2,700
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 1e5 + 1; const int MAX = 1e9; int MOD, n; bool isprime[100001]; vector<ll> primes; vector<ii> adj[N]; int subsize[N]; bool visited[N]; int treesize; vi clrlist; ll up[N]; ll down[N]; int h[N]; int PHI; int dppart[N]; ll mult(ll a, ll b) { return (a*b)%MOD; } ll add(ll a, ll b) { return (a+b+MOD)%MOD; } ll modpow(ll a, ll b) { ll r = 1; while(b) { if(b&1) r=(r*a)%MOD; a=(a*a)%MOD; b>>=1; } return r; } void Sieve(int n) { memset(isprime, 1, sizeof(isprime)); isprime[1] = false; for(int i = 2; i <= n; i++) { if(isprime[i]) { primes.pb(i); for(int j = 2*i; j <= n; j += i) { isprime[j] = false; } } } } int phi(int n) { ll num = 1; ll num2 = n; for(ll i = 0; primes[i]*primes[i] <= n; i++) { if(n%primes[i]==0) { num2/=primes[i]; num*=(primes[i]-1); } while(n%primes[i]==0) { n/=primes[i]; } } if(n>1) { num2/=n; num*=(n-1); } n = 1; num*=num2; return num; } ll inv(ll a) { return modpow(a, PHI-1); } void dfs(int u, int par) { if(par == -1) clrlist.clear(); subsize[u] = 1; clrlist.pb(u); for(int i = 0; i < adj[u].size(); i++) { int v = adj[u][i].fi; if(visited[v]) continue; if(v == par) continue; dfs(v, u); subsize[u] += subsize[v]; } if(par == -1) treesize = subsize[u]; } int centroid(int u, int par) { for(int i = 0; i < adj[u].size(); i++) { int v = adj[u][i].fi; if(visited[v]) continue; if(v == par) continue; if(subsize[v]*2 > treesize) return centroid(v, u); } return u; } int parts = 0; void fill(int u, int p, int cent) { if(p == cent) { dppart[u] = parts; parts++; } else if(p != -1) { dppart[u] = dppart[p]; } for(int i = 0; i < adj[u].size(); i++) { int v = adj[u][i].fi; int w = adj[u][i].se; if(v == p || visited[v]) continue; down[v] = add(mult(down[u], 10), w); up[v] = add(up[u], mult(modpow(10, h[u]), w)); h[v] = h[u] + 1; fill(v, u, cent); //cout << v << ' ' << u << ' ' << up[v] << ' ' << up[u] << '\n'; } } ll solve(int cent) { for(int i = 0; i < clrlist.size(); i++) { up[clrlist[i]] = 0; down[clrlist[i]] = 0; h[clrlist[i]] = 0; } parts = 0; fill(cent, -1, cent); parts--; dppart[cent] = -1; map<ll,ll> tot; //only count up vector<map<ll,ll> > vec; //only count up, but in specific subtree vec.resize(parts+1); tot[0]++; for(int i = 0; i < clrlist.size(); i++) { int u = clrlist[i]; //cout << u << ' ' << up[u] << ' ' << down[u] << '\n'; if(u == cent) continue; tot[up[u]]++; vec[dppart[u]][up[u]]++; } ll ans = 0; for(int i = 0; i < clrlist.size(); i++) { int u = clrlist[i]; int ht = h[u]; int pt = dppart[u]; if(u == cent) { ans += (tot[0] - 1); //exclude cent as the vertex } else { ll val = ((-down[u])%MOD+MOD)%MOD; val = mult(val, inv(modpow(10, ht))); ans += (tot[val] - vec[pt][val]); } } return ans; } ll compsolve(int u) { dfs(u, -1); int cent = centroid(u, -1); ll ans = solve(cent); //cout << u << ' ' << cent << ' ' << ans << '\n'; visited[cent] = true; for(int i = 0; i < adj[cent].size(); i++) { int v = adj[cent][i].fi; if(!visited[v]) ans += compsolve(v); } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> MOD; if(MOD == 1) { cout << ll(n)*ll(n - 1); return 0; } Sieve(100000); PHI = phi(MOD); for(int i = 0; i < n - 1; i++) //tree is 0-indexed { int u, v, w; cin >> u >> v >> w; adj[u].pb(ii(v, w)); adj[v].pb(ii(u, w)); } cout << compsolve(0) << '\n'; return 0; }
715
D
Create a Maze
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of $n × m$ rooms, and the rooms are arranged in $n$ rows (numbered from the top to the bottom starting from $1$) and $m$ columns (numbered from the left to the right starting from $1$). The room in the $i$-th row and $j$-th column is denoted by $(i, j)$. A player starts in the room $(1, 1)$ and wants to reach the room $(n, m)$. Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting $(i, j)$ and $(i, j + 1)$ is locked, then we can't go from $(i, j)$ to $(i, j + 1)$. Also, one can only travel between the rooms downwards (from the room $(i, j)$ to the room $(i + 1, j)$) or rightwards (from the room $(i, j)$ to the room $(i, j + 1)$) provided the corresponding door is not locked. \begin{center} {\small This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door.} \end{center} ZS the Coder considers a maze to have difficulty $x$ if there is exactly $x$ ways of travelling from the room $(1, 1)$ to the room $(n, m)$. Two ways are considered different if they differ by the sequence of rooms visited while travelling. Your task is to create a maze such that its difficulty is exactly equal to $T$. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right?
The solution to this problem is quite simple, if you get the idea. Thanks to danilka.pro for improving the solution to the current constraints which is much harder than my original proposal. Note that to calculate the difficulty of a given maze, we can just use dp. We write on each square (room) the number of ways to get from the starting square to it, and the number written on $(i, j)$ will be the sum of the numbers written on $(i - 1, j)$ and $(i, j - 1)$, and the edge between $(i - 1, j)$ and $(i, j)$ is blocked, we don't add the number written on $(i - 1, j)$ and similarly for $(i, j - 1)$. We'll call the rooms squares and the doors as edges. We'll call locking doors as edge deletions. First, we look at several attempts that do not work. Write $t$ in its binary representation. To solve the problem, we just need to know how to construct a maze with difficulty $2x$ and $x + 1$ from a given maze with difficulty $x$. The most direct way to get from $x$ to $2x$ is to increase both dimensions of the maze by $1$. Let's say the bottom right square of the grid was $(n, n)$ and increased to $(n + 1, n + 1)$. So, the number $x$ is written at $(n, n)$. Then, we can block off the edge to the left of $(n + 1, n)$ and above $(n, n + 1)$. This will make the numbers in these two squares equal to $x$, so the number in square $(n + 1, n + 1)$ would be $2x$, as desired. To create $x + 1$ from $x$, we can increase both dimensions by $1$, remove edges such that $(n + 1, n)$ contains $x$ while $(n, n + 1)$ contains $1$ (this requires deleting most of the edges joining the $n$-th column and $(n + 1)$-th column. Thus, the number in $(n, n)$ would be $x + 1$. This would've used way too many edge deletions and the size of the grid would be too large. This was the original proposal. There's another way to do it with binary representation. We construct a grid with difficulty $2x$ and $2x + 1$ from a grid with difficulty $x$. The key idea is to make use of surrounding $1$s and maintaining it with some walls so that $2x + 1$ can be easily constructed. This method is shown in the picture below. This method would've used around $120 \times 120$ grid and $480$ edge deletions, which is too large to pass. Now, what follows is the AC solution. Since it's quite easy once you get the idea, I recommend you to try again after reading the hint. To read the full solution, click on the spoiler tag. Hint : Binary can't work since there can be up to $60$ binary digits for $t$ and our grid size can be at most $50$. In our binary solution we used a $2 \times 2$ grid to multiply the number of ways by $2$. What about using other grid sizes instead? Our AC solution uses base $6$ instead of binary. Write $t$ in base $6$. Note that $t$ has at most $24$ digits in base $6$, so to add a new digit we can increase the dimensions by $2$ and the number of deleted edges can be up to $12$ per digit. We'll construct such a way. This method is explained in the picture below. The key is to first construct a grid which has $0$ in it, then find a way to get $6x + i$ for all $0 \le i \le 5$ from $x$ by maintaining a wall of $1$s around the squares. This method uses a $50 \times 50(2 \cdot 24 + 2 = 50)$ grid and at most $24 \cdot 12 + 2 = 290$ edge deletions and will get AC. Of course, this might not be the only way to solve this problem. Can you come up with other ways of solving this or reducing the constraints even further? (Open Question) Time Complexity : $O(\log t)$
[ "constructive algorithms" ]
3,100
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int INF = 1e9 + 7; const int MOD = 1e9 + 7; typedef pair<ii,ii> move; set<move> ans; int curx, cury; bool isvalid(move x) { if(x.fi.fi > 0 && x.se.fi > 0 && x.fi.se > 0 && x.se.se > 0 && x.fi.fi <= curx && x.fi.se <= cury && x.se.fi <= curx && x.se.se <= cury) return true; return false; } void edge(int x1, int y1, int x2, int y2) { ans.insert(mp(mp(x1, y1), mp(x2, y2))); } void add(int bit) { int x = curx; edge(x,x+2,x,x+3); edge(x+1,x+2,x+1,x+3); edge(x+2,x,x+3,x); edge(x+2,x+1,x+3,x+1); edge(x-2,x+3,x-1,x+3); edge(x,x+4,x+1,x+4); edge(x+3,x-2,x+3,x-1); edge(x+4,x,x+4,x+1); edge(x-1,x+1,x,x+1); if(bit%3==0) edge(x-1,x+2,x,x+2); if(bit%3!=2) edge(x+2,x-1,x+2,x); if(bit<3) edge(x+1,x-1,x+1,x); curx += 2; cury += 2; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll t; cin >> t; vector<int> digits; while(t) { digits.pb(t%6); t/=6; } reverse(digits.begin(), digits.end()); edge(1, 2, 2, 2); edge(2, 1, 2, 2); curx = 2; cury = 2; for(int i = 0; i < digits.size(); i++) { add(digits[i]); } cout << curx << ' ' << cury << '\n'; vector<move> clr; for(set<move>::iterator it = ans.begin(); it != ans.end(); it++) { if(!isvalid(*it)) { clr.pb(*it); } } for(int i = 0; i < clr.size(); i++) { ans.erase(clr[i]); } cout << ans.size() << '\n'; for(set<move>::iterator it = ans.begin(); it != ans.end(); it++) { move tmp = (*it); cout << tmp.fi.fi << ' ' << tmp.fi.se << ' ' << tmp.se.fi << ' ' << tmp.se.se << '\n'; } }
715
E
Complete the Permutations
ZS the Coder is given two permutations $p$ and $q$ of ${1, 2, ..., n}$, but some of their elements are replaced with $0$. The distance between two permutations $p$ and $q$ is defined as the minimum number of moves required to turn $p$ into $q$. A move consists of swapping exactly $2$ elements of $p$. ZS the Coder wants to determine the number of ways to replace the zeros with positive integers from the set ${1, 2, ..., n}$ such that $p$ and $q$ are permutations of ${1, 2, ..., n}$ and the distance between $p$ and $q$ is exactly $k$. ZS the Coder wants to find the answer for all $0 ≤ k ≤ n - 1$. Can you help him?
We'll slowly unwind the problem and reduce it to something easier to count. First, we need to determine a way to tell when the distance between $p$ and $q$ is exactly $k$. This is a classic problem but I'll include it here for completeness. Let $f$ denote the inverse permutation of $q$. So, the minimum number of swaps to transform $p$ into $q$ is the minimum number of swaps to transform $p_{fi}$ into the identity permutation. Construct the graph where the edges are $i\rightarrow p_{f},$ for all $1 \le i \le n$. Now, note that the graph is equivalent to $q_{i}\rightarrow p_{i}$ and is composed of disjoint cycles after $q_{i}$ and $p_{i}$ are filled completely. Note that the direction of the edges doesn't matter so we consider the edges to be $p_{i}\to q_{i}$ for all $1 \le i \le n$. Note that if the number of cycles of the graph is $t$, then the minimum number of swaps needed to transform $p$ into $q$ would be $n - t$. (Each swap can break one cycle into two) This means we just need to find the number of ways to fill in the empty spaces such that the number of cycles is exactly $i$ for all $1 \le i \le n$. Now, some of the values $p_{i}$ and $q_{i}$ are known. The edges can be classified into four types : A-type : The edges of the form $x\to{\mathfrak{Y}}$, i.e. $p_{i}$ is known, $q_{i}$ isn't. B-type : The edges of the form $\gamma\to x$, i.e. $q_{i}$ is known, $p_{i}$ isn't. C-type : The edges of the form $x\to y$, i.e. both $p_{i}$ and $q_{i}$ are known. D-type : The edges of the form $\gamma\rightarrow\gamma$, i.e. both $p_{i}$ and $q_{i}$ are unknown. Now, the problem reduces to finding the number of ways to assign values to the question marks such that the number of cycles of the graph is exactly $i$ for all $1 \le i \le n$. First, we'll simplify the graph slightly. While there exists a number $x$ appears twice (clearly it can't appear more than twice) among the edges, we will combine the edges with $x$ together to simplify the graph. If there's an edge $x\to x$, then we increment the total number of cycles by $1$ and remove this edge from the graph. If there is an edge $a\to x$ and $x\to b$, where $a$ and $b$ might be some given numbers or question marks, then we can merge them together to form the edge $a\to b$. Clearly, these are the only cases for $x$ to appear twice. Hence, after doing all the reductions, we're reduced to edges where each known number appears at most once, i.e. all the known numbers are distinct. We'll do this step in $O(n^{2})$. For each number $x$, store the position $i$ such that $p_{i} = x$ and also the position $j$ such that $q_{j} = x$, if it has already been given and $- 1$ otherwise. So, we need to remove a number when the $i$ and $j$ stored are both positive. We iterate through the numbers from $1$ to $n$. If we need to remove a number, we go to the two positions where it occur and replace the two edges with the new merged one. Then, recompute the positions for all numbers (takes $O(n)$ time). So, for each number, we used $O(n)$ time. (to remove naively and update positions) Thus, the whole complexity for this part is $O(n^{2})$. (It is possible to do it in $O(n)$ with a simple dfs as well. Basically almost any correct way of doing this part that is at most $O(n^{3})$ works, since the constraints for $n$ is low) Now, suppose there are $m$ edges left and $p$ known numbers remain. Note that in the end when we form the graph we might join edges of the form $a\rightarrow?$ and $\gamma\rightarrow b$ (where $a$ and $b$ are either fixed numbers or question marks) together. So, the choice for the $?$ can be any of the $m - p$ remaining unused numbers. Note that there will be always $m - p$ such pairs so we need to multiply our answer by $(m - p)!$ in the end. Also, note that the $?$ are distinguishable, and order is important when filling in the blanks. So, we can actually reduce the problem to the following : Given integers $a, b, c, d$ denoting the number of A-type, B-type, C-type, D-type edges respectively. Find the number of ways to create $k$ cycles using them, for all $1 \le k \le n$. Note that the answer is only dependent on the values of $a, b, c, d$ as the numbers are all distinct after the reduction. First, we'll look at how to solve the problem for $k = 1$. We need to fit all the edges in a single cycle. First, we investigate what happens when $d = 0$. Note that we cannot have a B-type and C-type edge before an A-type or C-type edge, since all numbers are distinct so these edges can't be joined together. Similarly, an A or C-type edge cannot be directly after a B or C-type edge. Thus, with these restrictions, it is easy to see that the cycle must contain either all A-type edges or B-type edges. So, the answer can be easily calculated. It is also important to note that if we ignore the cyclic property then a contiguous string of edges without D must be of the form AA...BB.. or AA...CBB..., where there is only one C, and zero or more As and Bs. Now, if $d \ge 1$, we can fix one of the D-type edges as the front of the cycle. This helps a lot because now we can ignore the cyclic properties. (we can place anything at the end of the cycle because D-type edges can connect with any type of edges) So, we just need to find the number of ways to make a length $n - 1$ string with $a$ As, $b$ Bs, $c$ Cs and $d - 1$ Ds. In fact, we can ignore the fact that the A-type edges, B-type edges, C-type edges and D-type edges are distinguishable and after that multiply the answer by $a!b!c!(d - 1)!$. We can easily find the number of valid strings we can make. First, place all the Ds. Now, we're trying to insert the As, Bs and Cs into the $d$ empty spaces between, after and before the Ds. The key is that by our observation above, we only care about how many As, Bs and Cs we insert in each space since after that the way to put that in is uniquely determined. So, to place the As and Bs, we can use the balls in urns formula to find that the number of ways to place the As is $\textstyle{\binom{a+d-1}{d-1}}$ and the number of ways to place the Bs is $\textstyle{\binom{b+d-1}{d-1}}$. The number of ways to place the Cs is $\textstyle{\binom{d}{x}}$, since we choose where the Cs should go. Thus, it turns out that we can find the answer in $O(1)$ (with precomputing binomial coefficients and factorials) when $k = 1$. We'll use this to find the answer for all $k$. In the general case, there might be cycles that consists entirely of As and entirely of Bs, and those that contains at least one D. We call them the A-cycle, B-cycle and D-cycles respectively. Now, we precompute $f(n, k)$, the number of ways to form $k$ cycles using $n$ distinguishable As. This can be done with a simple dp in $O(n^{3})$. We iterate through the number of As we're using for the first cycle. Then, suppose we use $m$ As. The number of ways to choose which of the $m$ As to use is $\binom{n}{m}$ and we can permute them in $(m - 1)!$ ways inside the cycle. (not $m!$ because we have to account for all the cyclic permutations) Also, after summing this for all $m$, we have to divide the answer by $k$, to account for overcounting the candidates for the first cycle (the order of the $k$ cycles are not important) Thus, $f(n, k)$ can be computed in $O(n^{3})$. First, we see how to compute the answer for a single $k$. Fix $x, y, e, f$, the number of A-cycles, B-cycles, number of As in total among the A-cycles and number of Bs in total among the B-cycles. Then, since $k$ is fixed, we know that the number of D-cycles is $k - x - y$. Now, we can find the answer in $O(1)$. First, we can use the values of $f(e, x), f(f, y), f(d, k - x - y)$ to determine the number of ways to place the Ds, and the As, Bs that are in the A-cycles and B-cycles. Then, to place the remaining As, Bs and Cs, we can use the same method as we did for $k = 1$ in $O(1)$, since the number of spaces to place them is still the same. (You can think of it as each D leaves an empty space to place As, Bs and Cs to the right of it) After that, we multiply the answer by $\left(a_{e}\right)\cdot\left({b_{f}}\right)$ to account for the choice of the set of As and Bs used in the A-only and B-only cycles. Thus, the complexity of this method is $O(n^{4})$ for each $k$ and $O(n^{5})$ in total, which is clearly too slow. We can improve this by iterating through all $x + y, e, f$ instead. So, for this to work we need to precompute $f(e, 0)f(f, x + y) + f(e, 1)f(f, x + y - 1) + ... + f(e, x + y)f(f, 0)$, which we can write as $g(x + y, e, f)$. Naively doing this precomputation gives $O(n^{4})$. Then, we can calculate the answer by iterating through all $x + y, e, f$ and thus getting $O(n^{3})$ per query and $O(n^{4})$ for all $k$. This is still too slow to pass $n = 250$. We should take a closer look of what we're actually calculating. Note that for a fixed pair $e, f$, the values of $g(x + y, e, f)$ can be calculated for all possible $x + y$ in $O(n\log n)$ or $O(n^{1.58})$ by using Number Theoretic Transform or Karatsuba's Algorithm respectively. (note that the modulus has been chosen for NFT to work) This is because if we fix $e, f$, then we're precisely finding the coefficients of the polynomial $(f(e, 0)x^{0} + f(e, 1)x^{1} + ... + f(e, n)x^{n})(f(f, 0)x^{0} + f(f, 1)x^{1} + ... + f(f, n)x^{n})$, so this can be handled with NFT/Karatsuba. Thus, the precomputation of $g(x + y, e, f)$ can be done in $O(n^{3}\log{n})$ or $O(n^{3.58})$. Next, suppose we fixed $e$ and $f$. We will calculate the answer for all possible $k$ in $O(n\log n)$ similar to how we calculated $g(x + y, e, f)$. This time, we're multiplying the following two polynomials : $f(d, 0)x^{0} + f(d, 1)x^{1} + ... + f(d, n)x^{n}$ and $g(0, e, f)x^{0} + g(1, e, f)x^{1} + ... + g(n, e, f)x^{n}$. Again, we can calculate this using any fast multiplication method, so the entire solution takes $O(n^{3}\log{n})$ or $O(n^{3.58})$, depending on which algorithm is used to multiply polynomials. Note that if you're using NFT/FFT, there is a small trick that can save some time. When we precompute the values of $g(x + y, e, f)$, we don't need to do inverse FFT on the result and leave it in the FFTed form. After that, when we want to find the convolution of $f(d, i)$ and $g(i, e, f)$, we just need to apply FFT to the first polynomial and multiply them. This reduces the number of FFTs and it reduced my solution runtime by half. Time Complexity : $O(n^{3}\log{n})$ or $O(n^{3.58})$, depending on whether NFT or Karatsuba is used.
[ "combinatorics", "fft", "graphs", "math" ]
3,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 251; const int MOD = 998244353; ll inv2; ll prt; ll iprt; ll dpncr[N][N]; ll fact[N]; ll inverse[N]; ll g[N][N]; ll sumg[N][N][N]; vector<ii> perm; int A, B, C, D; ll modpow(ll a, ll b) { ll r = 1; while(b) { if(b&1) r = (r*a)%MOD; a = (a*a)%MOD; b>>=1; } return r; } ll inv(ll a) { return modpow(a, MOD - 2); } ll choose(int n, int m) { if(m < 0) return 0; if(n < m) return 0; if(m == 0) return 1; if(n == m) return 1; if(dpncr[n][m] != -1) return dpncr[n][m]; dpncr[n][m] = choose(n - 1, m - 1) + choose(n - 1, m); dpncr[n][m] += MOD; dpncr[n][m] %= MOD; return dpncr[n][m]; } void computefact() { fact[0] = 1; for(ll i = 1; i < N; i++) { fact[i] = (fact[i - 1]*i)%MOD; } for(ll i = 1; i < N; i++) { inverse[i] = modpow(i, MOD - 2); } } void print(vector<ii>& vec) { for(int i = 0; i < vec.size(); i++) { cout << vec[i].fi << ' ' << vec[i].se << endl; } cout << "------------------------------------------------" << endl; } void printans(vector<ll>& vec) { for(int i = 0; i < vec.size(); i++) { cout << vec[i] << ' '; } cout << endl; } void printansi(vector<int>& vec) { for(int i = 0; i < vec.size(); i++) { cout << vec[i] << ' '; } cout << endl; } void calcpos(vector<ii>& pos) { pos.resize(perm.size()); for(int i = 0; i < perm.size(); i++) { pos[i] = ii(-1, -1); } for(int i = 1; i < perm.size(); i++) { if(perm[i].fi > 0) { pos[perm[i].fi].fi = i; } if(perm[i].se > 0) { pos[perm[i].se].se = i; } } } int reduce() { int n = perm.size() - 1; vector<ii> pos; int cnt = 0; for(int i = 1; i <= n; i++) //Do a reduction { calcpos(pos); //print(pos); if(pos[i].fi > 0 && pos[i].se > 0) { if(pos[i].fi == pos[i].se) { cnt++; ii tmp1 = perm[pos[i].fi]; for(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++) { if((*it) == tmp1) { perm.erase(it); break; } } continue; } int p1 = pos[i].se; int l = perm[p1].fi; ii tmp1 = perm[p1]; int p2 = pos[i].fi; int r = perm[p2].se; ii tmp2 = perm[p2]; for(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++) { if((*it) == tmp1) { perm.erase(it); break; } } for(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++) { if((*it) == tmp2) { perm.erase(it); break; } } perm.pb(ii(l, r)); } } //count A, B, C, D for(int i = 1; i < perm.size(); i++) { if(perm[i].fi > 0 && perm[i].se > 0) { assert(perm[i].fi != perm[i].se); C++; } else if(perm[i].fi > 0) { A++; } else if(perm[i].se > 0) { B++; } else { D++; } } return cnt; } ll mult(ll a, ll b) { ll r = (a*b)%MOD; r = (r+MOD)%MOD; return r; } ll add(ll a, ll b) { ll r = ((a+b)%MOD+MOD)%MOD; return r; } ll F(ll a, ll b, ll c, ll d) { ll ans = 1; if(d == 0) { if(a == 0 && b == 0 && c == 0) return 1; else return 0; } ans = mult(ans, fact[a]); ans = mult(ans, fact[b]); ans = mult(ans, fact[c]); ans = mult(ans, choose(a+d-1, d-1)); ans = mult(ans, choose(b+d-1, d-1)); ans = mult(ans, choose(d, C)); return ans; } ll buffer[20001], bufferpos, siz = 1024; const int LG = 4; void multiply(int size, ll a[], ll b[], ll r[]) { if(size <= (1<<LG)) { for(int i = 0; i < size*2; i++) r[i] = 0; for(int i = 0; i < size; i++) { if(a[i]) { for(int j = 0; j < size; j++) { r[i+j] += a[i]*b[j]; r[i+j] %= MOD; } } } for(int i = 0; i < size*2; i++) { r[i] %= MOD; } return ; } int s = size/2; multiply(s, a, b, r); multiply(s, a+s, b+s, r+size); ll *a2 = buffer+bufferpos; bufferpos += s; ll *b2 = buffer+bufferpos; bufferpos += s; ll *r2 = buffer+bufferpos; bufferpos += size; for(int i = 0; i < s; i++) { a2[i] = a[i] + a[i+s]; if(a2[i]>=MOD) a2[i]-=MOD; } for(int i = 0; i < s; i++) { b2[i] = b[i] + b[i+s]; if(b2[i]>=MOD) b2[i]-=MOD; } multiply(s, a2, b2, r2); for(int i = 0; i < size; i++) { r2[i] -= (r[i] + r[i+size]); } for(int i = 0; i < size; i++) { r[i+s] += r2[i]; r[i+s]%=MOD; if(r[i+s]<0) r[i+s]+=MOD; } bufferpos -= (s+s+size); } ll gi[N+5]; ll gj[N+5]; void computeg(int n) { g[0][0] = 1; g[1][1] = 1; for(int i = 2; i <= n; i++) { for(int j = 1; j <= i; j++) { for(int k = 1; k <= i; k++) { g[i][j] = add(g[i][j], mult(g[i-k][j-1], mult(choose(i, k), fact[k-1]))); } g[i][j] = mult(g[i][j], inverse[j]); } } for(int i = 0; i <= A; i++) { for(int j = 0; j <= B; j++) { siz = 512; while(siz/2 >= n+1) siz>>=1; for(int k = 0; k < siz; k++) { if(k <= n) { gi[k] = g[i][k]; gj[k] = g[j][k]; } else { gi[k] = gj[k] = 0; } } ll *res = buffer+bufferpos; bufferpos+=2*siz; multiply(siz,gi,gj,res); for(int k = 0; k <= n; k++) { sumg[i][j][k] = res[k]; } bufferpos-=2*siz; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; perm.resize(n+1); for(int i = 1; i <= n; i++) { cin >> perm[i].fi; } for(int i = 1; i <= n; i++) { cin >> perm[i].se; } A = 0; B = 0; C = 0; D = 0; memset(dpncr, -1, sizeof(dpncr)); memset(sumg, 0, sizeof(sumg)); memset(g, 0, sizeof(g)); memset(fact, 0, sizeof(fact)); memset(inverse, 0, sizeof(inverse)); int cycles = reduce(); computefact(); computeg(n); vector<ll> ans; ans.assign(n+1, 0); if(D - C < 0) { for(int i = 0; i < n; i++) { cout << ans[i] << ' '; } cout << endl; return 0; } for(int i = 0; i <= A; i++) { for(int j = 0; j <= B; j++) { ll coef = 1; coef = mult(coef, F(A-i,B-j,C,D)); if(A > 0) coef = mult(coef, choose(A, i)); if(B > 0) coef = mult(coef, choose(B, j)); siz = 512; while(siz/2 >= n-cycles+1) siz>>=1; for(int k = 0; k < siz; k++) { if(k <= n-cycles) { gi[k] = g[D][k]; gj[k] = sumg[i][j][k]; } else { gi[k] = gj[k] = 0; } } ll *res = buffer+bufferpos; bufferpos+=2*siz; multiply(siz,gi,gj,res); for(int k = 0; k <= n - cycles; k++) { int moves = n - (k + cycles); ans[moves] = add(ans[moves], mult(res[k], coef)); } bufferpos-=2*siz; } } for(int i = 0; i < ans.size(); i++) { ans[i] = mult(ans[i], fact[D-C]); } for(int i = 0; i < n; i++) { cout << ans[i] << ' '; } cout << endl; }
716
A
Crazy Computer
ZS the Coder is coding on a crazy computer. If you don't type in a word for a $c$ consecutive seconds, everything you typed disappear! More formally, if you typed a word at second $a$ and then the next word at second $b$, then if $b - a ≤ c$, just the new word is appended to other words on the screen. If $b - a > c$, then everything on the screen disappears and after that the word you have typed appears on the screen. For example, if $c = 5$ and you typed words at seconds $1, 3, 8, 14, 19, 20$ then at the second $8$ there will be $3$ words on the screen. After that, everything disappears at the second $13$ because nothing was typed. At the seconds $14$ and $19$ another two words are typed, and finally, at the second $20$, one more word is typed, and a total of $3$ words remain on the screen. You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
This is a straightforward implementation problem. Iterate through the times in order, keeping track of when is the last time a word is typed, keeping a counter for the number of words appearing on the screen. Increment the counter by $1$ whenever you process a new time. Whenever the difference between the time for two consecutive words is greater than $c$, reset the counter to $0$. After that, increment it by $1$. Time Complexity : $O(n)$, since the times are already sorted.
[ "implementation" ]
800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 1e5 + 3; ll a[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, c; cin >> n >> c; for(int i = 0; i < n; i++) { cin >> a[i]; } //sort(a, a + n); int cnt = 0; for(int i = 0; i < n; i++) { if(i == 0) cnt++; else { if(a[i] - a[i - 1] <= c) cnt++; else cnt = 1; } } cout << cnt; return 0; }
716
B
Complete the Word
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a \textbf{substring} (contiguous segment of letters) of it of length $26$ where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than $26$, no such substring exists and thus it is not nice. Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?
Firstly, if the length of the string is less than $26$, output $- 1$ immediately. We want to make a substring of length $26$ have all the letters of the alphabet. Thus, the simplest way is to iterate through all substrings of length $26$ (there are $O(n)$ such substrings), then for each substring count the number of occurrences of each alphabet, ignoring the question marks. After that, if there exist a letter that occurs twice or more, this substring cannot contain all letters of the alphabet, and we process the next substring. Otherwise, we can fill in the question marks with the letters that have not appeared in the substring and obtain a substring of length $26$ which contains all letters of the alphabet. After iterating through all substrings, either there is no solution, or we already created a nice substring. If the former case appears, output $- 1$. Otherwise, fill in the remaining question marks with random letters and output the string. Note that one can optimize the solution above by noting that we don't need to iterate through all $26$ letters of each substring we consider, but we can iterate through the substrings from left to right and when we move to the next substring, remove the front letter of the current substring and add the last letter of the next substring. This optimization is not required to pass. We can still optimize it further and make the complexity purely $O(|s|)$. We use the same trick as above, when we move to the next substring, we remove the previous letter and add the new letter. We store a frequency array counting how many times each letter appear in the current substring. Additionally, store a counter which we will use to detect whether the current substring can contain all the letters of the alphabet in $O(1)$. When a letter first appear in the frequency array, increment the counter by $1$. If a letter disappears (is removed) in the frequency array, decrement the counter by $1$. When we add a new question mark, increment the counter by $1$. When we remove a question mark, decrement the counter by $1$. To check whether a substring can work, we just have to check whether the counter is equal to $26$. This solution works in $O(|s|)$. Time Complexity : $O(|s| \cdot 26^{2})$, $O(|s| \cdot 26)$ or $O(|s|)$
[ "greedy", "two pointers" ]
1,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 50000; int cnt[27]; string s; int n; int counter; bool valid() { //cout << counter << endl; return (counter == 26); } void fillall() { for(int i = 0; i < n; i++) { if(s[i] == '?') s[i] = 'A'; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> s; n = s.length(); if(n < 26) {cout << -1; return 0;} counter = 0; for(int i = 0; i < 26; i++) { if(s[i] == '?') { counter++; continue; } cnt[s[i]-'A']++; if(cnt[s[i]-'A'] == 1) counter++; } if(valid()) { int cur = 0; while(cnt[cur]>0) cur++; for(int i = 0; i < 26; i++) { if(s[i] == '?') { s[i] = cur + 'A'; cur++; while(cnt[cur]>0) cur++; } } fillall(); cout << s; return 0; } for(int i = 26; i < n; i++) { if(s[i] != '?') {cnt[s[i]-'A']++; if(cnt[s[i]-'A']==1) counter++;} if(s[i-26] != '?') {cnt[s[i-26]-'A']--; if(cnt[s[i-26]-'A']==0) counter--;} if(s[i-26] == '?') counter--; if(s[i] == '?') counter++; if(valid()) { int cur = 0; while(cnt[cur]>0) cur++; for(int j = i - 25; j <= i; j++) { if(s[j] == '?') { s[j] = cur + 'A'; cur++; while(cnt[cur]>0) cur++; } } fillall(); cout << s; return 0; } } cout << -1; return 0; }
718
A
Efim and Strange Grade
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are $t$ seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than $t$ seconds. Note, that he can choose to not use all $t$ seconds. Moreover, he can even choose to not round the grade at all. In this problem, classic rounding rules are used: while rounding number to the $n$-th digit one has to take a look at the digit $n + 1$. If it is less than $5$ than the $n$-th digit remain unchanged while all subsequent digits are replaced with $0$. Otherwise, if the $n + 1$ digit is greater or equal to $5$, the digit at the position $n$ is increased by $1$ (this might also change some other digits, if this one was equal to $9$) and all subsequent digits are replaced with $0$. At the end, all trailing zeroes are thrown away. For example, if the number $1.14$ is rounded to the first decimal place, the result is $1.1$, while if we round $1.5$ to the nearest integer, the result is $2$. Rounding number $1.299996121$ in the fifth decimal place will result in number $1.3$.
One can notice that the closer to the decimal point we round our grade the bigger grade we get. Based on this observation we can easily solve the problem with dynamic programming. Let $dp_{i}$ be the minimum time required to get a carry to the ($i - 1$)-th position. Let's denote our grade as $a$, and let $a_{i}$ be the ($i$)-th digit of the $a$. There are three cases: If $a_{i} \ge 5$, then $dp_{i} = 1$. If $a_{i} < 4$, then $dp_{i} = inf$ (it means, that we cann't get a carry to the ($i - 1$)-th position). If $a_{i} = 4$, then $dp_{i} = 1 + dp_{i + 1}$. After computing $dp$, we need to find the minimum $pos$ such that $dp_{pos} \le t$. So, after that we know the position where we should round our grade. Now we only need to carefully add 1 to the number formed by the prefix that contains $pos$ elements of the original grade. Time Complexity: $\mathrm{O}(n)$.
[ "dp", "implementation", "math" ]
1,700
null
718
C
Sasha and Array
Sasha has an array of integers $a_{1}, a_{2}, ..., a_{n}$. You have to perform $m$ queries. There might be queries of two types: - 1 l r x — increase all integers on the segment from $l$ to $r$ by values $x$; - 2 l r — find $\textstyle\sum_{i=l}^{r}f(a_{i})$, where $f(x)$ is the $x$-th Fibonacci number. As this number may be large, you only have to find it modulo $10^{9} + 7$. In this problem we define Fibonacci numbers as follows: $f(1) = 1$, $f(2) = 1$, $f(x) = f(x - 1) + f(x - 2)$ for all $x > 2$. Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?
Let's denote Let's recall how we can quickly find $n$-th Fibonacci number. To do this we need to find a matrix product $(1~1)\times A^{n-2}$. In order to solve our problem let's create the following segments tree: in each leaf which corresponds to the element $i$ we will store a vector $\left(f_{a_{i}}\ \ f_{a_{i}+1}\right)$ and in all other nodes we will store the sums of all the vectors that correspond to a given segment. Now, to perform the first request we should multiply all the vectors in a segment $[l..r]$ by $A^{x}$ and to get an answer to the second request we have to find a sum in a segment $[l..r]$. Time Complexity: $O(m\log n+(n+m)\log x)$.
[ "data structures", "math", "matrices" ]
2,300
null
718
D
Andrew and Chemistry
During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he faced some difficulties and asks you to help. Formally, you are given a tree consisting of $n$ vertices, such that the degree of each vertex doesn't exceed $4$. You have to count the number of distinct non-isomorphic trees that can be obtained by adding to this tree one new vertex and one new edge, such that the graph is still the tree and the degree of each vertex doesn't exceed $4$. Two trees are isomorphic if there exists a bijection $f(v)$ such that vertices $u$ and $v$ are connected by an edge if and only if vertices $f(v)$ and $f(u)$ are connected by an edge.
Let's first figure out how we can solve the problem in $O(n^{2}\log{n})$ time. Let's pick a vertex we're going to add an edge to and make this vertex the root of the tree. For each vertex $v_{i}$ we're going to assign a label $a[v_{i}]$ (some number). The way we assign labels is the following: if the two given vertices have the same subtrees they're going to get the same labels, but if the subtrees are different then the labels for these vertices are going to be different as well. We can do such labeling in a following way: let's create a map<vector<int>, int> m (the maximum degree for a vertex is 4, but let's assume that the length of the vector is always equal to 4). Let m[{x, y, z, w}] be a label for a vertex which has children with the labels $x$, $y$, $z$, $w$. Let's note that the vector {$x$, $y$, $z$, $w$} should be sorted to avoid duplications, also if the number of children is less than 4 then we'll store $- 1$'s for the missing children (to make the length of a vector always equal to 4). Let's understand how we can compute the value for the label for the vertex $v$. Let's recursively compute the labels for its children: $v_{1}$, $v_{2}$, $v_{3}$, $v_{4}$. Now, if m.count({a[v1], a[v2], a[v3], a[v4]}) then we use the corresponding value. Otherwise, we use the first unused number: m[{a[v1], a[v2], a[v3], a[v4]}]=cnt++. Now, let's pick another vertex which we're going to add an edge to. Again, let's make it the root of the tree and set the labels without zeroing out our counter $cnt$. Now, let's do the same operation for all the other possible roots (vertices, $n$ times). Now, one can see that if the two roots have the same labels, then the trees which can be obtained by adding an edge to these roots, are exactly the same. Thus, we only need to count the amount of roots with different labels. Also, we should keep in mind that if a degree for a vertex is already 4 it's impossible to add an edge to it. The solution described above has the time complexity $O(n^{2}\log{n})$, because we consider $n$ rooted trees and in the each tree we iterate through all the vertices ($n$), but each label update takes $O(\log n)$. Let's speed up this solution to $O(n\log n)$. Let $b$ be an array where $b[v_{i}]$ is a label in a vertex $v_{i}$ if we make this vertex the root of the tree. Then the answer to the problem is the number of different numbers in the array $b$. Let's root the tree in a vertex $root$ and compute the values $a[v_{i}]$. Then $b[root] = a[root]$ and all the other values for $b[v_{i}]$ we can get by pushing the information from the top of the tree to the bottom. Time complexity: $\mathrm{O}(n\log n)$.
[ "dp", "hashing", "trees" ]
2,900
null
718
E
Matvey's Birthday
Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string $s$ of length $n$. This string consists of only first eight English letters: 'a', 'b', $...$, 'h'. First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do with this string. He used it to build an undirected graph where vertices correspond to position in the string and there is an edge between distinct positions $a$ and $b$ ($1 ≤ a, b ≤ n$) if \textbf{at least one} of the following conditions hold: - $a$ and $b$ are neighbouring, i.e. $|a - b| = 1$. - Positions $a$ and $b$ contain equal characters, i.e. $s_{a} = s_{b}$. Then Matvey decided to find the diameter of this graph. Diameter is a maximum distance (length of the shortest path) among all pairs of vertices. Also, Matvey wants to find the number of pairs of vertices such that the distance between them is equal to the diameter of the graph. As he is very cool and experienced programmer he managed to solve this problem very fast. Will you do the same?
Let's prove that the distance between any two vertices is no more than $MaxDist = 2 \cdot sigma - 1$, where $sigma$ is the size of the alphabet. Let's consider one of the shortest paths from the position $i$ to the position $j$. One can see that in this path each letter $ch$ occurs no more than two times (otherwise you could have skipped the third occurrence by jumping from the first occurrence to the last which gives us a shorter path). Thus, the total amount of letters in the path is no more than $2 \cdot sigma$ which means that the length of the path is no more than $2 \cdot sigma - 1$. Let $dist_{i, c}$ be the distance from the position $i$ to some position $j$ where $s_{j} = c$. These numbers can be obtained from simulating bfs for each letter $c$. We can simulate bfs in $O(n \cdot sigma^{2})$ (let's leave this as an exercise to the reader). Let $dist(i, j)$ be the distance between positions $i$ and $j$. Let's figure out how we can find $dist(i, j)$ using precomputed values $dist_{i, c}$. There are two different cases: The optimal path goes through the edges of the first type only. In this case the distance is equal to $|i-j|$. The optimal path has at least one edge of the second type. We can assume that it was a jump between two letters $c$. Then, in this case the distance is $dist_{i, c} + 1 + dist_{c, j}$. Adding these two cases up we get: $d i s t(i,j)=m i n(|i-j|\,,m i n(d i s t_{i.c}+1+d i s t_{c.j}))$. Let's iterate over the possible values for the first position $i = 1..n$. Let's compute the distance for all such $j$, where $|i-j|\leq M a x D i s t$ by the above formula. Now, for a given $i$ we have to find $max(dist(i, j))$ for $\vert i-j\vert>M a x D i s t$. In this case $dist(i, j) = min(dist_{i, c} + 1 + dist_{c, j})$. Let's compute one additional number $dist_{c1, c2}$$-$ the minimal distance between positions $i$ and $j$ where $s_{i} = c_{1}$ and $s_{j} = c_{2}$. This can be easily done using $dist_{i, c}$. One can notice that $dist_{sj, c} \le dist_{j, c} \le dist_{sj, c} + 1$. It means that for every position $j$ we can compute a mask $mask_{j}$ with $sigma$ bits where $i$-th bit is equal to $dist_{j, c} - dist_{sj, c}$. Thus, we can compute the distance using only $s_{j}$ and $mask_{j}$. I.e. now $dist_{j, c} = dist_{sj, c} + mask_{j, c}$. Let $cnt$ be an array where $cnt_{c, mask}$ is the number of such $j$ where $|i-j|>M a x D i s t$, $s_{j} = c$ and $mask_{j} = mask$. Now, instead of iterating over $j$ for a given $i$ we can iterate over $(c, mask)$ and if $cnt_{c, mask} \neq 0$ we'll be updating the answer. Time complexity: $O(n\cdot s i g m a^{3}+n\cdot s i g m a^{2}\cdot2^{s i g m a})$.
[ "bitmasks", "graphs" ]
3,300
null
719
A
Vitya in the Countryside
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down. Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is $0$, $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$, $10$, $11$, $12$, $13$, $14$, $15$, $14$, $13$, $12$, $11$, $10$, $9$, $8$, $7$, $6$, $5$, $4$, $3$, $2$, $1$, and then cycle repeats, thus after the second $1$ again goes $0$. As there is no internet in the countryside, Vitya has been watching the moon for $n$ consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
There are four cases that should be carefully considered: $a_{n} = 15$ $-$ the answer is always DOWN. $a_{n} = 0$ $-$ the answer is always UP. If $n = 1$ $-$ the answer is -1. If $n > 1$, then if $a_{n-1} > a_{n}$ $-$ answer is DOWN, else UP. Time Complexity: $O(1)$.
[ "implementation" ]
1,100
null
719
B
Anatoly and Cockroaches
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are $n$ cockroaches living in Anatoly's room. Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to \textbf{alternate}. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color. Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
We can notice that there are only two possible final coloring of cockroaches that satisfy the problem statement: $rbrbrb...$ or $brbrbr...$ Let's go through both of these variants. In the each case let's count the number of red and black cockroaches which are not standing in their places. Let's denote these numbers as $x$ and $y$. Then it is obvious that the $min(x, y)$ pairs of cockroaches need to be swapped and the rest should be repaint. In other words, the result for a fixed final coloring is exactly $min(x, y) + max(x, y) - min(x, y) = max(x, y)$. The final answer for the problem is the minimum between the answers for the first and the second colorings. Time Complexity: $\mathrm{O}(n)$.
[ "greedy" ]
1,400
null
720
A
Closing ceremony
The closing ceremony of Squanch Code Cup is held in the big hall with $n × m$ seats, arranged in $n$ rows, $m$ seats in a row. Each seat has two coordinates $(x, y)$ ($1 ≤ x ≤ n$, $1 ≤ y ≤ m$). There are two queues of people waiting to enter the hall: $k$ people are standing at $(0, 0)$ and $n·m - k$ people are standing at $(0, m + 1)$. Each person should have a ticket for a specific seat. If person $p$ at $(x, y)$ has ticket for seat $(x_{p}, y_{p})$ then he should walk $|x - x_{p}| + |y - y_{p}|$ to get to his seat. Each person has a stamina — the maximum distance, that the person agrees to walk. You should find out if this is possible to distribute all $n·m$ tickets in such a way that each person has enough stamina to get to their seat.
Probably the easiest way to solve the problem is greedy. Sort people from the first line by increasing of their stamina. Give them tickets in this order, each time using the place which is furthest away from the other line. After that try to assign people from the second line to the remaining seats by sorting people by stamina and seats by the distance. The time complexity of your solution must not exceed $O((nm)^{2})$, however using std::set one can get a solution with complexity of $O(nm log(nm))$.
[ "greedy" ]
2,000
null
720
B
Cactusophobia
Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle. Vasya has an edge cactus, each edge of this graph has some color. Vasya would like to remove the minimal number of edges in such way that his cactus turned to a tree. Vasya wants to make it in such a way that there were edges of as many different colors in the resulting tree, as possible. Help him to find how many different colors can the resulting tree have.
Let us divide the graph to biconnected blocks. Each block is either a bridge, or a cycle. Our goal is to remove one edge from each cycle, so that the number of remaining colors were maximum possible. Let us build a bipartite graph, one part would be blocks, another one would be colors. For each block put an edge of capacity $1$ for each color of an edge in this block (make multiple edges, or bigger capacity if there are several edges of some color). Add two vertices: source and sink, add edges from source to blocks, if the block is a cycle of length $l$, set its capacity to $l - 1$, if it is a bridge, set its capacity to $1$. Add edges from color vertices to the sink of capacity $1$. It is quite clear that size of the maximum flow in this graph is indeed the answer to the problem. As a final note, the judges know the solution that runs in $O(n)$ and requires no maximum flow algorithms, challenge yourself to come up with it!
[ "dfs and similar", "flows" ]
2,400
null
720
C
Homework
Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: $n$, $m$ and $k$, and asked him to mark one or more squares on a square grid of size $n × m$. The marked squares must form a connected figure, and there must be exactly $k$ triples of marked squares that form an L-shaped tromino — all three squares are inside a $2 × 2$ square. The set of squares forms a connected figure if it is possible to get from any square to any other one if you are allowed to move from a square to any adjacent by a common side square. Peter cannot fulfill the task, so he asks you for help. Help him to create such figure.
The solution is constructive. First let us use backtracking to find solutions for all $n, m < 5$, it is also better to precalculate all answers, in order not to mess with non-asymptotic optimizations. Now $m \ge 5$. Let us put asterisks from left to right, one row after another. When adding the new asterisk, we add 4 new L-trominoes, except the first asterisk in a row that adds 1 new L-tromino, and the last asterisk in a row adds 3 new L-trominoes. Let us stop when the number of remaining L-trominoes $k$ is less than 4, or there are less than 5 free squares in the table. Now there are two cases there is a free row thee is no free row If there is a free row, we stopped because $k$ is now less then 4. So: k = 0: the solution is found k = 1: if there are already at least $2$ asterisks in the current row, put the asterisk in the beginning of the next row, if there is only $1$, put it in the end of the current row k = 2, k = 3 - similar, left as an exercise. If there are now free rows left, one can see that you can only add $k$ from the set ${0, 1, 2, 3, 4, 5, 6, 8, 9, 12, 15}$ L-trominoes. And finally there is also the special case where the size of the board is $3 \times m$, $m \ge 5$ and $k = 2 * (m - 1) - 8$ - in this case the first column should be left empty, and the rest of the board must be completely filled with asterisks.
[ "constructive algorithms" ]
3,100
null
720
D
Slalom
Little girl Masha likes winter sports, today she's planning to take part in slalom skiing. The track is represented as a grid composed of $n × m$ squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square $(1, 1)$ to the square $(n, m)$. She can move from a square to adjacent square: either to the right, or upwards. If the square is occupied by an obstacle, it is not allowed to move to that square. One can see that each obstacle can actually be passed in two ways: either it is to the right of Masha's path, or to the left. Masha likes to try all ways to do things, so she would like to know how many ways are there to pass the track. Two ways are considered different if there is an obstacle such that it is to the right of the path in one way, and to the left of the path in the other way. Help Masha to find the number of ways to pass the track. The number of ways can be quite big, so Masha would like to know it modulo $10^{9} + 7$. The pictures below show different ways to pass the track in sample tests.
First let us consider all paths from the starting square to the finish one. Let us say that two paths are equivalent, if each obstacle is at the same side for both paths. For each class of equivalence let us choose the representative path - the one that tries to go as low as possible, lexicographically minimum. Let us use dynamic programming. For each square let us count the number of representative paths that go from the starting square to this one. When the obstacle starts, some paths can now separate. The new representatives will pass this obstacle from above (it will be to the right of them). So we add the sum of values for squares below it, but above any other lower obstacle, to the value for the square right above the obstacle. To overcome the time and memory limits that the naive solution with $O(nm)$ memory and $O(nm^{2})$ time complexity, we use segment tree for range sum queries with mass update, running scanline and events "start of an obstacle", "end of an obstacle". This leads to the solution with $O(m)$ memory and $O(n log m)$ time complexity.
[ "data structures", "dp", "sortings" ]
3,100
null
720
E
Cipher
Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has $n$ decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet. There is a legend near the display, that describes how the number is encoded. For each digit position $i$ and each digit $j$ the character $c$ is known, that encodes this digit at this position. Different digits can have the same code characters. Each second the number is increased by 1. And one second after a moment when the number reaches the value that is represented as $n$ 9-s in decimal notation, the loud beep sounds. Andrew knows the number that is stored in the computer. Now he wants to know how many seconds must pass until Borya can definitely tell what was the original number encoded by the display. Assume that Borya can precisely measure time, and that the encoded number will first be increased exactly one second after Borya started watching at the display.
First let us consider a slow solution. Let us find a condition for each number $k$ after what number of seconds Borya can distinguish it from the given number. Let us look at their initial encoding. Increase both numbers by $1$ until the encodings are different (or one of the numbers needs more than $n$ digits to represent in which case the beep allows Borya to distinguish the numbers as well). Now there are two main ideas that allow us to get a better solution. First, we don't have to check all numbers. We only need to check numbers that differ from the given number in exactly one digit. Second: to get the time when the numbers can be distinguished we don't need to iterate over all possible values. We just need to try all digit positions and all values for that position, and check only moments when the digit at the position will first have this value in one of the numbers. So the complexity is now polynomial in $n$ and since $n \le 18$, it easily fits into the time limit.
[ "implementation" ]
3,100
null
720
F
Array Covering
Misha has an array of integers of length $n$. He wants to choose $k$ different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays. Misha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all these sums, the resulting value was maximum possible.
We give the outline of the solution, leaving technical details as an excercise. First note that the answer will always use $min(k - n, 0)$ subarrays with maximal sums. Sof let us find the sum of $min(k - n, 0)$ maximal subarrays, elements that are used in them, and the following $min(k, n)$ subarrays. We can do it using binary search for the border sum, and a data structure similar to Fenwick tree. For the given value of the sum this tree must provide the number of subarrays with greater or equal sum, sum of their sums, and the set of the elements of these subarrays. It should also allow to list all these subarrays in linear time complexity. This part has time complexity $O(n log^{2} n)$. Let us now describe how to solve the problem in $O(n^{2} log n)$. Let us try all values of $x$ - the number of subarrays with maximum sums that we will use in our solution (there are $O(n)$ variants, because top $min(k - n, 0)$ subarrays will definitely be used). Let elements with indices $i_{1}, ..., i_{m}$ be the ones that are not used in these subarrays. Now we must add $k - x$ segments that would contain all of these elements. Note that each of these $k - x$ segments must contain at least one of these elements, and no two segments can have a common element among them (in the other case the solution is not optimal). These observations let us greedily choose these $k - x$ segments in $O(n log n)$ and the final solution complexity is $O(n^{2} log n)$ To optimize this solution, we keep segments [$i_{j} + 1$; $i_{j + 1} - 1$] in the ordered set. When we iterate over $x$ and increase its value, we remove some of the $i_{j}$-s, and recalculate the required values for the affected segments. After that we must take $k - x$ maximal values from the set, so since there are $O(n)$ changes in total, this part now works in $O(n log n)$.
[ "data structures" ]
3,100
null
721
A
One-dimensional Japanese Crossword
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized $a × b$ squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia https://en.wikipedia.org/wiki/Japanese_crossword). Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of $n$ squares (e.g. japanese crossword sized $1 × n$), which he wants to encrypt in the same way as in japanese crossword. \begin{center} {\small The example of encrypting of a single row of japanese crossword.} \end{center} Help Adaltik find the numbers encrypting the row he drew.
In this problem we have to compute the lengths of all blocks consisting of consecutive black cells. Let's iterate from the left cell of crossword to the end: let $i$ be the number of the cell where we are currently; if $s[i] = B$, let $j = i$, and while $j < n$ and $s[j] = 'B'$, we increase $j$ by one. When we come to a white cell or to the end of the crossword, we can compute the length of the block we have just passed (it is equal to $j - i$, and we need to store this value), and now move to cell $j$ (make $i = j$). And if we are in a white cell, all we need to do is increase $i$ by one. When $i = n$, it means that we have gone through the whole crossword, and now we print the answer. Time complexity - $O(n)$, and memory complexity - $O(n)$.
[ "implementation" ]
800
null
721
B
Passwords
Vanya is managed to enter his favourite site Codehorses. Vanya uses $n$ distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration. Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice. Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password $k$ times, then he is able to make the next try only $5$ seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that. Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).
The author suggests a solution with formulas: let's count two variables - $cnt_{l}$ (the number of passwords that are shorter than Vanya's Codehorses password) and $cnt_{le}$ (the number of passwords that are not longer than Vanya's Codehorses password). Then it's easy to see that in the best case answer will be equal to $c n t_{l}+\lfloor{\frac{c n t_{l}}{k}}\rfloor\cdot5+1$, and in the worst case it will be $c n t_{l e}+\big[\frac{c n t_{l e}-1}{k}\big]\cdot5$. Time complexity of solution - $O(n)$, memory complexity - $O(n)$.
[ "implementation", "math", "sortings", "strings" ]
1,100
null
721
C
Journey
Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are $n$ showplaces in the city, numbered from $1$ to $n$, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there \textbf{are no} cyclic routes between showplaces. Initially Irina stands at the showplace $1$, and the endpoint of her journey is the showplace $n$. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than $T$ time units. Help Irina determine how many showplaces she may visit during her journey from showplace $1$ to showplace $n$ within a time not exceeding $T$. It is guaranteed that there is at least one route from showplace $1$ to showplace $n$ such that Irina will spend no more than $T$ time units passing it.
Author's solution uses dynamic programming. Let $dp_{i, j}$ be the minimum time required to arrive at the vertex $i$, if we visit $j$ vertices (including vertices $1$ and $i$). We have a DAG (directed acyclic graph), so we can compute it recursively (and memory constraints were a bit strict in this problem, so it's better to use recursion to compute it). Let's store the transposed version of the graph: if we had an edge ($u, v$) in the input, we will store ($v, u$). Then our function $calc(i, j)$, which will compute the answer for $dp_{i, j}$, will be like that: the base of dynamic programming is $dp_{1, 1} = 0$, all other states are equal to <<-1>>. If we call $calc(i, j)$, then it will work like that: if the state we want to compute is incorrect ($j < 0$), we return a very large integer number (any number that is greater than $10^{9}$, because $T \le 10^{9}$). If the answer for this state has already been calculated, then we return $dp_{i, j}$ (it is easy do determine: if $dp_{i, j} \neq - 1$, then it has already been calculated). Else we begin to calculate the state. Firstly, let's put $INF$ (a number greater than $10^{9}$) into $dp_{i, j}$. Then look at all the edges beginning in $i$ and try to update $dp_{i, j}$ with the value of $calc(to, j - 1) + w$ ($to$ is the vertex at the endpoint of current edge, $w$ is the weight of this edge). If this value is less than $dp_{i, j}$, then we update $dp_{i, j}$ and store the information that our last update in $dp_{i, j}$ was from the vertex $to$. If we try to go by path which doesn't end in the vertex $1$, then we get a value which is greater than $10^{9}$, that's because that the only value we didn't denote as $- 1$ is $dp_{1, 1}$. So, now we have our $calc$ function, let's compute the answer. We will iterate on the number of vertices in the path from $n$ to $1$ in descending order, and if $calc(n, i) \le T$, then we have found the answer, now we iterate on the parent vertices we stored while calculating our $dp$, until we come to vertex $1$ (it's important because some participants sent solutions that continued even past vertex $1$!) and print the answer. Time complexity of this solution - $O((n + m)n)$, and mempry complexity - $O(nm)$.
[ "dp", "graphs" ]
1,800
null
721
D
Maxim and Array
Recently Maxim has found an array of $n$ integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer $x$ and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer $i$ ($1 ≤ i ≤ n$) and replaces the $i$-th element of array $a_{i}$ either with $a_{i} + x$ or with $a_{i} - x$. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. $\prod_{i=1}^{n}a_{i}$) can reach, if Maxim would apply no more than $k$ operations to it. Please help him in that.
Main idea: we act greedily, trying to make the best possible answer every action (each time we choose an action with minimum possible product after it). Detailed explanation: While we have zeroes in our array, we have to get rid of them, changing each of them exactly one time. Also we keep the quantity of negative numbers - we need it to make the product negative after changing the last zero. Let $m$ be the number of zeroes in the array. If $m > k$, then we cannot make the product negative or positive (it will always be equal to $0$), so any sequence of operations will lead to a correct answer. However, if $m \le k$, then we are able to come to negative product (if the number of negative elements was even, then we subtract $x$ from one zero and add it to all other zeroes; if the number of negative elements was odd, then we can just add $x$ to all zeroes). If current product is still positive, then we want to change the sign of exactly one element. Its absolute value has to be minimal: suppose we have two elements $a$ and $b$, $|a| < |b|$; let's prove that if we change $b$'s sign, then our answer is wrong. Let $m$ be the minimum number of operations required to change $b$'s sign. If we perform $m$ operations with $b$, then the absolute value of $a$ won't change, and absolute value of $b$ will become $x \cdot m - |b|$. If, on the other hand, we perform $m$ operations with $a$ (this may not be optimal, but now we need to prove that if we change $b$, then the result will be worse), then the absolute value of $a$ will become $x \cdot m - |a|$, the absolute value of $b$ won't change. The product becomes negative, so we need to maximize the product of absolute values. And then $x \cdot m - |a| > x \cdot m - |b|$ and $|b| > |a|$, so if we change $b$, then the product of absolute values will be less than if we change $a$. Now, until we have performed $k$ operations, we choose a number with minimum absolute value and enlarge it (add $x$ if this number if positive, subtract if negative). Let's prove that the answer will be optimal. Suppose that this algorithm chooses $a$ on some iteration, but we can't get optimal answer if we change $a$. This means that we can't change $a$ after this iteration at all (we can reorder our operations in an arbitrary way, and the answer won't change). Suppose we have to change $b$ instead, and $|b| > |a|$. Let's consider the sequence of operations leading to the optimal answer when we choose $b$, and replace change of $b$ with change of $a$, and let the product of all remaining numbers (the whole array excluding $a$ and $b$ after all operations) be $c$. If we change $a$, the total product will be $- (|a| + x) \cdot (|b| + x \cdot m) \cdot |c|$, and if we change $b$, we get $- |a| \cdot (|b| + x \cdot (m + 1)) \cdot |c|$ ($m$ is the number of times we change $b$). Now $|a| < |b| + x \cdot m$, so $(|a| + x) \cdot (|b| + x \cdot m) - |a| \cdot (|b| + x \cdot (m + 1)) = |b| + x \cdot m - |a| > 0$, so the absolute value of total product will be greater if we change $a$. This proves that we won't come to unoptimal answer if we change $a$. Time complexity: $O((n+k)\log n)$ if we use a data structure similar to set or priority_queue to get the number with minimal absolute value. Memory complexity: $O(n)$.
[ "constructive algorithms", "data structures", "greedy", "math" ]
2,000
null
721
E
Road to Home
Once Danil the student was returning home from tram stop lately by straight road of length $L$. The stop is located at the point $x = 0$, but the Danil's home — at the point $x = L$. Danil goes from $x = 0$ to $x = L$ with a constant speed and does not change direction of movement. There are $n$ street lights at the road, each of which lights some continuous segment of the road. All of the $n$ lightened segments do not share common points. Danil loves to sing, thus he wants to sing his favourite song over and over again during his walk. As soon as non-lightened segments of the road scare him, he sings only when he goes through the lightened segments. Danil passes distance $p$ while performing his favourite song once. Danil can't start another performance if the segment passed while performing is not fully lightened. Moreover, if Danil has taken a pause between two performances, he is not performing while not having passed a segment of length at least $t$. Formally, - Danil can start single performance at a point $x$ only if every point of segment $[x, x + p]$ is lightened; - If Danil has finished performing at a point $x + p$, then the next performance can be started only at a point $y$ such that $y = x + p$ or $y ≥ x + p + t$ satisfying the statement under the point $1$. \begin{center} {\small Blue half-circles denote performances. Please note that just after Danil has taken a pause in performing, he has not sang for a path of length of at least $t$.} \end{center} Determine how many times Danil can perform his favourite song during his walk from $x = 0$ to $x = L$. Please note that Danil does not break a single performance, thus, started singing another time, he finishes singing when having a segment of length of $p$ passed from the performance start point.
Firstly, if we are in some segment and we are going to sing in it, we want to sing as much as possible in this segment. So there are two cases for each segment: either we sing in the segment while we can or we just skip it. Now we consider two different cases: 1) $p \le 100$ If we have stopped singing in the segment, then the distance we need to walk to reach the end of this segment is strictly less than $p$. Let's calculate two values - $dp_{left}[i]$ - the answer (how many times we can sing a song) if we start from the beginning of segment number $i$ (from $l_{i}$), and $dp_{right}[i][j]$ - the answer if we start from $r_{i} - j$ ($0 \le j < p$, as we already said before). To calculate the value using the value from point $x$, we have to find the segment which contains the point $x + t$ and the segment which begins after this point. If we are in segment number $k$, we either skip it and update next segment ($dp_{left}[k + 1]$), or start singing and update the value in the point $y$ where we stop singing ($dp_{right}[k][y]$). To find the segment containing point $x + t$, we can use binary search or precalculate the required indices using iterations on the array of segments. Time complexity: $O(n p\log n)$ or $O(np)$. 2) $p > 100$ Let's use the fact that the answer is not greater than ${\frac{L}{p}}<10^{7}$. For each value $i$ we calculate $lf_{i}$ - the leftmost point where we can get it. We will iterate on those values considering that we have already calculated $lf_{j}$ for every $j < i$ when we start calculating $lf_{i}$. Then if $lf_{i}$ is before the beginning of some segment, and $lf_{i + 1}$ is after its beginning, then we can try singing starting from the beginning of this segment with $i$ performed songs currently, updating $lf$ for next values (from $i + 1$ till $i+{\bigl\lfloor}{\frac{r_{k}-l_{k}}{p}}{\bigr\rfloor}$ with the values $r_{k} - (r_{k} - l_{k}) mod p$). Using this fact we update the value for the largest answer, skipping the points in the middle of the segment. To calculate these values we need a data structure (for example, Fenwick tree) which sustains the minimum value on the suffix ($lf_{i}$ is the minimum on suffix beginning from element number $i$). All $lf$ values are increasing, so we need only one variable to sustain the index of the segment we are using to update. How we have to consider the points in the middle of some segment. So we have a variable storing the index of the rightmost segment which begins before $lf_{i}$ for current answer $i$. It may seem that the values from the beginning and from the middle of some segment may be used in the wrong order, but it's easy to prove that it's not true. Copmplexity: $O(\frac{L}{p}\log\left(\frac{L}{p}\right)+n)$. We can use a special updating structure based on stack to get rid of Fenwick tree, then complexity will be $O({\frac{L}{p}}+n)$.
[ "binary search", "dp" ]
2,700
null
722
A
Broken Clock
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from $1$ to $12$, while in 24-hours it changes from $0$ to $23$. In both formats minutes change from $0$ to $59$. You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format. For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.
Let's iterate over all possible values that can be shown on the clock. First two digits must form a number from $1$ to $12$ in case of $12$-hours format and a number from $0$ to $23$ in case of $24$-hours format. Second two digits must form a number from $0$ to $59$. For each value, we will count the number of digits that differ from the original ones. Finally, choose the value, that differs in the least number of digits.
[ "brute force", "implementation" ]
1,300
null
722
B
Verse Pattern
You are given a text consisting of $n$ lines. Each line contains some space-separated words, consisting of lowercase English letters. We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'. Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored. The verse patterns for the given text is a sequence of $n$ integers $p_{1}, p_{2}, ..., p_{n}$. Text matches the given verse pattern if for each $i$ from $1$ to $n$ one can divide words of the $i$-th line in syllables in such a way that the total number of syllables is equal to $p_{i}$. You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
Number of syllables, in which we can split a word, can be uniqely defined by the number of vowels in it. Thus, we need to count the number of vowels in each line and compare them to the given sequence.
[ "implementation", "strings" ]
1,200
null
722
C
Destroying Array
You are given an array consisting of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from $1$ to $n$ defining the order elements of the array are destroyed. After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be $0$.
Main observation, that was necessary to solve the problem: since all numbers are non-negative, it makes sense to consider only subsegments, maximal with respect to inclusion. That is, such segments on both sides of which there are either destroyed numbers or the end of the array. Let's solve the problem in reversed order: first destroy all the numbers, and then add them back. We will carry a single value - the current maximum sum among all subsegments. After destroying all the numbers, the answer is equal to zero. Now, we add a new number on each step. To find the maximum subsegment containing this number, we need to find the nearest to the left and to the right destroyed number. This can be done in $O(log n)$ using binary search tree (f.e. set from STL). To find the sum of the numbers in the subsegment, we can compute partial sums of the original array. Thus, at each step, we can update the maximum sum among all subsegments in $O(log n)$ time. The total complexity of this solution is $O(n log n)$.
[ "data structures", "dsu" ]
1,600
null
722
D
Generating Sets
You are given a set $Y$ of $n$ \textbf{distinct} positive integers $y_{1}, y_{2}, ..., y_{n}$. Set $X$ of $n$ \textbf{distinct} positive integers $x_{1}, x_{2}, ..., x_{n}$ is said to generate set $Y$ if one can transform $X$ to $Y$ by applying some number of the following two operation to integers in $X$: - Take any integer $x_{i}$ and multiply it by two, i.e. replace $x_{i}$ with $2·x_{i}$. - Take any integer $x_{i}$, multiply it by two and add one, i.e. replace $x_{i}$ with $2·x_{i} + 1$. Note that integers in $X$ are not required to be distinct after each operation. Two sets of distinct integers $X$ and $Y$ are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set $Y$ and have to find a set $X$ that generates $Y$ and the \textbf{maximum element of $X$ is mininum possible}.
Author's solution appeared to be slightly more complicated than the solutions of most of the participants, so we will describe that simple solution. An arbitrary number $y$ can be obtained from one of the following numbers - $y,\{{\frac{y}{2}}\},\{{\frac{y}{4}}\},\ldots,1$ and only from them. Therefore, we will use the following greedy algorithm: Let's choose the maximum number from the set $Y$ (assume this number is $y_{i}$). We look through all the numbers from which you can obtain the selected number - $y_{i},\left[{\frac{y_{i}}{2}}\right],\left[{\frac{y_{i}}{4}}\right],\ldots\cdot,\ 1\right.$. Among these numbers choose the maximum number, which is not included in the set $Y$ yet. Replace $y_{i}$ with this number and do the above operation again. If at some point it turned out that all of these numbers already belong to the set $Y$, then we print the current set and finish the algorithm. To find the maximum number and to check whether any number is belong to $Y$ or not, you can use the binary search tree (f.e. set from STL) or the combination of priority queue and hash table. Formally, the total complexity of this solution is $O(n log n log 10^{9})$.
[ "binary search", "data structures", "dfs and similar", "greedy", "strings", "trees" ]
1,900
null
722
E
Research Rover
Unfortunately, the formal description of the task turned out to be too long, so here is the legend. Research rover finally reached the surface of Mars and is ready to complete its mission. Unfortunately, due to the mistake in the navigation system design, the rover is located in the wrong place. The rover will operate on the grid consisting of $n$ rows and $m$ columns. We will define as $(r, c)$ the cell located in the row $r$ and column $c$. From each cell the rover is able to move to any cell that share a side with the current one. The rover is currently located at cell $(1, 1)$ and has to move to the cell $(n, m)$. It will randomly follow some \textbf{shortest path} between these two cells. Each possible way is chosen equiprobably. The cargo section of the rover contains the battery required to conduct the research. Initially, the battery charge is equal to $s$ units of energy. Some of the cells contain anomaly. Each time the rover gets to the cell with anomaly, the battery looses half of its charge rounded down. Formally, if the charge was equal to $x$ before the rover gets to the cell with anomaly, the charge will change to $\left|{\frac{x}{2}}\right|$. While the rover picks a random shortest path to proceed, compute the expected value of the battery charge after it reaches cell $(n, m)$. If the cells $(1, 1)$ and $(n, m)$ contain anomaly, they also affect the charge of the battery.
Several auxiliary statements: The number of paths between cells with coordinates $(i_{1}, j_{1})$ and $(i_{2}, j_{2})$, for which $i_{1} \le i_{2}$ and $j_{1} \le j_{2}$, is equal to $\left(^{\left(j_{2}-j_{1}\right)+\left(i_{2}-i_{1}\right)}\right)$. In order to get the answer it is not necessary to find irreducible fraction $\frac{P}{Q}$. Suppose that we have found some fraction $\textstyle{\frac{P_{1}}{Q_{1}}}$, for which the following is true: $P_{1} = P * g$, $Q_{1} = Q * g$. Let's calculate the answer for this fraction: $P_{1} * Q_{1}^{ - 1} \equiv P * g * (Q * g)^{ - 1} \equiv P * g * Q^{ - 1} * g^{ - 1} \equiv P * g * g^{ - 1} * Q^{ - 1} \equiv P * Q (mod 10^{9} + 7)$. From the second statement it implies that the answer can be found in the following form: $Q$ is equal to the number of paths between cells $(1, 1)$ and $(n, m)$, and $P$ is equal to the sum of the battery charges in the endpoint among all paths. The battery charge in the endpoint does not depend on the order of visit of the anomalies, but only on the number of anomalies on the path. Then in order to calculate the required sum it is enough to count the number of paths that pass through the $0, 1, 2$ and so on anomalies. Note that since the original battery charge does not exceed $10^{6}$, and each time you visit the anomaly it is reduced by half, then in all paths, with the number of anomalies greater than or equal to $20$, the charge at the endpoint will be equal to $1$. First let's try to solve a simpler problem: count the number of paths that do not pass through the cells with anomalies. Sort all the cells with anomalies in increasing order of the sum of their coordinates. Then, if the path passes through the anomaly with the number $i$ (in sorted order), then the next cell with anomaly on the path can only be the cell with the number greater than $i$. We calculate the following dynamic: $F(i)$ - number of paths which start in the anomaly with the number $i$, end in the cell $(n, m)$ and don't pass through other anomalies. Let's denote as $paths(i_{1}, j_{1}, i_{2}, j_{2})$ the following value: $\left(^{\left(j_{2}-j_{1}\right)+\left(i_{2}-i_{1}\right)}\right)$ if $i_{1} \le i_{2}, j_{1} \le j_{2}$ and $0$ otherwise. Values of $F$ can be calculated using the following formula: $F(i)=p a t h s(r_{i},c_{i},n,m)-\sum_{j=i+1}^{k}(p a t h s(r_{i},c_{i},r_{j},c_{j})*F(j))$. Every path that passes through at least one anomaly different from the $i$-th, will be subtracted from the total number of paths exactly once - when the $j$ is equal to the number of the last anomaly on this path. Let's go back to the original problem: denote as $G(i, v)$ the number of paths which start in the anomaly with the number $i$, end in the cell $(n, m)$ and pass through exactly $v$ anomalies different from $i$-th. For $v = 0$, $G(i, 0) = F(i)$. For $v > 0$, values of $G$ can be calculated using the following formula: $G(i,v)=p a t h s(r_{i},c_{i},n,m)-\sum_{j=i+1}^{k}p a t h s(r_{i},c_{i},r_{j},c_{j})*G(j,v)-\sum_{j=0}^{v-1}G(i,j)$. Every path that passes through at least $v + 1$ anomalies different from the $i$-th, will be subtracted from the total number of paths exactly once - when the $j$ is equal to the number of $v$-th anomaly from the end on this path. It remains only to subtract all paths that contains less than $v$ anomalies (last part of the formula). For simplicity, you can add an additional anomaly with coordinates $(1, 1)$. In the end, let's iterate over the number of anomalies (from $0$ to $19$) on the path. For each number, we can find the value of the battery charge in the endpoint and multiply it by the number of paths calculated above. Also, add one to the sum for each path that visits $20$ or more anomalies. The resulting complexity of the solution is $O(n^{2} log 10^{6})$.
[ "combinatorics", "dp" ]
2,900
null