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
955
F
Heaps
You're given a tree with $n$ vertices rooted at $1$. We say that there's a $k$-ary heap of depth $m$ located at $u$ if the following holds: - For $m = 1$ $u$ itself is a $k$-ary heap of depth $1$. - For $m > 1$ vertex $u$ is a $k$-ary heap of depth $m$ if \textbf{at least} $k$ of its children are $k$-ary heaps of dep...
Denote $heap_{k}(u)$ as maximum depth of $k$-ary heap rooted at $u$, and $dp_{k}(u)$ as maximum depth of $k$-ary heap in the subtree of $u$ (including $u$). Let $v_{i}$ - children of vertex $u$; sort them in order of descending $heap_{k}{v_{i}}$. Then $heap_{k}(u) = heap_{k}(v_{k}) + 1$, and $dp_{k}(u) = max(heap_{k}(u...
[ "dp", "trees" ]
2,600
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <vector> #include <ctime> #include <unordered_set> #include <string> #include <map> #include <unordered_map> #include <random> #include <set> #include <cassert> #include <functional> #include <queue> #include <numeric> #include <bitset> ...
957
A
Tritonic Iridescence
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas. Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into $n$ consecutive segments, each segment needs to be painted in one of the co...
The problem can be solved in different approaches. Here we describe one based on manually finding out all cases. What causes the answer to be "Yes"? Of course, there cannot be adjacent segments that already have the same colour; but what else? We can figure out that whenever two consecutive question marks appear, there...
[ "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; void NO() { puts("No"); exit(0); } void YES() { puts("Yes"); exit(0); } int main() { int n; cin >> n; string s; cin >> s; for(int i = 0; i < n - 1; ++i) if(s[i] != '?' && s[i] == s[i+1]) NO(); for(int i = 0; i < n; ++i) if(s[i] == '?') { if(i == 0 || i ==...
959
A
Mahmoud and Ehab and the even-odd game
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer $n$ and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer $a$ and subtract it from $n$ such that: - $1 ≤ a ≤ n$. - If it's Mahmoud's turn, $a$ has to be even, but if it's Ehab's turn, ...
It's easy to see that if $n = 0$, the next player loses. If $n$ is even, Mahmoud will choose $a = n$ and win. Otherwise, Mahmoud will have to choose $a < n$. $n$ is odd and $a$ is even, so $n - a$ is odd. Ehab will then subtract it all and win. Therefore, if $n$ is even Mahmoud wins. Otherwise, Ehab wins. $n = 1$ doesn...
[ "games", "math" ]
800
"#include <iostream>\nusing namespace std;\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tif (n%2)\n\tprintf(\"Ehab\");\n\telse\n\tprintf(\"Mahmoud\");\n}"
959
B
Mahmoud and Ehab and the message
Mahmoud wants to send a message to his friend Ehab. Their language consists of $n$ words numbered from $1$ to $n$. Some words have the same meaning so there are $k$ groups of words such that all the words in some group have the same meaning. Mahmoud knows that the $i$-th word can be sent with cost $a_{i}$. For each wo...
It's easy to see that for every word, the minimum cost of sending it is the minimum cost of sending any word in its group. For each group, we'll maintain the minimum cost for sending a word in it (let it be $cost_{i}$) and for each word, we'll maintain its group (let it be $group_{i}$). For every word $i$ in the messag...
[ "dsu", "greedy", "implementation" ]
1,200
"#include <iostream>\n#include <map>\nusing namespace std;\nmap<string,int> d;\nint arr[100005],cost[100005],group[100005];\nint main()\n{\n\tint n,k,m;\n\tcin >> n >> k >> m;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\td[s]=i;\n\t}\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tcin >> arr[i];\n\t\tcost[i]=(...
959
C
Mahmoud and Ehab and the wrong algorithm
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of $n$ nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge $(u, v)$ that belongs to the tree, either $u$ is i...
For $n \ge 6$, you can connect nodes $2$, $3$, and $4$ to node $1$ and connect the rest of the nodes to node $2$. The real vertex cover is the set ${1, 2}$ of size $2$ while the found vertex cover will have size $min(3, n - 3)$. As $n \ge 6$, that value will be $3$ which is incorrect. For $n < 6$, the answer doesn'...
[ "constructive algorithms", "trees" ]
1,500
"#include <iostream>\nusing namespace std;\nint main()\n{\n\tint n;\n\tcin >> n;\n\tif (n<=5)\n\tputs(\"-1\");\n\telse\n\t{\n\t\tfor (int i=2;i<=4;i++)\n\t\tprintf(\"1 %d\\n\",i);\n\t\tfor (int i=5;i<=n;i++)\n\t\tprintf(\"2 %d\\n\",i);\n\t}\n\tfor (int i=2;i<=n;i++)\n\tprintf(\"1 %d\\n\",i);\n}"
959
D
Mahmoud and Ehab and another array construction task
Mahmoud has an array $a$ consisting of $n$ integers. He asked Ehab to find another array $b$ \textbf{of the same length} such that: - $b$ is lexicographically greater than or equal to $a$. - $b_{i} ≥ 2$. - $b$ is pairwise coprime: for every $1 ≤ i < j ≤ n$, $b_{i}$ and $b_{j}$ are coprime, i. e. $GCD(b_{i}, b_{j}) = 1...
Common things : Let's call a number "ok" if it could be inserted to array $b$, as a new element, without breaking any of the conditions (i.e it should be coprime with all the previously inserted elements). Let's call the maximum number that could be inserted in the worst case $mx$. For each integer from 2 to $mx$, we'l...
[ "constructive algorithms", "greedy", "math", "number theory" ]
1,900
"#include <iostream>\n#include <vector>\nusing namespace std;\nvector<int> d[2000005];\nbool p[2000005],used[2000005];\nbool ok(int x)\n{\n\tbool ret=1;\n\tfor (int i:d[x])\n\tret&=!used[i];\n\treturn ret;\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=2;i<2000005;i++)\n\t{\n\t\tif (!p[i])\n\t\t{\n\t\t\...
959
E
Mahmoud and Ehab and the xor-MST
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of $n$ vertices numbered from $0$ to $n - 1$. For all $0 ≤ u < v < n$, vertex $u$ and vertex $v$ are connected with an undirected edge that has weight $u\oplus v$ (wh...
For convenience, let $n$ be the label of the last node not the number of nodes (i.e $n = n_{input} - 1$). Denote $lsb(x) = x&( - x)$ as the value of the least significant bit set to 1 in $x$. The answer is $\sum_{i=1}^{n}l s b(i)$, which means that node $u$ is connected to node $u\oplus l s b(u)$ for all $1 \le u \l...
[ "bitmasks", "dp", "graphs", "implementation", "math" ]
1,900
"#include <iostream>\nusing namespace std;\nlong long dp[50];\nint main()\n{\n\tlong long n;\n\tscanf(\"%I64d\",&n);\n\tfor (int i=1;i<50;i++)\n\tdp[i]=2LL*dp[i-1]+(1LL<<(i-1));\n\tn--;\n\tlong long ans=0;\n\tfor (int i=0;i<50;i++)\n\t{\n\t\tif (n&(1LL<<i))\n\t\tans+=dp[i]+(1LL<<i);\n\t}\n\tprintf(\"%I64d\",ans);\n}"
959
F
Mahmoud and Ehab and yet another xor task
Ehab has an array $a$ of $n$ integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud $q$ queries. In each of them, he gave Mahmoud 2 integers $l$ and $x$, and asked him to find the number of subsequences of the first $l$ elements of the array such that t...
Let's solve a simpler version of the problem. Assume the queries only ask you to see whether the answer is 0 or positive instead of the exact answer. We can answer all the queries offline. We can keep a set containing all the possible xors of subsequences and update it for each prefix. Initially, the set contains only ...
[ "bitmasks", "dp", "math", "matrices" ]
2,400
"#include <iostream>\n#include <vector>\nusing namespace std;\n#define mod 1000000007\nvector<pair<int,int> > v[100005];\nint arr[100005],a[100005];\nvector<int> s;\nbool b[(1<<20)];\nint main()\n{\n\tint n,q;\n\tscanf(\"%d%d\",&n,&q);\n\tfor (int i=0;i<n;i++)\n\tscanf(\"%d\",&arr[i]);\n\tfor (int i=0;i<q;i++)\n\t{\n\t...
960
A
Check the string
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, \textbf{at least one 'a' and one 'b'} exist in the string. ...
Traverse the string once and check if the ASCII value of all characters is greater than or equal or the ASCII value of the previous character. This ensures that the string does not have a,b,c in wrong order. Also, while traversing the string, keep three separate counters for the number of 'a', 'b' and 'c' along. Now, d...
[ "implementation" ]
1,200
#include<bits/stdc++.h> #define rep(i,start,lim) for(lld i=start;i<lim;i++) #define repd(i,start,lim) for(lld i=start;i>=lim;i--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define f first #define s second #define pb push_back #define mp make_pair #define br printf("\n") #define sz(a) lld((a).s...
960
B
Minimize the error
You are given two arrays $A$ and $B$, each of size $n$. The error, $E$, between these two arrays is defined $E=\sum_{i=1}^{n}(a_{i}-b_{i})^{2}$. You have to perform \textbf{exactly} $k_{1}$ operations on array $A$ and \textbf{exactly} $k_{2}$ operations on array $B$. In one operation, you have to choose one element of ...
The problem can be interpreted as follows: array $B$ is fixed and a total of $k_{1} + k_{2} = K$ operations allowed on $A$. Let the array $C$ be defined as $Ci = |Ai - Bi|$ Now this is just a simple greedy problem where value of $E=\sum_{i=1}^{n}C_{i}^{2}$ is to be minimized after exactly $K$ subtraction/addition opera...
[ "data structures", "greedy", "sortings" ]
1,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; priority_queue<ll> pq; int main(){ int n, k1, k2, k; cin>>n>>k1>>k2; k = k1+k2; vector<ll> a(n), b(n), arr(n); for(int i=0 ; i<n ; ++i) cin>>a[i]; for(int i=0 ; i<n ; ++i){ cin>>b[i]; arr[i] = abs(a[i]-...
960
C
Subsequence Counting
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size $n$ has $2^{n} - 1$ non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence $ - $ Minimum_element_of_su...
Let's call a subsequence valid if the difference of maximum element and minimum element is less than d. For an array of size $n$ with all the elements equal, there are $2^{n} - 1$ non-empty subsequences and all of them are valid. This is because for any subsequence, the difference of maximum element and minimum element...
[ "bitmasks", "constructive algorithms", "greedy", "implementation" ]
1,700
#include<bits/stdc++.h> #define rep(i,start,lim) for(lld i=start;i<lim;i++) #define repd(i,start,lim) for(lld i=start;i>=lim;i--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define f first #define s second #define pb push_back #define mp make_pair #define br printf("\n") #define sz(a) lld((a).s...
960
D
Full Binary Tree Queries
You have a full binary tree having infinite levels. Each node has an initial value. If a node has value $x$, then its left child has value $2·x$ and its right child has value $2·x + 1$. The value of the root is $1$. You need to answer $Q$ queries. There are $3$ types of queries: - Cyclically shift the \textbf{valu...
Let us define the root of the tree to be at level $L = 1$. Now, the level $L$ for any value $X$ can be found using this formula: $L = 64 -$ (Number of leading unset bits in $X$). In C++, you can conveniently calculate the leading unset bits by using __builtin_clzll($X$). Let us imagine each level of the tree as an arra...
[ "brute force", "implementation", "trees" ]
2,100
//Gvs Akhil (Vicennial) #include<bits/stdc++.h> #define int long long #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define ld(a) while(a--) #define tci(v,i) for(auto i=v.begin();i!=v.end();i++) #define tcf(v,i) for(auto i : v) #define all(v) v.begin(),v.end() #define rep(i,sta...
960
E
Alternating Tree
Given a tree with $n$ nodes numbered from $1$ to $n$. Each node $i$ has an associated value $V_i$. If the simple path from $u_1$ to $u_m$ consists of $m$ nodes namely $u_1 \rightarrow u_2 \rightarrow u_3 \rightarrow \dots u_{m-1} \rightarrow u_{m}$, then its alternating function $A(u_{1},u_{m})$ is defined as $A(u_{1}...
An important observation for the question is $A(u,v) = -A(v,u)$ if there are even number of nodes on the simple path from $u$ to $v$ $A(u,v) = A(v,u)$ if there are odd number of nodes on the simple path from $u$ to $v$ Hence $A(u,v) + A(v,u)=0$ for paths with even number of nodes. Hence the task has been reduced to fin...
[ "combinatorics", "dfs and similar", "divide and conquer", "dp", "probabilities", "trees" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int M=1000005,mod=1e9+7; vector<int> adj[M]; int par[M],lev[M]; ll v[M]; ll e[M],o[M]; ll ans,res,n; ll powmod(ll base, ll exponent) { //cout<<base<<" "<<exponent<<endl; ll ans=1; while(exponent) { while(exponent%2==0) { base=...
960
F
Pathwalks
You are given a directed graph with $n$ nodes and $m$ edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges a...
The problem is similar to Longest Increasing Subsequence, done on a graph instead of an array. The solution for this problem can be obtained in the following ways:- $Approach1$ Maintain a map for every node, consisting of weights and the corresponding max no of edges you can achieve for some path ending at that node at...
[ "data structures", "dp", "graphs" ]
2,100
#include <bits/stdc++.h> using namespace std; vector<map<int,int> > s; int getedgelen(int a, int w) { auto it = s[a].lower_bound(w); if(it == s[a].begin()) return 1; it--; return (it->second)+1; } int32_t main() { ios::sync_with_stdio(false);cin.tie(0); int n,m,a,b,w; cin>>n>>m; s.resize...
960
G
Bandit Blues
Japate, while traveling through the forest of Mala, saw $N$ bags of gold lying in a row. Each bag has some \textbf{distinct} weight of gold between $1$ to $N$. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag. Initially, he starts with an empty bag (zero weight). He con...
The problem can be seen as to count the number of permutations such that the number of records from the front is A and the number of records from the back is B, where a record is an element greater than all previous. let $s(A, N)$ be the number of permutations such that for $N$ elements exactly $A$ records are present ...
[ "combinatorics", "dp", "fft", "math" ]
2,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back const int mod = 998244353; const int root = 15311432; const int root_1 = 469870224; const int root_pw = 1 << 23; const int N = 400004; vector<int> v[N]; ll modInv(ll a, ll mod = mod){ ll x0 = 0, x1 = 1, r0 = mod, r1 = a; while(...
960
H
Santa's Gift
Santa has an infinite number of candies for each of $m$ flavours. You are given a rooted tree with $n$ vertices. The root of the tree is the vertex $1$. Each vertex contains exactly one candy. The $i$-th vertex has a candy of flavour $f_i$. Sometimes Santa fears that candies of flavour $k$ have melted. He chooses any ...
The actual cost of replacing all candies of flavour $k$ in the subtree of vertex $x$ is $h_k(x) \cdot c_k$. Here, $h_k(x)$ is the number of vertices (candy) in the subtree of $x$ with value (flavour) $k$ and $c_k$ is the cost of replacing each candy of flavour $k$. Error $E(v)$ is defined as $(h_k(x) \cdot c_k - C) ^ 2...
[ "data structures", "trees" ]
3,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back const int N = 400004; int n; vector<int> e[N]; int sz[N], par[N], sp[30][N]; int V[N], L[N], CS[N]; bool mark[N]; struct tri { long long A, B; int C; }; map<int, tri> nmp[N]; long long D[N]; // Sum of Distances long long S[N]...
961
A
Tetris
You are given a following process. There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. Wh...
The answer will be equal to $\min\limits_{i = 1}^{n} cnt_i$, where $cnt_i$ is the number of squares that will appear in the $i$-th column.
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> cnt(n); for (int i = 0; i < m; ++i) { int col; cin >> col; ++cnt[col - 1]; } cout << *min_element(cnt.begin(), ...
961
B
Lecture Sleep
Your friend Mishka and you attend a calculus lecture. Lecture lasts $n$ minutes. Lecturer tells $a_{i}$ theorems during the $i$-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array $t$ of Mishka's behavior. If Mishka is asleep during...
Let's iterate over all $i$ from $1$ to $n$ and if $t_{i}$ is equal to $1$ then add $a_{i}$ to the some variable $res$ and replace $a_{i}$ with $0$. Then answer will be equal to $r e s+\operatorname*{m}_{i=k}^{n}a_{j}{}=\underline{{{i}}}^{i}-k+1}a_{j}$, where $\sum_{j=i-k+1}^{i}a_{j}$ can be easily calculated with prefi...
[ "data structures", "dp", "implementation", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<int> a(n); vector<int> t(n); int overall = 0; for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = ...
961
C
Chessboard
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into $4$ pieces, each of size $n$ by $n$, $n$ is \textbf{always odd}. And what's even worse, some squares were of wrong color. $j$-th square of the $i$-th row of $k$-th piece of the board has c...
Since $n$ is odd, exactly $2$ pieces of the board will have upper left corner colored black (and exactly $2$ - white). Let's check every option to choose two pieces of the board so their upper left corners will be painted white when we assemble the board, calculate the number of board cells that have to be recolored, a...
[ "bitmasks", "brute force", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 109; int n; string a[4][N]; int main() { cin >> n; for(int k = 0; k < 4; ++k) for(int i = 0; i < n; ++i){ cin >> a[k][i]; for(int j = 0; j < n; ++j) a[k][i][j] -= '0'; } vector <int> v; for(int k = 0; k < 4; ++k){ int sum = 0; f...
961
D
Pair Of Lines
You are given $n$ points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?
If the number of points is less than $3$, then the answer is obviously YES. Else let's fix first $3$ points. Check if there is a solution if $1$-st and $2$-nd points lie on the same line. Just erase all points which lie on this line and check the remaining points if they belong to one line. If we didn't find the answer...
[ "geometry" ]
2,000
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define all(a) (a).begin(), (a).end() #define sz(a) int(a.size()) #define mp make_pair #define x first #define y second using namespace std; typedef long long li; typedef pair<int, int> pt; inline pt operator -(const pt &a, const ...
961
E
Tufurama
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the ...
At first, it doesn't matter if some season has more than $n$ episodes, so we can set $a_{i} = min(a_{i}, n)$. Let's maintain next invariant: when we proceed $i$-th season we will have only seasons containing the episodes with indices $ \ge i$. Then the number of pairs $(i, y)$ is just number of seasons with index $ \l...
[ "data structures" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 9; int n; int a[N]; int f[N]; vector <int> v[N]; void upd(int pos, int d){ for(; pos < N; pos |= pos + 1) f[pos] += d; } int get(int pos){ int res = 0; for(; pos >= 0; pos = (pos & (pos + 1)) - 1) res += f[pos]; return res; } int mai...
961
F
k-substrings
You are given a string $s$ consisting of $n$ lowercase Latin letters. Let's denote $k$-substring of $s$ as a string $subs_{k} = s_{k}s_{k + 1}..s_{n + 1 - k}$. Obviously, $subs_{1} = s$, and there are exactly $\textstyle{\left[\!\!{\frac{n}{2}}\right]}$ such substrings. Let's call some string $t$ an \textbf{odd prope...
Let's look at suprefix of fixed $k$-substring: we can't find its maximal length via binary search because this function isn't monotone in general case. But, by fixing not the left border but the center of the prefix, we also fix the center of the corresponding suffix (center of a prefix in position $i$ is tied with the...
[ "binary search", "hashing", "string suffix structures" ]
2,700
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define all(a) (a).begin(), (a).end() #define sz(a) int(a.size()) #define mp make_pair #define x first #define y second using namespace std; typedef long long li; const li MOD = li(1e18) + 3; const li BASE = 1009; inline li norm(...
961
G
Partitions
You are given a set of $n$ elements indexed from $1$ to $n$. The weight of $i$-th element is $w_{i}$. The weight of some subset of a given set is denoted as $W(S)=|S|\cdot\sum_{i\in S}w_{i}$. The weight of some partition $R$ of a given set into $k$ subsets is $W(R)=\sum_{S\in R}W(S)$ (recall that a partition of a given...
Let's look at some facts. At first, the answer is the sum of weights $w_{i}$ taken with some coefficients $cf_{i}$. So, it's enough to calculate those coefficients. Then $cf_{i}$ can be calculated by iterating on the size of the subset containing $i$-th element: $c f_{i}=\sum_{s i z e=1}^{s i z e=n+1-k}s i z e\cdot f(n...
[ "combinatorics", "math", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) const int MOD = int(1e9) + 7; inline int norm(int a) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } inline int mul(int a, int b) { return int((a * 1ll * ...
962
A
Equator
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first. On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on...
To solve the problem we need to know the total number of problems which Polycarp planned to solve. We count it in one iteration through the given array and save the total number of problems in the variable $sum$. After that, we will again iterate through the array and count the number of problems that Polycarp will sol...
[ "implementation" ]
1,300
null
962
B
Students in Railway Carriage
There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carri...
We will iterate from the left to the right through the given string and take the maximal substrings consisting from the dots only (bounded by asterisks/string bounds). Let the length of the current such substring is $len$. If $len$ is even, in the places corresponding to this substring, you can put maximum $len / 2$ st...
[ "constructive algorithms", "greedy", "implementation" ]
1,300
null
962
C
Make a Square
You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently a...
Consider the given integer as a string $s$. Use the masks to brute all possible ways to delete digits. Let the remaining integer for the current mask is a string $t$. If the first character of $t$ is zero, skip this mask. Otherwise, we revert the string $t$ into the integer $cur$. Now we need to check does the $cur$ is...
[ "brute force", "implementation", "math" ]
1,400
null
962
D
Merge Equals
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two...
To solve this problem we should use a set of pairs, let's call it $b$. We will store in it all the elements of the current array (the first number in the pair)and the positions of these elements in the current array (the second number in the pair). The first elements of pairs should have type long long, because the res...
[ "data structures", "implementation" ]
1,600
null
962
E
Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities: - the cities of Byteland, - the cities of Berland, - disputed cities. Recently, the...
We will call the disputed cities - purple points, the cities of Byteland - blue points, and the cities of Berland - red points. If there are no any purple points among the given points, you just need to connect all the neighboring red points between each other and all the neighboring blue points with each other. Thus, ...
[ "constructive algorithms", "greedy" ]
2,200
null
962
F
Simple Cycles Edges
You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself). A cycle in a graph is called a simple, if it conta...
To solve this problem, it is good to know about fundamental set of cycles. Briefly, in the graph it is easy to select such a minimal set of cycles $C$ that any other cycle can be obtained as XOR of some subset of cycles from $C$. This set is also called the fundamental set of cycles. To find it in a connected graph, yo...
[ "dfs and similar", "graphs", "trees" ]
2,400
null
962
G
Visible Black Areas
Petya has a polygon consisting of $n$ vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the ...
First, lets build a graph that represents only part of the polygon that is inside the window, as well as borders of the window. Do do this, for each segment of the polygon, find the intersection of that segment with the window, and, if it still is a segment with non-zero length, add it to the graph (add both endpoints ...
[ "data structures", "dsu", "geometry", "trees" ]
2,800
null
963
A
Alternating Sum
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$. Find out the \textbf{non-n...
Let $Z = \sum \limits_{i=0}^{k - 1} s_{i} a^{n - i} b^{i}$ and $q = (\frac{b}{a})^k$. Let's notice that according equality is true: $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i} = \sum \limits_{i=0}^{(n + 1) / k - 1} Z \cdot q^{i}$ We can easily get values of $Z$, $q$. We only have to count the value of geometric progr...
[ "math", "number theory" ]
1,800
null
963
B
Destruction of a Tree
You are given a tree (a graph with $n$ vertices and $n - 1$ edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tre...
If $n$ is even, then the answer is always $NO$, because such trees have odd degree, but we can destroy only even number of edges. For any odd $n$ the answer exists. Let's call $dfs(i)$ from subtree $i$ and destroy such nodes, that new subtree will be empty or for all alive nodes in connected component will be true, tha...
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,000
null
963
C
Cutting Rectangle
A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least o...
There are a lot of ways to solve this problem. Let $a_i$ occurs in input $cnt_{a_{i}}$ (sum of $c$) times and $a_j$ occurs $cnt_{a_{j}}$. Then on a side of initial rectangle number of times $a_i$ occurs $/$ number of times $a_j$ occurs is a ratio $(cnt_{a_{i}}: cnt_{a_{j}})$. Analogically for $b$. Let's build the small...
[ "brute force", "math", "number theory" ]
2,600
null
963
D
Frequency of String
You are given a string $s$. You should answer $n$ queries. The $i$-th query consists of integer $k_i$ and string $m_i$. The answer for this query is the minimum length of such a string $t$ that $t$ is a substring of $s$ and $m_i$ has at least $k_i$ occurrences as a substring in $t$. A substring of a string is a contin...
Let $M$ be the summary length of $m_i$ Number of different lengths of $m_i$ is $O(\sqrt{M})$. All $m_i$ are distinct, so summary number of their entries in $s$ is $O(M\sqrt{M}))$. Let's find all entries of every $m_i$. To do this we can use Aho-Corasick's algorithm. Then we know entries of $m_i$, it is not hard to calc...
[ "hashing", "string suffix structures", "strings" ]
2,500
null
963
E
Circles of Waiting
A chip was placed on a field with coordinate system onto point $(0, 0)$. Every second the chip moves randomly. If the chip is currently at a point $(x, y)$, after a second it moves to the point $(x - 1, y)$ with probability $p_{1}$, to the point $(x, y - 1)$ with probability $p_{2}$, to the point $(x + 1, y)$ with pro...
Let's call a sell "good", if for its coordinates the following condition is satisfied $x^{2} + y^{2} \le R^{2}$. For each good cell we consider the equation of its expected value: $f(x, y) = p_{1} \cdot f(x - 1, y) + p_{2} \cdot f(x, y + 1) + p_{3} \cdot f(x + 1, y) + p_{4} \cdot f(x, y - 1) + 1$. Then this problem c...
[ "math" ]
3,100
null
964
A
Splits
Let's define a split of $n$ as a nonincreasing sequence of positive integers, the sum of which is $n$. For example, the following sequences are splits of $8$: $[4, 4]$, $[3, 3, 2]$, $[2, 2, 1, 1, 1, 1]$, $[5, 2, 1]$. The following sequences aren't splits of $8$: $[1, 7]$, $[5, 4]$, $[11, -3]$, $[1, 1, 4, 1, 1]$. The...
There are 2 cases: If weight of the split equals $n$, then the split consist of ones. Here we have only 1 option. Else maximum number in the split is more then 1. Then we can replace all maximum numbers with twos and the rest we split into ones and weight will be the same. So, here we have $\frac{n}{2}$ options. Answer...
[ "math" ]
800
null
964
B
Messages
There are $n$ incoming messages for Vasya. The $i$-th message is going to be received after $t_{i}$ minutes. Each message has a cost, which equals to $A$ initially. After being received, the cost of a message decreases by $B$ each minute (it can become negative). Vasya can read any message after receiving it at any mom...
Adding $C \cdot k$ to account is equivalent to adding $C$ to prices of all come, but not read messages. Then after every minute to every unread messages adds $C - B$. If $C - B$ is positive, then answer is maximum when we read all messages at the time $T$. Otherwise we should read every message at the time it comes.
[ "math" ]
1,300
null
965
A
Paper Airplanes
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes. A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people....
Each person should receive $\lceil \frac{n}{s} \rceil$ sheets. So, there should be at least $k \cdot \lceil \frac{n}{s} \rceil$ sheets in total, for them $\lceil \frac{k \cdot \lceil \frac{n}{s} \rceil}{p} \rceil$ packs are needed.
[ "math" ]
800
## This is a solution for problem make-planes # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 16:28:50 +0300 k, n, s, p = map(int, input().split()) sheets_per_person = (n + s - 1) // s sheets = k * sheets_per_person print((sheets + p - 1) // p)
965
B
Battleship
Arkady is playing Battleship. The rules of this game aren't really important. There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arka...
Let's compute for each cell four values: the number of cells where a part of the ship can be located to the right ($r$), to the left ($l$), up ($u$) and down ($d$), including the cell itself. Then, if $k > 1$, then there are $\min(k, \max(0, l + r - k)) + \min(k, \max(0, u + d - k))$ positions of the ship containing th...
[ "implementation" ]
1,300
## This is a solution for problem sea-battle-best-shot # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 16:48:18 +0300 n, k = map(int, input().split()) a = [] for i in range(n): a.append(input()) maxans = 0 xans = 0 yans = 0 for i in range(n): for j in range(n): curans = 0 ...
965
C
Greedy Arkady
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away. The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies ...
As the limits on $D$ are small, let's try all possible values of $d$ - the number of times Arkady will receive candies. For a given $d$ it's easy to compute $x_{min}$ and $x_{max}$ - the maximum and minimum values of $x$ that suit these $d$ and $M$. Then, with a fixed $d$ it's easy to write the formula of how many cand...
[ "math" ]
2,000
## This is a solution for problem candies-splitting # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 21:58:46 +0300 n, k, M, D = map(int, input().split()) ans = 0 for d in range(1, D + 1): # (d - 1) * k * x + x <= n maxx = M maxx = min(n // ((d - 1) * k + 1), maxx) i...
965
D
Single-use Stones
A lot of frogs want to cross a river. A river is $w$ units width, but frogs can only jump $l$ units long, where $l < w$. Frogs can also jump on lengths shorter than $l$. but can't jump longer. Hopefully, there are some stones in the river to help them. The stones are located at integer distances from the banks. There ...
This problem can be solved using many different approaches, most of them are based on different greedy solutions. We will discuss a solution with an easy-provable greedy. First, let's do binary search for the answer. Let it be $k$. Then, assume that the stones are given by their positions $x_1, x_2, \ldots, x_m$, where...
[ "binary search", "flows", "greedy", "two pointers" ]
1,900
/** * This line was copied from template * This is nk_ok.cpp * * @author: Nikolay Kalinin * @date: Mon, 23 Apr 2018 23:38:49 +0300 */ #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pai...
965
E
Short Code
Arkady's code contains $n$ variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code. He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide wi...
First, let's construct a trie of the names. Now a name is a token on some node in the graph, and we can move the token freely up to the root with the only constraint that no two tokens share the same node. We have to minimize the total depth of the nodes with tokens. For each subtree let's compute the optimal positions...
[ "data structures", "dp", "greedy", "strings", "trees" ]
2,200
/** * This line was copied from template * This is nk_ok.cpp * * @author: Nikolay Kalinin * @date: Tue, 24 Apr 2018 19:13:31 +0300 */ #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pai...
967
A
Mind the Gap
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute. He was asked to insert one takeoff in the schedule. The takeoff takes $1$ minut...
This problem requires you to carefully read and understand the statement. First, scan all the landing times, transforming each $h$ and $m$ pair into the number of minutes from the starting moment $60h + m$. Then, there are three possibilities: The first plane takes of not earlier than $s + 1$ minutes from now. In this ...
[ "implementation" ]
1,100
null
967
B
Watering System
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After...
It's obvious that we should block several largest holes. Let's first sort them. After that, let's iterate through the number of blocked holes, maintaining the sum of sizes of non-blocked holes $S$. With the value $S$ it is easy to compute if the flow from the first hole is large enough or not. Just output the number of...
[ "math", "sortings" ]
1,000
null
975
A
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in ...
One can easily notice that we only differentiate between words when different letters exit, so one easy way to consider all the different words that belong to the same root as one, is to map every word to a mask of 26 bits; that is, for example, if letter 'b' exits in the ith word then we set the second bit in the ith ...
[ "implementation", "strings" ]
900
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%d\",&a)\n#define scs(a) scanf(\" %s\",a)\n\n\ntypedef long long ll;\n\nconst int MAX = 1e3 + 11;\n\nchar in[MAX];\nset<int> s;\n\nint main()\n{\n int n;\n sc(n);\n\n for(int i=0;i<n;++i)\n {\n scs(in);\n int l = strlen(...
975
B
Mancala
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a \textbf{positive} number of stones. He takes all the stones inside it and then redistributes these stones one by one in t...
in this problem, we brute-force on the optimal hole to choose since there are only 14 holes, but how to calculate how many stones there will be after we start from the ith hole? the process of putting stones is repeating every 14 holes, suppose k is the number of stones in hand now so k/14 will be added to all holes an...
[ "brute force", "implementation" ]
1,100
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%lld\",&a)\n\ntypedef long long ll;\n\nconst int MAX = 5e3 + 11;\n\nll a[22];\nll pro[22];\n\nint main()\n{\n for(int i=0;i<14;++i)\n sc(a[i]);\n\n ll res = 0;\n\n for(int i=0;i<14;++i)\n {\n for(int j=0;j<14;++j)\n ...
975
C
Valhalla Siege
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle. Ivar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. T...
naive simulations will get TLE, so how to calculate fast how many people are going to die after the ith query, we can binary search on the prefix sum. Thus, we can tell how many people are going to die in O(log n) per query. Note: beware to handle the queries that do a partial damage for some warrior and include that p...
[ "binary search" ]
1,400
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%d\",&a)\n#define scll(a) scanf(\"%lld\",&a)\n\ntypedef long long ll;\n\nconst int MAX = 2e5 + 11;\n\nll a[MAX],csum[MAX];\nint n;\n\nint bs(int pos,ll &hits,ll val)\n{\n if(val + hits < a[pos])\n {\n hits += val;\n return pos...
975
D
Ghosts
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way. There are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrig...
The condition for two points to meet in a moment of time T is for them to have the same X coordinates and the same Y coordinates. Time when they have the same X coordinates is $X_{0i} + V_{xi} T_x = X_{0j} + V_{xj} T_x$ So $T_x$ should be $T_x = (X_{0i} - X_{0j})/ (V_{xj} - V_{xi})$ Time when they will meet on Y axis $...
[ "geometry", "math" ]
2,000
"#include <bits/stdc++.h>\nconst int MX = 2e5+5;\nusing namespace std;\ntypedef long long ll;\nint main() {\n int n;cin>>n;ll a,b;cin>>a>>b;\n map<ll,ll> vis;\n map<pair<int,int>,int> sim;\n ll ans = 0;\n for(int i=1;i<=n;i++)\n {\n int x,vx,vy;\n scanf(\"%d%d%d\",&x,&vx,&vy);\n ans += vis[a*v...
975
E
Hag's Khashba
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering. Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and othe...
In this problem, we calculate the center of mass of the polygon (ie its centroid) and then we make it our reference point. we maintain its coordinates after each and every rotation. Now when the pin is taken out from a vertex it leaves the other pin as a pivot for rotation we calculate the angle of current rotation. ca...
[ "geometry" ]
2,600
"#include <algorithm>\n#include <bitset>\n#include <complex>\n#include <cassert>\n#include <deque>\n#include <iostream>\n#include <iomanip>\n#include <istream>\n#include <iterator>\n#include <map>\n#include <math.h>\n#include <memory>\n#include <ostream>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <...
976
A
Minimum Binary Number
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string $s$. You can perform two different operations on this string: - swap any pair of adjacent characters (for example, "{1\underline{0...
If $n = 1$ then the answer is equal to $s$. Otherwise answer will be equal to $2^{cnt0}$, where $cnt_{0}$ is the count of the zeroes in the given string (i.e. the answer is the binary string of length $cnt_{0} + 1$, in which the first character is one and the other characters are zeroes).
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; if (n == 1) { cout << s << endl; } else { int cnt0 = 0; for (int i = 0; i < n; ++i) cnt0 += s[i] == '0'; cout << 1;...
976
B
Lara Croft and the New Game
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
Naive solution would be just simulate the tranversal and break when $k$ steps are made. Obviously, this won't fit into time limit. Then we can decompose the path to some parts which can be calculated separately. Walk from the top left to the bottom left corner; Walk from second column to $m$-th on even rows; Walk from ...
[ "implementation", "math" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n, m; long long k; int main() { scanf("%d%d%lld", &n, &m, &k); if (k < n){ printf("%lld 1\n", k + 1); return 0; } k -= n; long long row = k / (m - 1); printf("%lld ", n - row); if (row & 1) printf("%ll...
976
C
Nested Segments
You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ of one-dimensional segments numbered $1$ through $n$. Your task is to find two distinct indices $i$ and $j$ such that segment $a_{i}$ lies within segment $a_{j}$. Segment $[l_{1}, r_{1}]$ lies within segment $[l_{2}, r_{2}]$ iff $l_{1} ≥ l_{2}$ and $r_{1} ≤ r_{2}$. ...
Let's sort segments firstly by their left border in increasing order and in case of equal by their right border in decreasing order. If there is any valid pair then the inner segment will always go after the outer one. Now you can go from left to right, keep the maximum right border of processed segments and compare it...
[ "greedy", "implementation", "sortings" ]
1,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define x first #define y second using namespace std; typedef pair<int, int> pt; const int N = 300 * 1000 + 13; int n; pair<pt, int> a[N]; int main() { scanf("%d", &n); forn(i, n){ scanf("%d%d", &a[i].x.x, &a[i].x.y); a[i].y = i + ...
976
D
Degree Set
You are given a sequence of $n$ positive integers $d_{1}, d_{2}, ..., d_{n}$ ($d_{1} < d_{2} < ... < d_{n}$). Your task is to construct an undirected graph such that: - there are exactly $d_{n} + 1$ vertices; - there are no self-loops; - there are no multiple edges; - there are no more than $10^{6}$ edges; - its degre...
We prove that the answer always always exists by constructing it. Graph for $n = 0$ is a single vertex; Graph for $n = 1$ is a clique of $d_{1} + 1$ vertices; Graph for some $(d_{1}, d_{2}, ..., d_{k})$ is obtained from the graph $(d_{2} - d_{1}, d_{3} - d_{1}, ..., d_{k - 1} - d_{1})$ by adding $(d_{k} - d_{k - 1})$ v...
[ "constructive algorithms", "graphs", "implementation" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef pair<int, int> pt; const int N = 100 * 1000 + 13; int n; vector<int> d; vector<int> g[N]; vector<pt> construct(int st, vector<int> d){ if (d.empty()) return vector<pt>(); vector<pt> res; forn(i, d[0]) ...
976
E
Well played!
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them: Max owns $n$ creatures, $i$-th of them can be described with two numbers — its health $hp_{i}$ and its damage $dmg_{i}$. Max also ...
At first let's prove that in optimal solution all spells of 1-st type are assigned to single creature. By contradiction: let's optimal answer contains indices $i \neq j$ where $hp'_{i} = hp_{i} \cdot 2^{x}$ and $hp'_{j} = hp_{j} \cdot 2^{y}$. If $hp'_{i(j)} \le dmg_{i(j)}$ using spells of 1-st type is meaningless. ...
[ "greedy", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 9; int n, a, b; int hp[N], dmg[N]; bool cmp(int i, int j){ if(hp[i] - dmg[i] != hp[j] - dmg[j]) return hp[i] - dmg[i] > hp[j] - dmg[j]; return i < j; } int get(int id){ return hp[id] > dmg[id]? hp[id] : dmg[id]; } int main(){ scanf("%...
976
F
Minimal k-covering
You are given a bipartite graph $G = (U, V, E)$, $U$ is the set of vertices of the first part, $V$ is the set of vertices of the second part and $E$ is the set of edges. There might be multiple edges. Let's call some subset of its edges $\bar{E}$ $k$-covering iff the graph ${\bar{G}}=(U,V,{\bar{E}})$ has each of its v...
To get the answer for some $k$ we can build the following network: connect the source to every vertex of the first part with edge with capacity $deg_{x} - k$ (where $deg_{x}$ is the degree of vertex), then transform every edge of the original graph into a directed edge with capacity $1$, and then connect each vertex fr...
[ "flows", "graphs" ]
2,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second const int INF = int(1e9); const int N = 4221; struct edge { int to, c, f, id; edge(int to = 0, int c = 0, int f = 0, int id = -1) : to(to),...
977
A
Wrong Subtraction
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, s...
In this problem you just need to simulate the process described in the statement (i.e. $k$ times repeat the following operation: if $n \% 10 = 0$ then $n := n / 10$ else $n := n - 1$) and print the result.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; for (int i = 0; i < k; ++i) { if (n % 10 == 0) n /= 10; else n--; } cout << n << endl; return 0; }
977
B
Two-gram
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string $s$ consisting of $n$ capital Latin letters. Your task is to find \textbf{any} two-gram contained in the given string \textbf{as a substring} (i.e. two cons...
There are at least two different approaches to this problem: You can iterate over all substrings of $s$ of length $2$ and calculate for each of them the number of its occurrences in $s$ (and try to update the result with the current substring). Also you can iterate over all two-grams in the alphabet and do the same as ...
[ "implementation", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; string s; cin >> s; int res = 0; string ans; for (int i = 0; i < n - 1; ++i) { int cur = 0; for (int j = 0; j < n - 1; ++j) if (s[...
977
C
Less or Equal
You are given a sequence of integers of length $n$ and integer number $k$. You should print \textbf{any integer} number $x$ in the range of $[1; 10^9]$ (i.e. $1 \le x \le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$. Note that the sequence can contain equal elements. If there ...
In this problem you can do the following thing: firstly, let's sort our array. Let $ans$ will be the answer. Then you have two cases: if $k = 0$ then $ans := a_0 - 1$ otherwise $ans := a_{k - 1}$ (for 0-indexed array). Then you need to calculate the number of the elements of the array $a$ that are less than or equal to...
[ "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); sort(a.begin(), a.end()); int ans; if (k == 0...
977
D
Divide by three, multiply by two
Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds: - divide the number $x$ by $3$ ($x$ must be divisible by $3$); - multiply the number $x$ by $2$. After each operation, Polycarp writes down the result on t...
Let $deg_3(x)$ be the maximum integer $y$ such that $3^y | x$ ($x$ is divisible by $3^y$). Our problem is to rearrange the given array in such a way that (easy to see it if we look at our operations) if it looks like $a_{i_1}, a_{i_2}, \dots, a_{i_n}$, then for each $k \in [1..n - 1]$ the next inequality will be satisf...
[ "dfs and similar", "math", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long LL; int count3(LL x){ int ret=0; while(x % 3 == 0){ ret++; x /= 3; } return ret; } int n; vector<pair<int,LL>> v; int main(){ cin>>n; v.resize(n); for(int i=0; i<n; i++){ cin>>v[i].second; v[i].first=-count3(v[i].second); } ...
977
E
Cyclic Components
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles. Here are some definitions of graph theory. An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of verti...
Let's solve this problem for each connected component of the given graph separately. It is easy to see that the connected component is a cycle iff the degree of each its vertex equals to $2$. So the solution is to count the number of components such that every vertex in the component has degree $2$. The connected compo...
[ "dfs and similar", "dsu", "graphs" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 11; int n, m; int deg[N]; bool used[N]; vector<int> comp; vector<int> g[N]; void dfs(int v) { used[v] = true; comp.push_back(v); for (auto to : g[v]) if (!used[to]) dfs(to); } int main() { #ifdef _DEBUG freopen("input.txt", "r", st...
977
F
Consecutive Subsequence
You are given an integer array of length $n$. You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $[x, x + 1, \dots, x + k - 1]$ for some value $x$ and length $k$. Su...
Let $dp[x]$ be the answer for our problem if the last element of our subsequence equals to $x$. Then we have an easy solution: let's store $dp$ as a "std::map" (C++) or "HashMap" (Java). Initially for each $i \in [1..n]$ $dp[a_i] = 0$. Then let's iterate over all $a_i$ in order of input and try to update $dp[a_i]$ with...
[ "dp" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); map<int, int> dp; int ans = 0; int lst = 0; for (int i = 0;...
978
A
Remove Duplicates
Petya has an array $a$ consisting of $n$ integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
We will store integers which we already met in a set $exist$. Let's iterate through the given array from the right to the left. Let the current element is equal to $x$. So, if $x$ does not contain in $exist$ we add $x$ in a vector-answer $ans$ and add $x$ in $exist$. After we considered all elements the answer sequence...
[ "implementation" ]
800
null
978
B
File Name
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
Let's iterate through the given string from the left to the right. In a variable $cnt$ we will store the number of letters "x" which were before the current letter in a row. If the current letter does not equal to "x" we should make $cnt = 0$. In the other case, the current letter equals to "x". If $cnt < 2$, we should...
[ "greedy", "strings" ]
800
null
978
C
Letters
There are $n$ dormitories in Berland State University, they are numbered with integers from $1$ to $n$. Each dormitory consists of rooms, there are $a_i$ rooms in $i$-th dormitory. The rooms in $i$-th dormitory are numbered from $1$ to $a_i$. A postman delivers letters. Sometimes there is no specific dormitory and roo...
We should use that the letter queries are given in increasing order of room numbers. We will store in a variable $sum$ the number of rooms in already considered dormitories (this variable should have 64-bit type) and in a variable $idx$ we will store the minimum number of dormitory where the room from the current lette...
[ "binary search", "implementation", "two pointers" ]
1,000
null
978
D
Almost Arithmetic Progression
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3...
If $n \le 2$ we can print $0$, because each such sequence is an arithmetic progression. Note, that an arithmetic progression is uniquely determined by the first two terms. So we should brute $d_1$ from $-1$ to $1$ - the change of the first element of the given sequence, and $d_2$ from $-1$ to $1$ - the change of the se...
[ "brute force", "implementation", "math" ]
1,500
null
978
E
Bus Video System
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops. If $x$ is the number of passengers in a bus just before the current bus stop and $y$ is the number of passengers in the bus just after current bus stop, th...
Firstly we should find the minimum and maximum numbers of passengers, which could be in a bus if initially it was empty. Let $b = 0$. We should iterate through the bus stops. For the $i$-th bus stop, we add $a_i$ to $b$ and update with a value of $b$ the minimum number of passengers $minB$ and the maximum number of pas...
[ "combinatorics", "math" ]
1,400
null
978
F
Mentors
In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$. A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a > r_b)$ and programmers $a$ and $b$ are not in a quarrel. You are gi...
Firstly we should sort all programmers in non-decreasing order of their skills. Also we need to store initially numbers of the programmers (we can user array of pairs - skill and initial number of the programmer). We will iterate through the programmers from the left to the right. The current programmer can be a mentor...
[ "binary search", "data structures", "implementation" ]
1,500
null
978
G
Petya's Exams
Petya studies at university. The current academic year finishes with $n$ special days. Petya needs to pass $m$ exams in those special days. The special days in this problem are numbered from $1$ to $n$. There are three values about each exam: - $s_i$ — the day, when questions for the $i$-th exam will be published, - ...
If in the current day there is no exam, we should prepare for an exam, for which questions already given, for which we prepare less than needed and which will be before other remaining exams. For this we will use array $cnt$, where $cnt_i$ equals to the number of days, which we already prepared for exam $i$. Initially,...
[ "greedy", "implementation", "sortings" ]
1,700
null
979
A
Pizza, Pizza, Pizza!!!
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
If $n = 0$, the answer is obviously $0$. If $n + 1$ is even, we can make $\textstyle{\frac{n+1}{2}}$ diametric cuts. Otherwise, the only way is to make $n + 1$ cuts. Time complexity: $O(1)$.
[ "math" ]
1,000
#include <stdio.h> using namespace std; long long n; int main() { scanf("%I64d", &n); n++; if (n == 1) printf("0"); else if (n % 2 == 0) printf("%I64d", n / 2); else printf("%I64d", n); return 0; }
979
B
Treasure Hunt
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her. The three friends are very smart so they passed all the challenges very quickly and finally reached the destination...
We all knew that the substrings with length $1$ appear at most in the string. So, to make a string as beautiful as possible, we will choose the letter that firstly appears at most in the string and replace all the other letters with the chosen letter. There is some cases. If $n$ is less than or equal to the number of r...
[ "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; int a[256], b[256], c[256], n, ma, mb, mc; string p, q, r; int main() { cin >> n >> p >> q >> r; for (char x: p) ma = max(ma, ++a[x]); for (char x: q) mb = max(mb, ++b[x]); for (char x: r) mc = max(mc, ++c[x]); if (n == 1 && ma == (int)p.len...
979
C
Kuro and Walking Route
Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which h...
We can consider the city as a graph, in which every town is a vertex and every road connecting two towns is an edge. Since $m$ < $n$, we can deduce that this graph is a tree. Now, instead of finding the number of pairs that Kuro can choose, we can find the number of pairs that Kuro cannot choose. In other words, we mus...
[ "dfs and similar", "trees" ]
1,600
#include <iostream> #include <cstdio> #include <vector> using namespace std; const int MAXN = 3e5; int n, m, u, v, x, y, sub_size[MAXN + 5]; bool vis[MAXN + 5], chk_sub[MAXN + 5]; vector<int> adj[MAXN + 5]; int DFS(int u) { vis[u] = true; sub_size[u] = 1; if (u == x) chk_sub[u] = true; else chk_s...
979
D
Kuro and GCD and XOR and SUM
Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day. Sadly, he's going on a vacation for a day, and he isn't able to continue his solving str...
We first look at the condition $k_{i}\mid G C D(x_{i},v)$. This condition holds iff both $x_{i}$ and $v$ are divisible by $k_{i}$. Therefore, if $k_{i}\uparrow x_{i}$, we return -1 immediately, else we only consider numbers in $a$ that are divisible by $k_{i}$. Finding the maximum XOR of $x_{i}$ with $v$ in the array $...
[ "binary search", "bitmasks", "brute force", "data structures", "dp", "dsu", "greedy", "math", "number theory", "strings", "trees" ]
2,200
#include <iostream> #include <cstdio> #include <vector> using namespace std; const int MAX = 1E5 + 5; struct SNode { int mi; SNode *bit[2]; SNode() { mi = MAX; bit[0] = bit[1] = nullptr; } } *rt[MAX]; vector<int> di[MAX]; int q, t, u, k, x, s; bool chk[MAX]; void init() { for...
979
E
Kuro and Topological Parity
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games. Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot o...
The problem asks us to find the number of different simple directed acyclic graphs with $1 \rightarrow n$ forming its topological order to ensure the parity of the number of alternating paths to be equal to $p$. We will solve this problem using the dynamic programming approach. Let's define even-white as the number o...
[ "dp" ]
2,400
#include <iostream> using namespace std; const int N = 55, MOD = 1E9 + 7; int n, p, c[N]; long long ans = 0, pw[N], fct[N], inv[N], od[N], ev[N], f[N][N][N][N]; long long power(int u, int p) { if (p == 0) return 1; long long ret = power(u, p >> 1); (ret *= ret) %= MOD; if (p & 1) (ret...
980
A
Links and Pearls
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you l...
The problem can be viewed as the following: You have a cyclic array with the characters '-' and 'o', you want to rearrange the elements of the array such that the number of '-' characters after every 'o' character is the same. So we want to distribute the '-' characters over the 'o' characters so that all the 'o' chara...
[ "implementation", "math" ]
900
null
980
B
Marlin
The city of Fishtopia can be imagined as a grid of $4$ rows and an \textbf{odd} number of columns. It has two main villages; the first is located at the top-left cell $(1,1)$, people who stay there love fishing at the Tuna pond at the bottom-right cell $(4, n)$. The second village is located at $(4, 1)$ and its people ...
Instead of looking at the second path from $(4, 1)$ to $(1, n)$, consider it as from $(1, n)$ to $(4, 1)$. Now when $k$ is even, we can do the following: start from (2,2), put a hotel in that cell and another hotel in (2,n-1), then a hotel in (2,3) and one in (2, n-2), and so on until either the second row is full (exp...
[ "constructive algorithms" ]
1,600
null
980
C
Posterized
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter. Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, theref...
First, it's obvious that for each group we should choose the color with minimum value as the group's key. Now since we want to find the lexicographically smallest array, we iterate from the leftmost number in the array and minimize it as much as possible without considering the numbers to its right. There are many ways...
[ "games", "greedy" ]
1,700
null
980
D
Perfect Groups
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one grou...
First let us examine perfect squares; a perfect square is a number $x$ that can be written as the product of an integer and itself $y*y$. This means that for each prime factor of the number $x$, the frequency of that factor must be even so it can be distributed evenly between each of the two $y$'s. This leads to the id...
[ "dp", "math", "number theory" ]
2,100
null
980
E
The Number Games
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant. The nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i...
As the final set of remaining districts need to be reachable from each other, this means that the resulting tree is a sub-graph of the original one. Now, looking at the number of fans in each district, district $i$ has $2^{i}$ fans. This means that if we had a choice of including a district $i$ in our solution and disc...
[ "data structures", "greedy", "trees" ]
2,200
null
980
F
Cactus to Tree
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle. Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting ...
The following solution is implemented in 136 lines, but most of it is a simple BFS and two DFS functions for finding bridges and marking cycles, the main part of the solution is implemented in 38 lines. Please check the code after (or while?) reading if it is not clear. Note that if we run a BFS from a node $u$, the BF...
[ "dp", "graphs", "trees" ]
2,900
"#include <stdio.h>\n#include <vector>\n#include <queue>\n#include <memory.h>\n#include <algorithm>\nusing namespace std;\ntypedef long long ll;\nconst int N = 500000;\nint n, m;\nint L[N], Z[N], maxLen[N];\nvector<vector<pair<int, int> > > g;\nbool isBridge[2 * N];\nint low[N], idx[N], dfs;\nbool vis[N];\nint parent[N...
981
A
Antipalindrome
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1 \leq l \leq r \leq |s|$) of a string $s = s_{1}s_{2} \ldots ...
You can just check all substrings on palindromity in $O(n^3)$. Also you can note that if all characters in the string are same, then answer is $0$, else, if string is not a palindrome, answer is $n$, else you can delete last char and get answer $n-1$, so you can solve the task in $O(n)$.
[ "brute force", "implementation", "strings" ]
900
null
981
B
Businessmen Problems
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the ...
With $map$ data structure for each chemical element that presents in input find maximal cost that you can get, and then just sum up these costs
[ "sortings" ]
1,000
null
981
C
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two pa...
Let's prove that all paths in this decomposition have one intersection vertex. 1) Any pair of paths have exactly one intersecting vertex, because else there are common edge (so it is not a decomposition) or cycle (so graph is not a tree). 2) Let's assume that there are several intersection points. Let us have three pat...
[ "implementation", "trees" ]
1,400
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#inclu...
981
D
Bookshelves
Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with some books on it, each book has an integer positive price. Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office. He learned that in the new...
Let's build answer from significant bit to least significant bit. We want to check, is there some partition in $k$ segments, such that all segment's sums have significant bit? We can check it with $dp_{n, k}$ - is there some partition of first $n$ elements on $k$ segments such that all segment's sums have significant b...
[ "bitmasks", "dp", "greedy" ]
1,900
"#include <cstdio>\n#include <cstring>\n\ntypedef long long int64;\nstatic const int MAXN = 52;\nstatic const int LOGA = 56;\n\nstatic int k, n;\nstatic int64 a[MAXN], s[MAXN];\n\nstatic bool feas[MAXN][MAXN];\n\ninline bool dp_check(int64 targ, int64 mask)\n{\n memset(feas, false, sizeof feas);\n feas[0][0] = tr...
981
E
Addition on Segments
Grisha come to a contest and faced the following problem. You are given an array of size $n$, initially consisting of zeros. The elements of the array are enumerated from $1$ to $n$. You perform $q$ operations on the array. The $i$-th operation is described with three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq ...
Suppose we know the index where the maximum is. Let's examine which requests we decided to take. Surely there is no need to take requests which doesn't contain the index of maximum. Because if you delete them, they will not impact maximum and nothing will change. This way we can see, that any possible answer is a sum o...
[ "bitmasks", "data structures", "divide and conquer", "dp" ]
2,200
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <iomanip>\n#include <bi...
981
F
Round Marriage
It's marriage season in Ringland! Ringland has a form of a circle's boundary of length $L$. There are $n$ bridegrooms and $n$ brides, and bridegrooms decided to marry brides. Of course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom. All objects in Ringland...
Key idea is that there there is a cut which is not crossed by anyoner (in other words, it is not profitable if brides will travel whole circle) So we can solve the problem in $O(n \cdot L)$ - fix the cut, and match $i$-th bridegrom (in increasing order) with $i$-th bride (if we will order brides in the traversal order ...
[ "binary search", "graph matchings", "greedy" ]
2,500
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <iomanip>\n#include <bi...
981
G
Magic multisets
In the School of Magic in Dirtpolis a lot of interesting objects are studied on Computer Science lessons. Consider, for example, the magic multiset. If you try to add an integer to it that is already presented in the multiset, each element in the multiset duplicates. For example, if you try to add the integer $2$ to t...
For each value of $x$, let's maintain the set of elements on which this value is present. We will do this by maintaining segments in the set (don't worry, we will get rid of this unpleasant part later). Then you just need to take all the segments crossing $l$ or $r$, cut them into two smaller ones, and then everything ...
[ "data structures" ]
2,500
"/*\n Author: isaf27 (Ivan Safonov)\n*/\n\n//#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n//defines\ntypedef long long ll;\ntypedef double ld;\n#define TIME clock() * 1.0 / CLOCKS_PER_SEC\n#define fast_read cin.sync_with_stdio(0)\n#define nul point(0, 0)\n#define str_to_int(strok...
981
H
K Paths
You are given a tree of $n$ vertices. You are to select $k$ (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and ...
For each vertex $v$ let's calculate $f_v$ - number of ways to choose $k$ ends for paths in their subtree, such that these paths are edge-intersecting, and $g_v$ - sum of $f_u$ by all vertices $u$ in subtree of $v$. Let $sz_v$ will be number of vertices in subtree of $v$. Then let $P(x) = (1 + x \cdot sz_{u_{0}}) \cdot ...
[ "combinatorics", "data structures", "dp", "fft", "math" ]
3,100
"#pragma GCC optimize(\"O3\")\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#i...
982
A
Row
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: - There are no neighbors adjacent to anyone seated. - It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means that ...
Seating is the maximum when it does not exist two ones or three zeros together. It is also necessary to carefully process the ends of the series - it is necessary to check that you can not put a person on the most right or the most left chairs.
[ "brute force", "constructive algorithms" ]
1,200
null
982
B
Bus of Characters
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct. Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers: - an introvert always chooses ...
Note that the final introvert-extrovert pairs are uniquely determined, and that using the stack, it is possible to recover which extrovert to which introvert will sit (note that the zeros and ones will form the correct bracket sequence). Then one of the solutions may be as follows: Sort the array of the lengths of the ...
[ "data structures", "greedy", "implementation" ]
1,300
null
982
C
Cut 'em all!
You're given a tree with $n$ vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
Note that if there is an edge that can be removed, we can do it without any problem. Let's consider such edge that in one of the obtained subtrees it is impossible to delete more anything else, and its removal is possible. What happens if we delete it in the tree? Relative to the other end of the edge, the odd-even bal...
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
1,500
null
982
D
Shark
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations. Max is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the d...
Let's sort the array and insert the numbers in the sort order from smaller to larger. Using the data structure "disjoint set union" we can easily maintain information about the current number of segments, as well as using the map within the function of union, and information about the current size of segments (location...
[ "brute force", "data structures", "dsu", "trees" ]
1,900
null
982
E
Billiard
Consider a billiard table of rectangular size $n \times m$ with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture). There is one ball at the point $(x, y)$ currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is paral...
If you symmetrically reflect a rectangle on the plane relative to its sides, the new trajectory of the ball will be much easier. Linear trajectory if be correct. One possible solution is: If the vector is directed at an angle of 90 degrees to the axes, then write the if-s. Otherwise, turn the field so that the impact v...
[ "geometry", "number theory" ]
2,600
null
982
F
The Meeting Place Cannot Be Changed
Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two in...
Let's assume that solution exists and will looking for solution relying on this assumption. At the end will check found "solution" in linear time, and if it is not real solution, then assumption wasn't right. If solution exists, then intersection (by vertices) of all cycles is not empty. Let's take any one cycle and ca...
[ "dfs and similar", "graphs" ]
2,700
null
983
A
Finite or not?
You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction. A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that...
First, if $p$ and $q$ are not coprime, divide them on $\gcd(p,q)$. Fraction is finite if and only if there is integer $k$ such that $q \mid p \cdot b^k$. Since $p$ and $q$ are being coprime now, $q \mid b^k \Rightarrow$ all prime factors of $q$ are prime factors of $b$. Now we can do iterations $q = q \div \gcd(b,q)$ w...
[ "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; while (n--) { long long p, q, b; cin >> p >> q >> b; long long g = gcd(p, q); q /= g; b = gcd(q, b); while (b != 1) { while (q % b == 0) q /= b; b = gcd(q...
983
B
XOR-pyramid
For an array $b$ of length $m$ we define the function $f$ as \begin{center} $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $ \end{center} where $\oplus$ is bitwise exclusive OR. For example, $f(1,2,4,8)=f(1\o...
Let's calculate $f(a)$ recursively and save arrays from each level of recursion. We get two-dimencional array $dp[n][n]$ and $dp[n][1]=f(a)$. Now let's view recursive calculation for $f(a_l \ldots a_r)$. You can see what array of $i$-th level of recursion is $dp[i][l\ldots r-i+1]\Rightarrow dp[r-l+1][l]=f(a_l \ldots a_...
[ "dp" ]
1,800
#include <bits/stdc++.h> using namespace std; int run(); int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); run(); } const int N = 5000; int a[N]; int dp[N][N]; int run...
983
C
Elevator
You work in a big office. It is a $9$ floor building with an elevator that can accommodate up to $4$ people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also,...
This problem is inspired by living in the house of $9$ floors with the elevator, which can accommodate up to $4$ people. What a surprise! We have a strict order. So let's make $dp[i][state] =$ minimal possible time, where $i$ means that first $i$ employees already came in the elevator (and possibly came out). So, what ...
[ "dp", "graphs", "shortest paths" ]
2,400
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <set> #include <bitset> #include <queue> #include <stack> #include <sstream> #include <cstring> #include <numeric> #include <ctime> #include <cassert> #define re return #define fi f...
983
D
Arkady and Rectangles
Arkady has got an infinite plane painted in color $0$. Then he draws $n$ rectangles filled with paint with sides parallel to the Cartesian coordinate axes, one after another. The color of the $i$-th rectangle is $i$ (rectangles are enumerated from $1$ to $n$ in the order he draws them). It is possible that new rectangl...
First let's compress the coordinates. Now all the coordinates are in $[0, 2n)$. Now we do scanline on $x$ coordinate with segment tree on $y$ coordinate. Let's talk about segment tree structute. In each vertex we store: Set of colors which cover the whole segment. If color covers a segment, we don't push it to it child...
[ "data structures" ]
3,300
#include <bits/stdc++.h> using namespace std; namespace solution { int run(); } int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); solution::run(); } namespace solution { con...
983
E
NN country
In the NN country, there are $n$ cities, numbered from $1$ to $n$, and $n - 1$ roads, connecting them. There is a roads path between any two cities. There are $m$ bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by ...
Let's say we go down when we go towards the root, and we go up when we go against the root. Also we say that vertex $a$ lower than vertex $b$ if $a$ is closer to the root. Each way from $v$ to $u$ can be represented as two parts: at first we go down from $v$ to $lca$ and then we go up from $lca$ to $u$. Let's say we ha...
[ "binary search", "data structures", "trees" ]
2,800
#include <bits/stdc++.h> using namespace std; int run(); int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); run(); } const int N = 200000; const int logN = 19; int n; vec...
984
A
Game
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players ...
First let's notice that the first player makes $\lceil \frac{n - 1}{2} \rceil$ turns and the second one makes $\lfloor \frac{n - 1}{2} \rfloor$. So, if numbers are $1$-indexed and sorted, first player can make the answer not more than $(n - \lceil \frac{n - 1}{2} \rceil)$-th by deleting maximal number every time. The s...
[ "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int a[1000]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); cout << a[(n - 1) / 2]; }
984
B
Minesweeper
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficu...
Let's make two-dimensional array $d[n][m]$. For each cell $i,j$ if it has bomb in it we add $1$ in $d[g][h]$ where $g,h$ is neighboring cell for $i,j$. Now $d[i][j]$ is a number of bombs in neighboring cells of $i,j$ and we can check validity of field according to the condition of the problem: If there is a number $k$ ...
[ "implementation" ]
1,100
#include <iostream> #include <vector> using std::vector; using std::cin; using std::cout; void setbomb(int x, int y, int n, int m, vector<vector<int>> &ans) { if (x > 0) { if (y > 0) ans[x - 1][y - 1]++; ans[x - 1][y]++; if (y < m - 1) ans[x - 1][y + 1]++; } if (x < n - 1) { if (y > 0) ans[x + 1][...