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 ⌀ |
|---|---|---|---|---|---|---|---|
797 | B | Odd sum | You are given sequence $a_{1}, a_{2}, ..., a_{n}$ of integer numbers of length $n$. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequen... | The answer to this problem can be constructed this way: Sum up all positive numbers Find maximum $max_{odd}$ of negative odd numbers Find minimum $min_{odd}$ of positive odd numbers If sum was even then subtract $min(min_{odd}, - max_{odd})$ Overall complexity: $O(n)$. | [
"dp",
"greedy",
"implementation"
] | 1,400 | null |
797 | C | Minimal string | Petya recieved a gift of a string $s$ with length up to $10^{5}$ characters for his birthday. He took two more empty strings $t$ and $u$ and decided to play a game. This game has two possible moves:
- Extract the \textbf{first} character of $s$ and append $t$ with this character.
- Extract the \textbf{last} character ... | On every step you should maintain minimal alphabetic letter in current string $s$ (this can be done by keeping array of 26 cells with number of times each letter appear in string nd updating it on every step). Let's call string $t$ a stack and use its terms. Now you extract letters from $s$ one by one. Put the letter t... | [
"data structures",
"greedy",
"strings"
] | 1,700 | null |
797 | D | Broken BST | Let $T$ be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree $T$:
- Set... | Let's firstly consider tree with only distinct values in its nodes. Then value will be reached if and only if all the jumps to the left children on the path from the root were done from the vertices with values greater than the current one and all the jumps to the right children on the path from the root were done from... | [
"data structures",
"dfs and similar"
] | 2,100 | null |
797 | E | Array Queries | $a$ is an array of $n$ positive integers, all of which are not greater than $n$.
You have to process $q$ queries to this array. Each query is represented by two numbers $p$ and $k$. Several operations are performed in each query; each operation changes $p$ to $p + a_{p} + k$. There operations are applied until $p$ bec... | There are two possible solutions in $O(n^{2})$ time. First of them answers each query using simple iteration - changes $p$ to $p + a_{p} + k$ for each query until $p$ becomes greater than $n$, as stated in the problem. But it is too slow. Second solution precalculates answers for each $p$ and $k$: if $p + a_{p} + k > n... | [
"brute force",
"data structures",
"dp"
] | 2,000 | null |
797 | F | Mice and Holes | One day Masha came home and noticed $n$ mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.
The corridor can be represeted as a numeric axis with $n$ mice and $m$ holes on it. $i$th mouse is at the coordinate $x_{i}$, and $j$th hole — at coordina... | This problem can be solved using dynamic programming. Let $dp_{i, j}$ be the answer for first $i$ holes and $j$ mice. If the constraints were smaller, then we could calculate it in $O(n^{2}m)$ just trying to update $dp_{i, j}$ by all values of $dp_{i - 1, k}$ where $k \le j$ and calculating the cost to transport all ... | [
"data structures",
"dp",
"greedy",
"sortings"
] | 2,600 | null |
798 | A | Mike and palindrome | Mike has a string $s$ consisting of only lowercase English letters. He wants to \textbf{change exactly one} character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings... | Let $cnt$ be the number of $1\leq i\leq{\frac{n}{2}}$ such that $s_{i} \neq s_{n - i + 1}$. If $cnt \ge 2$ then the answer is NO since we must change more than 1 character. If $cnt = 1$ then the answer is YES. If $cnt = 0$ and $n$ is odd answer is YES since we can change the character in the middle, otherwise if $n... | [
"brute force",
"constructive algorithms",
"strings"
] | 1,000 | "# include <bits/stdc++.h>\nusing namespace std;\nint main(void)\n{\n string s;\n cin>>s;\n s = '#' + s;\n int n = s.length() - 1;\n int cnt = 0;\n for (int i = 1;i + i <= n;++i)\n if (s[i] != s[n - i + 1])\n ++cnt;\n if ((cnt <= 1 && (n&1)) || cnt == 1) puts(\"YES\");\n else p... |
798 | B | Mike and strings | Mike has $n$ strings $s_{1}, s_{2}, ..., s_{n}$ each consisting of lowercase English letters. In one move he can choose a string $s_{i}$, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike ... | First of all, you must notice that the operation of removing the first character and appending it to the left is equivalent to cyclically shifting the string one position to the left. Let's denote by $dp_{i, j}$ the smallest number of operations for making the first $i$ strings equal to string $s_{i}$ moved $j$ times. ... | [
"brute force",
"dp",
"strings"
] | 1,300 | "# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\nstring s[512];\nint dp[512][512];\nint main(void)\n{\n int n;\n fi>>n;\n for (int i = 1;i <= n;++i)\n fi>>s[i];\n int k = s[1].length();\n for (int i = 1;i <= n;++i)\n for (int j = 0;j < k;++j)\n ... |
798 | C | Mike and gcd problem | Mike has a sequence $A = [a_{1}, a_{2}, ..., a_{n}]$ of length $n$. He considers the sequence $B = [b_{1}, b_{2}, ..., b_{n}]$ beautiful if the $gcd$ of all its elements is bigger than $1$, i.e. $\operatorname*{gcd}(b_{1},b_{2},\dots,b_{n})>1$.
Mike wants to change his sequence in order to make it beautiful. In one mo... | First of all, the answer is always YES. If $\operatorname*{gcd}(a_{1},a_{2},...,a_{n})\neq1$ then the answer is $0$. Now suppose that the gcd of the sequence is $1$. After we perform one operation on $a_{i}$ and $a_{i + 1}$, the new gcd $d$ must satisfy $d|a_{i} - a_{i + 1}$ and $d|a_{i} + a_{i + 1}$ $\longrightarrow\b... | [
"dp",
"greedy",
"number theory"
] | 1,700 | "# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\nint main(void)\n{\n int n;\n fi>>n;\n int g = 0,v,cnt = 0,ans = 0;\n while (n --)\n {\n int v;\n fi>>v;\n g = __gcd(g,v);\n if (v & 1) ++cnt;\n else ans += (cnt / 2) + 2 * (cnt & 1),cnt... |
798 | D | Mike and distribution | Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers $A = [a_{1}, a_{2}, ..., a_{n}]$ and $B = [b_{1}, b_{2}, ..., b_{n}]$ of length $n$ each which he uses to... | In the beginning, it's quite easy to notice that the condition " $2 \cdot (a_{p1} + ... + a_{pk})$ is greater than the sum of all elements in $A$ " is equivalent to " $a_{p1} + ... + a_{pk}$ is greater than the sum of the remaining elements in $A$ ". Now, let's store an array of indices $C$ with $C_{i} = i$ and then so... | [
"constructive algorithms",
"sortings"
] | 2,400 | "# include <bits/stdc++.h>\nusing namespace std;\n# define vi vector < int >\n# define pb push_back\nint a[1 << 20];\nint b[1 << 20];\nint p[1 << 20];\nint main(void)\n{\n int n;\n scanf(\"%d\",&n);\n for (int i = 1;i <= n;++i)\n scanf(\"%d\",&a[i]);\n for (int i = 1;i <= n;++i)\n scanf(\"%d\"... |
798 | E | Mike and code of a permutation | Mike has discovered a new way to encode permutations. If he has a permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, he will encode it in the following way:
Denote by $A = [a_{1}, a_{2}, ..., a_{n}]$ a sequence of length $n$ which will represent the code of the permutation. For each $i$ from $1$ to $n$ sequentially, he wil... | Let's consider $a_{i} = n + 1$ instead of $a_{i} = - 1$. Let's also define the sequence $b$, where $b_{i} = j$ such that $a_{j} = i$ or $b_{i} = n + 1$ if there is no such $j$. Lets make a directed graph with vertices be the indices of the permutation $p$ with edges of type $(a, b)$ representing that $p_{a} > p_{b}$. I... | [
"constructive algorithms",
"data structures",
"graphs",
"sortings"
] | 3,000 | "# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\n# define x first\n# define y second\n# define IOS ios_base :: sync_with_stdio(0)\nint a[1 << 20];\nint b[1 << 20];\npair < int , int > t[1 << 22];\nvoid build(int p,int u,int node)\n{\n if (p == u) t[node] = {b[p],p};\n else\n ... |
799 | A | Carrot Cakes | In some game by Playrix it takes $t$ minutes for an oven to bake $k$ carrot cakes, all cakes are ready at the same moment $t$ minutes after they started baking. Arkady needs at least $n$ cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady... | One of possible solutions - to simply simulate described process. To make it we need two variables - $t_{1}$ and $t_{2}$. In them we will store the time when each of the ovens will become free. In the beginning $t_{1}$ equals to $0$ and $t_{2}$ equals to $d$. After simulating the process we will get a time for which po... | [
"brute force",
"implementation"
] | 1,100 | null |
799 | B | T-shirt buying | A new pack of $n$ t-shirts came to a shop. Each of the t-shirts is characterized by three integers $p_{i}$, $a_{i}$ and $b_{i}$, where $p_{i}$ is the price of the $i$-th t-shirt, $a_{i}$ is front color of the $i$-th t-shirt and $b_{i}$ is back color of the $i$-th t-shirt. All values $p_{i}$ are distinct, and values $a_... | Let's store in three arrays t-shirts which have appropriate color. About each t-shirt is enough to store its index, but we will additionally store its cost. It is possible that one t-shirt will be in two arrays (if this t-shirt colorful). Then we need to sort t-shirts in each array in increasing order of cost. After th... | [
"data structures",
"implementation"
] | 1,400 | null |
799 | C | Fountains | Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are $n$ available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are all... | There are three ways - Arkady builds one fountain for coins and other for diamonds, Arkady builds both fountains for coins and Arkady builds both fountains for diamonds. In the end we need to choose a way with maximum total beauty. The first way is simple - we need to choose one fountain of each type with maximum beaut... | [
"binary search",
"data structures",
"implementation"
] | 1,800 | null |
799 | D | Field expansion | In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are $n$ extensions, the $i$-th of them multiplies the width or the length (b... | At first let's check if rectangle can be placed on given field - if it is possible print 0. In the other case we need to expand the field. Let's sort all extensions in descending order and take only $34$ from them - it is always enough based on given constraints. After that we need to calculate linear dynamic where $d_... | [
"brute force",
"dp",
"meet-in-the-middle"
] | 2,100 | null |
799 | E | Aquarium decoration | Arkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have $n$ decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose \textbf{exactly} $m$ decorations from given, and they want to spend as little money as possible.
There is one difficul... | Let's divide the decorations in four groups: that aren't liked by anybody (group 0), that are liked only by Masha (group 1), that are liked only by Arkady (group 2), that are liked by both (group 3). Sort each group by the cost. Then, it's obvious that in optimal solution we should take several (or 0) first elements in... | [
"data structures",
"greedy",
"two pointers"
] | 2,500 | null |
799 | F | Beautiful fountains rows | Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not.
The butler wants to show Arkady $n$ gardens. Each garden is a row of $m$ cells, the $i$-th garden has one fountain in each of the cells between $l_{i}$ and $r_{i}$ inclusive, and there ... | Let's describe an $O((n + m)^{2})$ solution first. Let's try all possible pairs $(a, b)$ and check if they suit us. Let's try all values of $a$ from $1$ to $m$. Let garden $(x, y)$ denote a garden with fountains from $x$ to $y$, and let's say that a garden bans a position $x$ for a fixed $a$ if there is non-zero even n... | [
"data structures"
] | 3,500 | null |
799 | G | Cut the pie | Arkady reached the $n$-th level in Township game, so Masha decided to bake a pie for him! Of course, the pie has a shape of convex $n$-gon, i.e. a polygon with $n$ vertices.
Arkady decided to cut the pie in two equal in area parts by cutting it by a straight line, so that he can eat one of them and give the other to M... | Let's first prove that solution always exists. Define $f( \alpha )$ as the difference between the area of the polygon part contained in the halfplane with polar angles in range $[ \alpha , \alpha + \pi ]$ and the area of the polygon part contained in the halfplane with polar angles in range $[ \alpha + \pi , \alp... | [
"binary search",
"data structures",
"geometry"
] | 3,500 | null |
801 | A | Vicious Keyboard | Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string $s$ with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maxi... | We can count the number of times the string "VK" appears as a substring. Then, we can try to replace each character with "V" or "K", do the count, and return the maximum such count. Alternatively, we can notice if there are currently $X$ occurrences of "VK" in the string, then we can either have $X$ or $X + 1$ after mo... | [
"brute force"
] | 1,100 | print (lambda s: s.count("VK") + int(any(x*3 in "K" + s + "V" for x in "VK")))(raw_input()) |
801 | B | Valued Keys | You found a mysterious function $f$. The function takes two strings $s_{1}$ and $s_{2}$. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function $f$ is another string of the same length. The $i$-th character of the output is equal to the minimum of the $i$-... | First, let's check for impossible cases. If there exists a position $i$ such that the $i$-th character of $x$ is less than the $i$-th character of $y$, then it is impossible. Now, let's assume it's always possible and construct an answer. We can notice that each position is independent, so let's simplify the problem to... | [
"constructive algorithms",
"greedy",
"strings"
] | 900 | x,y = raw_input(), raw_input()
print all(a>=b for a,b in zip(x,y)) * y or "-1" |
803 | A | Maximal Binary Matrix | You are given matrix with $n$ rows and $n$ columns filled with zeroes. You should put $k$ ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicograph... | Let's construct matrix from top to bottom, from left to right. At current step we consider position $(i, j)$. Look at contents of cells $a[i][j]$ and $a[j][i]$. If number of zeroes in them doesn't exceed $k$, then let's fill those cells with ones and decrease $k$ by this number. If $k$ isn't equal to $0$ in the end of ... | [
"constructive algorithms"
] | 1,400 | null |
803 | B | Distances to Zero | You are given the array of integer numbers $a_{0}, a_{1}, ..., a_{n - 1}$. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array. | Let's divide the solution into two parts: firstly check the closest zero to the left and then the closest zero to the right. After that we can take minimum of these numbers. Initialize distance with infinity. Iterate over array from left to right. If value in current position is $0$ then set distance to $0$, otherwise ... | [
"constructive algorithms"
] | 1,200 | null |
803 | C | Maximal GCD | You are given positive integer number $n$. You should create such \textbf{strictly increasing} sequence of $k$ positive numbers $a_{1}, a_{2}, ..., a_{k}$, that their sum is equal to $n$ and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequenc... | Notice that GCD of the resulting sequence is always a divisor of $n$. Now let's iterate over all divisors up to $\sqrt{n}$. Current divisor is $d$. One of the ways to retrieve resulting sequence is to take $d, 2d, 3d, ..., (k - 1) \cdot d$, their sum is $s$. The last number is $n - s$. You should check if $n - s > (k -... | [
"constructive algorithms",
"greedy",
"math"
] | 1,900 | null |
803 | D | Magazine Ad | The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more th... | Firstly notice that there is no difference between space and hyphen, you can replace them with the same character, if you want. Let's run binary search on answer. Fix width and greedily construct ad - wrap word only if you don't option to continue on the same line. Then check if number of lines doesn't exceed $k$. Over... | [
"binary search",
"greedy"
] | 1,900 | null |
803 | E | Roma and Poker | Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes $1$ virtual bourle from the loser.
Last evening Roma started to play poker. He decided to spend no more than $k$ virtual b... | This problem can be solved using dynamic programming: $dp_{i, j}$ is true if Roma could play first $i$ games with balance $j$. $dp_{0, 0}$ is true; and for each $dp_{i, j}$ such that $0 \le i < n$ and $- k < j < k$ we update $dp_{i + 1, j + 1}$ if $s_{i} = W$, $dp_{i + 1, j}$ if $s_{i} = D$, $dp_{i + 1, j - 1}$ if $s... | [
"dp",
"graphs"
] | 2,000 | null |
803 | F | Coprime Subsequences | Let's call a non-empty sequence of positive integers $a_{1}, a_{2}... a_{k}$ coprime if the greatest common divisor of all elements of this sequence is equal to $1$.
Given an array $a$ consisting of $n$ positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo ... | This problem can be solved using inclusion-exclusion. Let $f(x)$ be the number of subsequences such that all elements of the subsequence are divisible by $x$. We can calculate $cnt(x)$, which is the number of elements divisible by $x$, by factorizing all elements of the sequence and generating their divisors, and $f(x)... | [
"bitmasks",
"combinatorics",
"number theory"
] | 2,000 | null |
803 | G | Periodic RMQ Problem | You are given an array $a$ consisting of positive integers and $q$ queries to this array. There are two types of queries:
- $1$ $l$ $r$ $x$ — for each index $i$ such that $l ≤ i ≤ r$ set $a_{i} = x$.
- $2$ $l$ $r$ — find the minimum among such $a_{i}$ that $l ≤ i ≤ r$.
We decided that this problem is too easy. So the... | Most of the solutions used the fact that we can read all the queries, compress them and process after the compression using simple segment tree. But there is also an online solution: Let's build a sparse table on array $b$ to answer queries on segments that are not modified in $O(1)$. To process modification segments, ... | [
"data structures"
] | 2,300 | null |
804 | A | Find Amir | A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are $n$ schools numerated from $1$ to $n$. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools $i$ ... | Consider pairs of schools cost of their traverse is $0$: $\{1,n\},\;\{2,n-1\},\;\{3,n-2\}\ldots,\;\{\lfloor{\frac{x}{2}}\},\;\}{\frac{x}{2}}\}+1\}$. Connect this pairs with traversing from the second of each pair to the first of the next pair. So if $n = 2 \cdot k$ the answer is $k - 1$ and if $n = 2 \cdot k + 1$ the a... | [
"constructive algorithms",
"greedy",
"math"
] | 1,000 | int main(){
int n;
scanf("%d", &n);
printf("%d\n", (n-1)/2);
} |
804 | B | Minimum number of steps | We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo $10^{9}... | The final state will be some character $'a'$ after $'b'$: $"bbb...baaa...a"$ It's obvious to prove all $'b'$s are distinctive to each other(i.e. Each $'b'$ in the initial state, will add some number of $'b'$s to the final state disjoint from other $'b'$s). For a character $'b'$ from the initial state it will double aft... | [
"combinatorics",
"greedy",
"implementation",
"math"
] | 1,400 | int c,d,i,n,m,k,x,j=1000000007;
string s;
main(){
cin>>s;
for(i=s.size()-1;i>=0;i--){
if(s[i]=='b')c++;else{
k+=c;c*=2;k%=j;c%=j;
}
}
cout<<k;
} |
804 | C | Ice cream coloring | Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"
We have a tree $T$ with $n$ vertices and $m$ types of ice cream numerated from $1$ to $m$. Each vertex $i$ has a set of $s_{i}$ types of ice cream. Vertices w... | Let's guess as obvious as possible. We can get the answer is at least $\begin{array}{r}{\mathbf{Hax}\mathbf{S}{\hat{z}}_{i}}\\ {\mathbf{k}{\hat{-}}i\leq n}\end{array}$.We'll just use a dfs to paint the graph with this answer. Run dfs and in each step, when we are in vertex $v$ with parent $par$, for each ice cream, if ... | [
"constructive algorithms",
"dfs and similar",
"greedy"
] | 2,200 | vector <int> Vs[300050];
vector <int> conn[300050];
int ans[300050];
bool chk[500050];
bool dchk[300050];
vector <int> Vu;
void DFS(int n) {
dchk[n] = true;
for (auto it : Vs[n]) {
if (ans[it]) chk[ans[it]] = true;
else Vu.push_back(it);
}
int a = 1;
for (auto it : Vu) {
while (chk[a]) a++;
ans[it] = a+... |
804 | D | Expected diameter of a tree | Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.
We have a forest (acyclic undirected graph) with $n$ vertices and $m$ edges. There are $q$ queries we should answer. In each query two vertices $v$ and $u$ are given. Let... | Let's solve the problem for two trees. Define $d_{t}$ as diameter of $t$-th tree and $f_{ti}$ as the maximum path starting from $i$-th vertex of $t$-th tree, for all valid $i$ and $j$, assume that the edge is between them and find the diameter with $max(f_{1i} + f_{2j} + 1, max(d_{1}, d_{2}))$. The answer will be: $\fr... | [
"binary search",
"brute force",
"dfs and similar",
"dp",
"sortings",
"trees"
] | 2,500 | using namespace std ;
#define int long long
const int MAXN = 1e5 + 100 ;
vector<int>ver[MAXN] , com[MAXN] , ps[MAXN] ;
int vis[MAXN] , dis[MAXN] ;
int mxr , mxid ;
void dfs(int v , int col = -1 , int h = 0 , int par = -1){
vis[v] = max(vis[v] , col) ;
if(mxr < h)mxid = v , mxr = h ;
dis[v] = max(h , dis[v]) ... |
804 | E | The same permutation | Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions $(i, j)$, where $i < j$, exactly once. MoJaK does... | If $\textstyle{{\binom{n}{2}}\mod2=1}$ then it is simply provable the answer is "NO". So we just need to check $n = 4 \cdot k, 4 \cdot k + 1$. There is a constructive solution to do that. Assume that $n = 4 \cdot k$. Partition numbers to $k$ classes, each class contains a $4$ consecutive numbers. We can solve each clas... | [
"constructive algorithms"
] | 3,100 | int n;
int main()
{
scanf("%d",&n);
if(n%4>1)return printf("NO\n"),0;
printf("YES\n");
for(int i=1;i<n;i+=4)
{
if(n%4)printf("%d %d\n%d %d\n%d %d\n",i+2,n,i+2,i+3,i+3,n);
else printf("%d %d\n",i+2,i+3);
printf("%d %d\n",i,i+2);
printf("%d %d\n",i+1,i+3);
printf("%d %d\n",i+1,i+2);
printf("%d %d\n",i,i... |
804 | F | Fake bullions | In Isart people don't die. There are $n$ gangs of criminals. The $i$-th gang contains $s_{i}$ evil people numerated from $0$ to $s_{i} - 1$. Some of these people took part in a big mine robbery and picked \textbf{one} gold bullion each (these people are given in the input). That happened $10^{100}$ years ago and then a... | As the hints said this problem have two part: First we want to solve the first part that is evaluating the $mn_{i}$ and $mx_{i}$ for gangs. Obviously $mn_{i}$ will be the number of thieves have a gold in $i$-th gang. $lemma1$:Consider there is just a single edge from $v$ to $u$; as hints said if one thief in $v$ with i... | [
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"number theory"
] | 3,400 | #include <bits/stdc++.h>
#define xx first
#define yy second
#define mp make_pair
#define pb push_back
#define fill( x, y ) memset( x, y, sizeof x )
#define copy( x, y ) memcpy( x, y, sizeof x )
using namespace std;
typedef long long LL;
typedef pair < int, int > pa;
inline int read()
{
int sc = 0, f = 1; char ch = g... |
805 | A | Fake NP | Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given $l$ and $r$. For all integers from $l$ to $r$, inclusive, we wrote down all of their integer divisors except $1$. Find the integer that we wrote down the maximum number of tim... | If $l \le r$ the answer is 2, other wise l. To prove this phrase, assume the answer is $x$ ($2 < x$), consider all of multiples of $x$ from $l$ to $r$ as $z_{1}, z_{2}, ..., z_{k}$. If $k = = 1$, $2$ is also a correct answer, otherwise numbers from $l$ to $z_{2} - 1$ make at least $3$ even number, and for each multip... | [
"greedy",
"math"
] | 1,000 | int main(){
int l, r;
scanf("%d%d", &l, &r);
printf("%d", l == r ? l : 2);
} |
805 | B | 3-palindrome | In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given $n$ he wants to obtain a string of $n$ characters, each of which is either 'a', 'b' or 'c', with no palindromes of length $3$ appearing in the string as a ... | The answer is constructive as follows: $"aabbaabbaabb..."$ From: saliii, Writer: saliii Time Complexity: $O(1)$ Time Complexity: ${\mathcal{O}}(n)$ Memory complexity: ${\mathcal{O}}(n)$ | [
"constructive algorithms"
] | 1,000 | int N;
int main()
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
putchar(i & 2 ? 'b' : 'a');
puts("");
} |
807 | A | Is it rated? | \underline{Is it rated?}
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their ra... | To solve this problem, you just had to read the problem statement carefully. Looking through the explanations for the example cases was pretty useful. How do we check if the round is rated for sure? The round is rated for sure if anyone's rating has changed, that is, if $a_{i} \neq b_{i}$ for some $i$. How do we chec... | [
"implementation",
"sortings"
] | 900 | n = int(input())
results = []
for i in range(n):
results.append(list(map(int, input().split())))
for r in results:
if r[0] != r[1]:
print("rated")
exit()
for i in range(n):
for j in range(i):
if results[i][0] > results[j][0]:
print("unrated")
exit()
print("... |
807 | B | T-Shirt Hunt | Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.
Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place $p$.
Now the elimination r... | This problem was inspired by this comment: http://codeforces.com/blog/entry/49663#comment-337281. The hacks don't necessarily have to be stupid, though :) Initially, we have $x$ points. To win the current round, we need to score any number of points $s$ such that $s \ge y$. If we know our final score $s$, we can chec... | [
"brute force",
"implementation"
] | 1,300 | p, x, y = map(int, input().split())
def check(s):
i = (s // 50) % 475
for t in range(25):
i = (i * 96 + 42) % 475
if 26 + i == p:
return True
return False
for up in range(500):
for down in range(500):
if x + 100 * up - 50 * down >= y and check(x + 100 * up - 50 * do... |
808 | A | Lucky Year | Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long... | Notice that the next lucky year always looks like (first digit of the current + 1) $ \cdot $ 10^(number of digits of the current - 1). It holds also for numbers starting with 9, it will be 10 $ \cdot $ 10^(number of digits - 1). The answer is the difference between the next lucky year and current year. | [
"implementation"
] | 900 | null |
808 | B | Average Sleep Time | It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts $k$ days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp k... | To get the sum for $i$-th week you need to take sum of ($i - 1$)-th week, subtract first element of ($i - 1$)-th week from it and add up last element of $i$-th week. All common elements will remain. Thus by moving right week by week calculate sum of all weeks and divide it by $n - k + 1$. Overall complexity: $O(n)$. | [
"data structures",
"implementation",
"math"
] | 1,300 | null |
808 | C | Tea Party | Polycarp invited all his friends to the tea party to celebrate the holiday. He has $n$ cups, one for each of his $n$ friends, with volumes $a_{1}, a_{2}, ..., a_{n}$. His teapot stores $w$ milliliters of tea ($w ≤ a_{1} + a_{2} + ... + a_{n}$). Polycarp wants to pour tea in cups in such a way that:
- Every cup will co... | At first, let's pour minimal amount of tea in each cup, that is $\left|{\frac{a_{1}}{2}}\right|$. If it requires more tea than available then it's -1. Now let's sort cups in non-increasing order by volume and start filling up them until we run out of tea in the teapot. It's easy to see that everyone will be satisfied t... | [
"constructive algorithms",
"greedy",
"sortings"
] | 1,400 | null |
808 | D | Array Division | Vasya has an array $a$ consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element ... | Suppose we want to move an element from the prefix to the suffix (if we need to move an element from the suffix to the prefix, we can just reverse the array and do the same thing). Suppose the resulting prefix will contain $m$ elements. Then we need to check that the prefix with $m + 1$ elements contains an element suc... | [
"binary search",
"data structures",
"implementation"
] | 1,900 | null |
808 | E | Selling Souvenirs | After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as us... | There are lots of different solutions for this problem. We can iterate on the number of $3$-elements we will take (in this editorial $k$-element is a souvenir with weight $k$). When fixing the number of $3$-elements (let it be $x$), we want to know the best possible answer for the weight $m - 3x$, while taking into acc... | [
"binary search",
"dp",
"greedy",
"ternary search"
] | 2,300 | null |
808 | F | Card Game | Digital collectible card games have become very popular recently. So Vova decided to try one of these.
Vova has $n$ cards in his collection. Each of these cards is characterised by its power $p_{i}$, magic number $c_{i}$ and level $l_{i}$. Vova wants to build a deck with total power not less than $k$, but magic number... | The most tricky part of the problem is how to check if some set of cards allows us to build a deck with the required power (not taking the levels of cards into account). Suppose we have not more than one card with magic number $1$ (if there are multiple cards with this magic number, then we obviously can use only one o... | [
"binary search",
"flows",
"graphs"
] | 2,400 | null |
808 | G | Anthem of Berland | Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.
Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.
H... | Let's denote the string obtained by concatenation $t + # + s$ (where $#$ is some dividing character that isn't a part of the alphabet) as $ts$. Recall that KMP algorithm builds the prefix function for this string. We can calculate $dp[i][j]$ on this string, where $i$ is the position in this string and $j$ is the value ... | [
"dp",
"strings"
] | 2,300 | null |
809 | A | Do you want a date? | Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to $n$ computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on t... | We know, that a lot of different solutions exists on this task, I will describe the easiest in my opinion. Let's sort the coordinates in ascending order and iterate through the pairs of neighbours $x_{i}$ and $x_{i + 1}$. They are adding to the answer $x_{i + 1} - x_{i}$ in all the subsets, in which there is at least o... | [
"implementation",
"math",
"sortings"
] | 1,500 | st[0] = 1;
for ( int j = 1; j < maxn; j++ )
st[j] = ( 2 * st[j - 1] ) % base;
int n;
scanf ( "%d", &n );
for ( int j = 0; j < n; j++ )
scanf ( "%d", &a[j] );
sort( a, a + n );
int ans = 0;
for ( int j = 1; j < n; j++ ) {
int len = a[j] - a[j - 1];
int cntL = j;
int cntR = n - j;
int add = ( 1LL ... |
809 | B | Glad to see you! | \textbf{This is an interactive problem. In the output section below you will see the information about flushing the output.}
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot... | Let's start with searching the first point. We can do it using this binary search: let's ask points $mid$ and $mid + 1$ each time, when we calculated the center of search interval. So we always know in which of the halves $[l, mid], [mid + 1, r]$ exists at least one point. Since in the initial interval there is at leas... | [
"binary search",
"interactive"
] | 2,200 | int query(int x,int y){
if(x==-1)return 0;
cout<<1<<' '<<x<<' '<<y<<endl;
string ret;
cin>>ret;
return ("TAK"==ret);
}
int get(int l,int r){
if(l>r)return -1;
while(l<r){
int m=(l+r)/2;
if(query(m,m+1)){
r=m;
}else l=m+1;
}
return l;
}
int main(... |
809 | C | Find a car | After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Form... | At first, let's examine that numbers in the matrix are equal to binary xor of the row and column. Precisely, the number in cell $i, j$ is equal to $(i-1)\oplus(j-1)+1$. Now let's split the query into 4 queries to the matrix prefix, as we usually do it in matrix sum queries. In order to find the answer to the query, we ... | [
"combinatorics",
"divide and conquer",
"dp"
] | 2,600 |
ll dp[32][2][2][2];
ll sum[32][2][2][2];
void add(ll &x,ll y){
x+=y;
if(x>=mod)x-=mod;
}
void sub(ll &x,ll y){
x-=y;
if(x<0)x+=mod;
}
ll mul(ll x,ll y){
return x*y%mod;
}
ll pot[32];
ll solve(int x,int y,int z){
if(x<0||y<0||z<0)return 0;
memset(dp,0,sizeof dp);
memset(sum,0,sizeof... |
809 | D | Hitchhiking in the Baltic States | Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking.
In total, they intended to visit $n$ towns. Howeve... | Let $dp_{i}$ - minimal number that can be last in strictly increasing subsequence with length $i$. Iterate through prefixes of intervals and maintain this dp. Obviously this dp is strictly increasing. What happens when we add new interval $l, r$: Thinking from the facts above, we can solve this task maintaining dp in c... | [
"data structures",
"dp"
] | 2,900 | struct node {
int prior, sz, dp, add;
node *l, *r;
node ( int x ) {
prior = ( rand() << 15 ) | rand();
// sz = 1;
dp = x;
l = r = NULL;
add = 0;
}
};
typedef node * pnode;
void push( pnode T ) {
T -> dp += T -> add;
if ( T -> l )
T -> l -> add +... |
809 | E | Surprise me! | Tired of boring dates, Leha and Noora decided to play a game.
Leha found a tree with $n$ vertices numbered from $1$ to $n$. We remind you that tree is an undirected graph without cycles. Each vertex $v$ of a tree has a number $a_{v}$ written on it. Quite by accident it turned out that all values written on vertices ar... | Here $ \phi (x)$ denotes Euler's totient function of $x$, $gcd(x, y)$ is the greatest common divisor of $x$ and $y$ and $f(x)$ denotes the amount of divisors of $x$. Small remark. We need to find the answer in the form of $\frac{P}{Q}$, where $gcd(P, Q) = 1$. Let $A$ will be the sum of all pairwise values $f(u, v)$ and... | [
"divide and conquer",
"math",
"number theory",
"trees"
] | 3,100 |
#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <numeric>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <vector>
#include <math.h>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
using ... |
810 | A | Straight <<A>> | Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.
In school, where Noora is studying, teachers are putting down marks to the online class register, wh... | It is obvious that add any marks less than $k$ isn't optimal. Therefore, iterate on how many $k$ marks we add to the registry and find minimal sufficient number. | [
"implementation",
"math"
] | 900 | int n, k, s = 0;
cin >> n >> k;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
s += x;
}
for (int ans = 0;; ans++) {
int a = 2 * (s + ans * k);
int b = (2 * k - 1) * (ans + n);
if (a >= b) {
cout << ans;
return 0;
}
} |
810 | B | Summer sell-off | Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following $n$ days. For each day sales manag... | Initially, the number of sold products on $i$-th day is $min(k_{i}, l_{i})$ and in sell-out day is $min(2 * k_{i}, l_{i})$. Let's sort days in descending of $min(2 * k_{i}, l_{i}) - min(k_{i}, l_{i})$ and take first $f$ days as sell-out days. | [
"greedy",
"sortings"
] | 1,300 | for (int i = 0; i < n; i++) {
cin >> k[i] >> l[i];
a.push_back(make_pair(min(2 * k[i], l[i]) - min(k[i], l[i]), i));
}
sort(a.rbegin(), a.rend());
long long ans = 0;
for (int i = 0; i < f; i++) {
int pos = a[i].second;
ans += min(2 * k[pos], l[pos]);
}
for (int i = f; i < n; i++) {
int pos = a[i].s... |
811 | A | Vladik and Courtesy | At regular competition Vladik and Valera won $a$ and $b$ candies respectively. Vladik offered $1$ his candy to Valera. After that Valera gave Vladik $2$ his candies, so that no one thought that he was less generous. Vladik for same reason gave $3$ candies to Valera in next turn.
More formally, the guys take turns givi... | Let's simulate process, described in problem statement. I.e subtract from $a$ and $b$ numbers $1, 2, 3, ...$, until any of them is less than zero. The process would terminate less than in $\sqrt{10^{9}}$ iterations, because sum of arithmetical progression with $n$ members is approximately equal to $n^{2}$. | [
"brute force",
"implementation"
] | 800 | null |
811 | B | Vladik and Complicated Book | Vladik had started reading a complicated book about algorithms containing $n$ pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, where $p_{i}$ denotes the number of page that should be read $i$-th in turn.
Somet... | Obviously, that all the elements in range, which are less than $p_{x}$ will go to the left of $p_{x}$ after sort. So the new position will be $l + cnt_{less}$. Let's find $cnt_{less}$ with simple iterating through all the elements in the segment. $O(n * m)$ Challenge. Can you solve the problem with $n, m \le 10^{6}$? | [
"implementation",
"sortings"
] | 1,200 | null |
811 | C | Vladik and Memorable Trip | Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now $n$ people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code $a_{i}$ ... | Let's precalc for each $x$ it's $fr_{x}$ and $ls_{x}$ - it's leftmost and rightmost occurrences in the array respectively. Now for each range $[l, r]$ we can check, if it can be a separate train carriage, just checking for each $a_{i}$ $(l \le i \le r)$, that $fr_{ai}$ and $ls_{ai}$ are also in this range. Now let'... | [
"dp",
"implementation"
] | 1,900 | null |
811 | D | Vladik and Favorite Game | \textbf{This is an interactive problem.}
Vladik has favorite game, in which he plays all his free time.
Game field could be represented as $n × m$ matrix which consists of cells of three types:
- «.» — normal cell, player can visit it.
- «F» — finish cell, player has to finish his way there to win. There is exactly ... | It's clear, that to reach finish without stepping into dangerous cells we have to know, whether our buttons are broken. Firstly, let's find any route to the finish using bfs / dfs. At the first moment of this route, when we have to go down, we would find out, if our button is broken, because we are still at the first r... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"interactive"
] | 2,100 | null |
811 | E | Vladik and Entertaining Flags | In his spare time Vladik estimates beauty of the flags.
Every flag could be represented as the matrix $n × m$ which consists of positive integers.
Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set t... | Let's use interval tree, maintaining in each vertex two arrays of $n$ numbers: left and right profile of the interval corresponding to the vertex. Each number in this arrays would be in range from $1$ to $2 * n$ denoting component, in which cell is. For merging such structures we would iterate on splice of two vertices... | [
"data structures",
"dsu",
"graphs"
] | 2,600 | null |
812 | A | Sagheer and Crossroads | Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has $3$ lanes getting into the intersection (one for each direction) and $3$ lanes getting out of the intersection, so we have $4$ parts in total. Each part has $4$ lights, one for e... | For pedestrian crossing $i$ ($1 \le i \le 4)$, lanes $l_{i}, s_{i}, r_{i}, s_{i + 2}, l_{i + 1}, r_{i - 1}$ are the only lanes that can cross it. So, we have to check that either $p_{i} = 0$ or all mentioned lanes are $0$. Complexity: $O(1)$ | [
"implementation"
] | 1,200 | "import java.io.PrintWriter;\nimport java.util.Scanner;\n\npublic class SagheerAndCrossroads_MainSolution {\n\n\tpublic static void main(String[] args) {\n\t\t\n\t\tScanner sc = new Scanner(System.in);\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\t\n\t\tint[][] part = new int[4][4];\n\t\tfor(int i = 0; i < 4... |
812 | B | Sagheer, the Hausmeister | Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.
The building consists of $n$ floors with stairs at the left and the right sid... | When Sagheer reaches a floor for the first time, he will be standing at either left or right stairs. If he is standing at the left stairs, then he will go to the rightmost room with lights on. If he is standing at the right stairs, then he will go to the leftmost room with lights on. Next, he will either take the left ... | [
"bitmasks",
"brute force",
"dp"
] | 1,600 | "import java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tScanner sc = new Scanner(System.in);\n\t\t\n\t\tint n = sc.nextInt(), m = sc.nextInt();\n\t\t\n\t\tint[] leftMost = new int[n], rightMost = new... |
812 | C | Sagheer and Nubian Market | On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains $n$ different items numbered from $1$ to $n$. The $i$-th item has base cost $a_{i}$ Egyptian pounds. If Sagheer buys $k$ items with indices $x_{1}, x_{2}, .... | If Sagheer can buy $k$ items, then he can also buy less than $k$ items because they will be within his budget. If he can't buy $k$ items, then can't also buy more than $k$ items because they will exceed his budget. So, we can apply binary search to find the best value for $k$. For each value $k$, we will compute the ne... | [
"binary search",
"sortings"
] | 1,500 | "/**\n * code generated by JHelper\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\n * @author gainullin.ildar\n */\n\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 ... |
812 | D | Sagheer and Kindergarten | Sagheer is working at a kindergarten. There are $n$ children and $m$ different toys. These children use well-defined protocols for playing with the toys:
- Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and o... | Let's go through scenario requests one by one. For request $a$ $b$, if toy $b$ is free, then child $a$ can take it. Otherwise, child $a$ will wait until the last child $c$ who requested toy $b$ finishes playing. Since, no child can wait for two toys at the same time, each child depends on at most one other child. So we... | [
"dfs and similar",
"graphs",
"implementation",
"trees"
] | 2,700 | "/**\n * code generated by JHelper\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\n * @author gainullin.ildar\n */\n\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 ... |
812 | E | Sagheer and Apple Tree | Sagheer is playing a game with his best friend Soliman. He brought a tree with $n$ nodes numbered from $1$ to $n$ and rooted at node $1$. The $i$-th node has $a_{i}$ apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all ... | In the standard nim game, we xor the values of all piles, and if the xor value is $0$, then the first player loses. Otherwise, he has a winning strategy. One variant of the nim game has an extra move that allows players to add positive number of stones to a single pile (given some conditions to make the game finite). T... | [
"games",
"trees"
] | 2,300 | "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class SagheerAppleTree_AC1 {\n\n\tstatic final int MAXA = 10000000;\n\tstatic ArrayList<Inte... |
813 | A | The Contest | Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!
This contest consists of $n$ problems, and Pasha solves $i$th problem in $a_{i}$ time units (his solutions are always correct). At any moment of time he can be thinking a... | Notice that we can keep solved tasks and then submit all at once. So the solution goes down to this: you should find the first moment of time $t$ that the site works at that moment and $t\geq\sum_{i=1}^{n}a_{i}$. Also it's convinient that the intervals are already sorted in increasing order. Let's sum up all elements o... | [
"implementation"
] | 1,100 | null |
813 | B | The Golden Age | Unlucky year in Berland is such a year that its number $n$ can be represented as $n = x^{a} + y^{b}$, where $a$ and $b$ are non-negative integer numbers.
For example, if $x = 2$ and $y = 3$ then the years 4 and 17 are unlucky ($4 = 2^{0} + 3^{1}$, $17 = 2^{3} + 3^{2} = 2^{4} + 3^{0}$) and year 18 isn't unlucky as ther... | Notice that $x^{a}$ for $x \ge 2$ has no more than 60 powers which give numbers no greater than $10^{18}$. So let's store all possible sums of all powers of $x$ and $y$. Now the answer to the query can be obtained in linear time by checking difference between neighbouring unlucky years in sorted order. Don't forget t... | [
"brute force",
"math"
] | 1,800 | null |
813 | C | The Tag Game | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of $n$ vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex $x$ ($x ≠ 1$). The moves are made in turns, Bob goes... | If you check some games then you will notice that the most optimal strategy for Bob is always like this: Climb up for some steps (possibly zero) Go to the lowest vertex from it Stay in this vertex till the end Thus let's precalc the depth (the distance from the root) of the lowest vertex of each subtree (using dfs), di... | [
"dfs and similar",
"graphs"
] | 1,700 | null |
813 | D | Two Melodies | Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!
Alice has a sheet with $n$ notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.
... | Let's solve this problem with dynamic programming. Let $dp[x][y]$ be the maximum answer if one melody finishes in note number $x$ and another melody - in note number $y$. $x$ and $y$ are $1$-indexed; if one of them is $0$, then the melody is empty. How shall we update $dp[x][y]$? First of all, we will update from previ... | [
"dp",
"flows"
] | 2,600 | null |
813 | E | Army Creation | As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.
In the game Vova can hire $n$ different warriors; $i$th warrior has the type $a_{i}$. Vova wants to create a balanced army hiring some subset of warriors. An army is called bala... | Every time we process a plan, let's count only the first $k$ warriors of some type. When will the warrior on position $i$ be counted? Of course, he has to be present in the plan, so $l \le i \le r$. But also he has to be among $k$ first warriors of his type in this plan. Let's denote a function $prev(x, y)$: $prev(... | [
"binary search",
"data structures"
] | 2,200 | null |
813 | F | Bipartite Checking | You are given an undirected graph consisting of $n$ vertices. Initially there are no edges in the graph. Also you are given $q$ queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of t... | If the edges were only added and not deleted, it would be a common problem that is solved with disjoint set union. All you need to do in that problem is implement a DSU which maintains not only the leader in the class of some vertex, but also the distance to this leader. Then, if we try to connect two vertices that hav... | [
"data structures",
"dsu",
"graphs"
] | 2,500 | null |
814 | A | An abandoned sentiment from past | A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.
To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t... | The statement laid emphasis on the constraint that the elements are pairwise distinct. How is this important? In fact, this implies that if the resulting sequence is increasing, then swapping any two of its elements will result in another sequence which is not increasing. And we're able to perform a swap on any resulti... | [
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 900 | #include <cstdio>
#include <algorithm>
static const int MAXN = 102;
int n, k;
int a[MAXN], b[MAXN];
int p[MAXN], r[MAXN];
inline bool check()
{
for (int i = 1; i < n; ++i) if (r[i] <= r[i - 1]) return true;
return false;
}
int main()
{
scanf("%d%d", &n, &k);
int last_zero = -1;
for (int i = 0; i ... |
814 | B | An express train to reveries | Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.
On that night, Sengoku constructed a permutation $p_{1}, p_{2}, ..., p_{n}$ of intege... | Permutating directly no longer works here. Let's try to dig something out from the constraints. Imagine that we take a permutation $p_{1... n}$, and change one of its elements to a different integer in $[1, n]$, resulting in the sequence $p'_{1... n}$. There are exactly $2$ positions $i, j$ ($i \neq j$) such that $p'... | [
"constructive algorithms"
] | 1,300 | #include <cstdio>
#include <utility>
static const int MAXN = 1e3 + 4;
int n;
int a[MAXN], b[MAXN];
std::pair<int, int> get_duplication(int *a)
{
static int occ[MAXN];
for (int i = 1; i <= n; ++i) occ[i] = -1;
for (int i = 0; i < n; ++i) {
if (occ[a[i]] != -1) return std::make_pair(occ[a[i]], i);
... |
814 | C | An impassioned circulation of affection | Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has $n$ pieces numbered from $1$ to $n$ f... | The first thing to notice is that we are only changing other colours to Koyomi's favourite one. Furthermore, we won't create disconnected segments of that colour, for that's no better than painting just around the longest among them. This leads us to a straightforward approach: when faced with a query $(m, c)$, we chec... | [
"brute force",
"dp",
"strings",
"two pointers"
] | 1,600 | #include <cstdio>
#include <algorithm>
static const int MAXN = 1502;
static const int ALPHABET = 26;
int n;
char s[MAXN];
int ans[ALPHABET][MAXN] = {{ 0 }};
int q, m_i;
char c_i;
int main()
{
scanf("%d", &n); getchar();
for (int i = 0; i < n; ++i) s[i] = getchar() — 'a';
for (char c = 0; c < ALPHAB... |
814 | D | An overnight dance in discotheque | The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?
The discotheque can be seen as an infinite $xy$-plane, in which there are a total of $n$ dancers. Once someone starts moving around, they will move only inside their own movement range, whi... | Circles' borders do not intersect, that is, each circle is "directly" contained in another circle, or is among the outermost ones. Can you see a tree/forest structure out of this? We create a node for each of the circles $C_{i}$, with weight equal to its area $ \pi r_{i}^{2}$. Its parent is the circle which "directly"... | [
"dfs and similar",
"dp",
"geometry",
"greedy",
"trees"
] | 2,000 | #include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
typedef long long int64;
static const int MAXN = 1004;
#ifndef M_PI
static const double M_PI = acos(-1.0);
#endif
int n;
int x[MAXN], y[MAXN], r[MAXN];
int par[MAXN];
std::vector<int> e[MAXN];
bool level[MAXN];
// Whether one of C[u] and C[v] ... |
814 | E | An unavoidable detour for home | Those unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be... | Let's make it intuitive: the graph looks like this. Formally, if we find out the BFS levels of the graph, it will look like a tree with extra edges among vertices of the same level, and indices of vertices in the same level form a consecutive interval. Therefore we can add vertices from number $1$ to number $n$ to the ... | [
"combinatorics",
"dp",
"graphs",
"shortest paths"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
#ifdef WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
#define pb push_back
#define mp make_pair
#define all(x) (x... |
815 | A | Karen and Game | On the way to school, Karen became fixated on the puzzle game on her phone!
The game is played as follows. In each level, you have a grid with $n$ rows and $m$ columns. Each cell originally contains the number $0$.
One move consists of choosing one row or column, and adding $1$ to all of the cells in that row or colu... | Fix the number of times we choose the first row. Say we choose the first row $k$ times. This actually uniquely determines the rest of the solution; consider the cells on the first row. There is no other way to increase these cells, except by choosing the columns they are on, and so we need to choose the $j$-th column $... | [
"brute force",
"greedy",
"implementation"
] | 1,700 | null |
815 | B | Karen and Test | Karen has just arrived at school, and she has a math test today!
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
There are $... | There are a couple of ways to solve this problem. The easiest way is to calculate the coefficients, or "contributions", of each number to the final sequence. In fact, the contribution of any number is determined by its position as well as the $n$. To do this, using brute force, we can compute the contribution of each e... | [
"brute force",
"combinatorics",
"constructive algorithms",
"math"
] | 2,200 | null |
815 | C | Karen and Supermarket | On the way home, Karen decided to stop by the supermarket to buy some groceries.
She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to $b$ dollars.
The supermarket sells $n$ goods. The $i$-th good can be bought for $c_{i}$ dollars. Of course, ... | Instead of asking for the maximum number of items we can buy with $b$ dollars, let's ask instead for the minimum cost to buy $j$ items for all $j$. Afterwards, we can simply brute force all $j$ to find the largest $j$ that still fits within her budget $b$. Note this problem is actually on a rooted tree, with root at no... | [
"brute force",
"dp",
"trees"
] | 2,400 | null |
815 | D | Karen and Cards | Karen just got home from the supermarket, and is getting ready to go to sleep.
After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection.
She recalled that she used to play with those cards as a child, and, although she is n... | Let's say we have one card, with $a_{1} = 4$, $b_{1} = 2$ and $c_{1} = 3$. For simplicity, we have $p = q = r = 5$. Consider which cards will beat this one. Let's fix the $c$ of our card, and see what happens at all various $c$: Note that a green cell at $(a, b)$ in grid $c$ represents that the card $(a, b, c)$ can bea... | [
"binary search",
"combinatorics",
"data structures",
"geometry"
] | 2,800 | null |
815 | E | Karen and Neighborhood | It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood.
The neighborhood consists of $n$ houses in a straight line, labelled $1$ to $n$ from left to right, all an equal distance apart.
Everyone in this neighborhood loves ... | Surprisingly, it is possible to solve this problem without knowledge of any sophisticated algorithms or data structures; this problem can be solved completely through observations, brutal case analysis and grunt work, which we will try to summarize here. The first and most obvious observation: the first person always g... | [
"binary search",
"constructive algorithms",
"implementation"
] | 2,900 | null |
816 | A | Karen and Morning | Karen is getting ready for a new school day!
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palin... | This is a rather straightforward implementation problem. The only observation here is that there are only $1440$ different possible times. It is enough to iterate through all of them until we encounter a palindromic time, and count the number of times we had to check before we reached a palindromic time. How do we iter... | [
"brute force",
"implementation"
] | 1,000 | null |
816 | B | Karen and Coffee | To stay woke and attentive during classes, Karen needs some coffee!
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows $n$ coffee ... | There are two separate tasks here: Efficiently generate an array $c$ where $c_{i}$ is the number of recipes that recommend temperature $i$. Efficiently answer queries "how many numbers $c_{a}, c_{a + 1}, c_{a + 2}, ..., c_{b}$" are at least $k$?" where $k$ is fixed across all queries. There are some solutions to this t... | [
"binary search",
"data structures",
"implementation"
] | 1,400 | null |
817 | A | Treasure Hunt | Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values $x$ and $y$ written on it. These values define four moves which can be perfor... | Firstly, let's approach this problem as if the steps were $(a,b)\to(a\pm x,0)$ and $(a,b)\rightarrow(0,b\pm y)$. Then the answer is "YES" if $|x_{1} - x_{2}|$ $mod$ $x = 0$ and $|y_{1} - y_{2}|$ $mod$ $y = 0$. It's easy to see that if the answer to this problem is "NO" then the answer to the original one is also "NO". ... | [
"implementation",
"math",
"number theory"
] | 1,200 | null |
817 | B | Makes And The Product | After returning from the army Makes received a gift — an array $a$ consisting of $n$ positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices $(i, j, k)$ ($i < j < k$), such that $a_{i}·a_{j}·a_{k}$ is minimum possi... | Minimal product is obtained by multiplying three smallest elements of the array. Let's iterate over the middle element of these three and calc sum of all options. Firstly let's precalc two arrays of pairs - $mnl$ and $mnr$. $mnl[x]$ is minimum and number of its occurrences on the prefix of array $a$ up to index $x$ inc... | [
"combinatorics",
"implementation",
"math",
"sortings"
] | 1,500 | null |
817 | C | Really Big Numbers | Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number $x$ is really big if the difference between $x$ and the sum of its digits (in decimal representation) is not less than $s$. To prove that these numbers may have different... | Let's prove that if $x$ is really big, then $x + 1$ is really big too. Since the sum of digits of $x + 1$ (let's call it $sumd(x + 1)$) is not greater than $sumd(x) + 1$, then $x + 1 - sumd(x + 1) \ge x - sumd(x)$, and if $x - sumd(x) \ge s$, then $x + 1 - sumd(x + 1) \ge s$. So if $x$ is really big, then $x + 1$... | [
"binary search",
"brute force",
"dp",
"math"
] | 1,600 | null |
817 | D | Imbalanced Array | You are given an array $a$ consisting of $n$ elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of ... | First of all, we will calculate the sum of maximum and minimum values on all segments separatedly. Then the answer is the difference between the sum of maximum values and minimum values. How can we calculate the sum of minimum values, for example? For each element we will try to find the number of segments where it is ... | [
"data structures",
"divide and conquer",
"dsu",
"sortings"
] | 1,900 | null |
817 | E | Choosing The Commander | As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.
Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.
Ea... | Let's use binary trie to store all personalities of warriors (that is, just use the trie data structure on binary representations of all $p_{i}$). For each subtree of this trie you have to maintain the number of $p_{i}$'s currently present in this subtree - when inserting a value of $p_{i}$, we increase the sizes of su... | [
"bitmasks",
"data structures",
"trees"
] | 2,000 | null |
817 | F | MEX Queries | You are given a set of integer numbers, initially it is empty. You should perform $n$ queries.
There are three different types of queries:
- 1 $l$ $r$ — Add all missing numbers from the interval $[l, r]$
- 2 $l$ $r$ — Remove all present numbers from the interval $[l, r]$
- 3 $l$ $r$ — Invert the interval $[l, r]$ — a... | There are many ways to solve this problem, you can use cartesian tree, segment tree, sqrt decomposition, maybe something else. I personally see the solution with the segment tree the easiest one so let me describe it. Firstly, let's notice that the queries are offline. So we can compress the numbers by taking $L$ and $... | [
"binary search",
"data structures",
"trees"
] | 2,300 | null |
818 | A | Diplomas and Certificates | There are $n$ students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ... | Let $a$ be the number of students with diplomas and $b$ - students with certificates. $b$ is always $a \cdot k$. So the total number of winners is $a + a \cdot k = a \cdot (k + 1)$. It should not exceed $\textstyle{\left[{\frac{n}{2}}\right]}$, so the maximum value for $a$ will be hit in $(n$ $div$ $2)$ $div$ $(k + 1)$... | [
"implementation",
"math"
] | 800 | null |
818 | B | Permutation Game | $n$ children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation $a_{1}, a_{2}, ..., a_{n}$ of length $n$. It is an integer sequence such that each integer from $1$ to $n$ appears exactly once in it.
The game consists of $m$ steps. On each step the current leader with ... | Let's show by construction that there can be no ambiguity in values of $a_{j}$ of the children who were leaders at least once (except for probably the last leader). If $l_{i + 1} > l_{i}$ then on this step the value of $a_{l[i]}$ taken was exactly $l_{i + 1} - l_{i}$. Otherwise $l_{i} + a_{l[i]}$ went over $n$ and in c... | [
"implementation"
] | 1,600 | null |
818 | C | Sofa Thief | Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?
Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs ... | Coordinates don't exceed $10^{5}$ so it's possible to use sweep line method to solve the problem. Let's calculate $cnt$ value separately for each side. I will show the algorithm for left side and all the others will be done similarly. Let $cnt_left[i]$ be the number of sofas which has smaller of their $x$ coordinates l... | [
"brute force",
"implementation"
] | 2,000 | null |
818 | D | Multicolored Cars | Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.
The game rules are like this. Firstly Alice chooses some color $A$, then Bob chooses some color $B$ ($A ≠ B$). After each car th... | Let's maintain the current availability of colors and the amounts of cars of each color. Firstly color $A$ is never available. When car of some color $C$ ($C \neq A$) goes, you check if the number of cars of color $C$ past before this one isn't smaller than the number of cars of color $A$. Only after that increment t... | [
"data structures",
"implementation"
] | 1,700 | null |
818 | E | Card Game Again | Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of $n$ cards and a magic number $k$. The order of the cards in the deck is fixed. Each card has a number written on it; number $a_{i}$ is written on the $i$-th card in the deck.
After r... | Let's use two pointers. Firstly you need to learn to factorize any number in no more than $O(\log n)$. We don't actually need any of their prime divisors except for those that are presented in $k$. So let's factorize $k$ in $O({\sqrt{10^{9}}})$. After that check for the maximum power of each useful prime will work in $... | [
"binary search",
"data structures",
"number theory",
"two pointers"
] | 1,900 | null |
818 | F | Level Generation | Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly $n_{i}$ vertices in the graph representing level $i$, and the edges have to be bidirectional.... | The best way to build a graph is to make a $2$-edge-connected component with $k$ vertices and connect each of the remaining $n - k$ vertices to it with a single edge. Then we will have $n - k$ bridges outside the component and $m i n({\frac{k\cdot(k-1)}{2}},n-k)$ edges in the component. So the answer for some fixed $k$... | [
"binary search",
"math",
"ternary search"
] | 2,100 | null |
818 | G | Four Melodies | Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult!
Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks.
This ti... | Let's build a directed graph where vertices represent notes and a directed edge comes from vertex $i$ to vertex $j$ iff $i < j$ and $a_{i}$ and $a_{j}$ can be consecutive notes in a melody. Now we have to find four longest vertex-disjoint paths in this graph. This problem can be solved with mincost $k$-flow algorithms.... | [
"flows",
"graphs"
] | 2,600 | null |
819 | A | Mister B and Boring Game | \textbf{Unfortunately, a mistake was found in the proof of the author's solution to this problem. Currently, we don't know the absolutely correct solution. However, you can solve this task, but if your solution passes all the tests, it is not guaranteed to be correct. If your solution has passed all the tests, and you ... | Tutorial is not available | [
"games",
"greedy"
] | 2,200 | null |
819 | B | Mister B and PR Shifts | Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation $p$ of length $n$ or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation... | Let's see, how $p_{k}$ $(1 \le k \le n)$ affects different shifts. Let's denote $d_{i}$ is deviation of the $i - th$ shift. At first all $d_{i} = 0$. Then $p_{k}$ affects it in following way: $d_{0} + = |p_{k} - k|$, $d_{1} + = |p_{k} - (k + 1)|$, $...$ $d_{n - k} + = |p_{k} - n|$, $d_{n - k + 1} + = |p_{k} - 1|$, ... | [
"data structures",
"implementation",
"math"
] | 1,900 | #define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
typedef long long li;
const int N = 1000 * 1000 + 555;
int n, p[N];
inline bool read() {
if(!(cin >> n))
return false;
forn(i, n)
assert(scanf("%d", &p[i]) == 1);
return true;
}
li sum[N], df[N], res[N];
inline void... |
819 | C | Mister B and Beacons on Field | Mister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates $(0, 0)$. After that they sent three beacons to the field, but something went wrong. One beacon was c... | There 2 stages in this task: moving of first beacon and moving of second. But at first we need factorization of $n$ and $s$. Since $n$ and $s$ are product of integers $ \le 10^{6}$, it can be done in $O(log(n) + log(s))$ time by "Sieve of Eratosthenes". Start from second stage, when second beacon is moving: Position o... | [
"number theory"
] | 2,900 | #define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
#define all(a) (a).begin(), (a).end()
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define mp make_pair
#define pb push_back
typedef long long li;
typedef pair<int, int> pt;
typedef pair<li, li> ptl;
const int INF =... |
819 | D | Mister B and Astronomers | After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly $T$ seconds. The problem is that the star is yet to be discovered by scientists.
There are $n$ astronomers numerate... | Let's construct slow but clear solution and then, speed it up. Let's denote $s=\sum_{i=1}^{i=n}a_{i}$. We can see, that, at first, all operation with time are modulo $T$ and the $i - th$ astronomer checks moments $st_{i}$, $(st_{i} + s)%T$, $(st_{i} + 2s)%T$ ..., where $s t_{i}=\sum_{j=2}^{j=i}a_{i}$. More over, every ... | [
"number theory"
] | 2,900 | #define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
#define all(a) (a).begin(), (a).end()
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define mp make_pair
#define pb push_back
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pai... |
819 | E | Mister B and Flight to the Moon | In order to fly to the Moon Mister B just needs to solve the following problem.
There is a complete indirected graph with $n$ vertices. You need to cover it with several simple cycles of length $3$ and $4$ so that each edge is in exactly $2$ cycles.
We are sure that Mister B will solve the problem soon and will fly t... | There are different constructive solutions in this problem. Here is one of them. Consider odd and even $n$ separately. Let $n$ be even. Let's build for each even $n \ge 4$ a solution such that there are triangles 1-2-x, 3-4-y, 5-6-z and so on. For $n = 4$ it's easy to construct such a solution. Then let's add two ver... | [
"constructive algorithms",
"graphs"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
#ifdef WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
#define pb push_back
#define mp make_pair
#define all(x) (x... |
820 | A | Mister B and Book Reading | Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had $c$ pages.
At first day Mister B read $v_{0}$ pages, but after that he started to speed up. Every day, starting from the second, he read $a$ pages more than on the previous day (at first day he read $v_{0}$ page... | All that needed - is to accurately simulate process. Create variable, which will contain count of read pages, subtract $l$, add $v_{0}$, check, what you still have unread pages, make $v_{0} = min(v_{1}, v_{0} + a)$ and again. Complexity is $O(c)$. | [
"implementation"
] | 900 | #define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
int c, l, v0, v1, a;
inline bool read() {
if(!(cin >> c >> v0 >> v1 >> a >> l))
return false;
return true;
}
inline void solve() {
int pos = v0;
int t = 1;
int add = v0;
while(pos < c) {
add = min(v1, add + a)... |
820 | B | Mister B and Angle in Polygon | On one quiet day all of sudden Mister B decided to draw angle $a$ on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is \textbf{regular convex $n$-gon} (regular convex polygon with $n$ sides).
That's why Mister B decided to use this polygon. Now Mist... | Since polygon is regular, all vertices of a regular polygon lie on a common circle (the circumscribed circle), so all possible angles are inscribed angles. And all inscribed angles subtending the same arc have same measure. More over, minor and major arcs between vertices $v_{i}$ and $v_{k}$ equals to minor and major a... | [
"constructive algorithms",
"geometry",
"math"
] | 1,300 | int n, a;
inline bool read() {
if(!(cin >> n >> a))
return false;
return true;
}
inline void solve() {
int base = n * a / 180;
base = max(1, min(n - 2, base));
int bk = base;
for(int ck = max(1, base - 2); ck <= min(n - 2, base + 2); ck++) {
if(abs(180 * ck - n * a) < abs(180 * bk - n * a))
bk = ck;
... |
821 | A | Okabe and Future Gadget Laboratory | Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an $n$ by $n$ square grid of integers. A good lab is defined as a lab in which every number not equal to $1$ can be expressed as the sum of a number in the same row and a number in the same column... | We can simulate exactly what's described in the statement: loop over all cells not equal to 1 and check if it doesn't break the city property. To check if a cell breaks the property, just loop over an element in the same row, and an element in the same column, and see if they can add to give the cell's number. The comp... | [
"implementation"
] | 800 | #include <queue>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cst... |
821 | B | Okabe and Banana Trees | Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point $(x, y)$ in the 2D plane such that $x$ and $y$ are integers and $0 ≤ x, y$. There is a tree in such a point, and it has $x + y$ bananas. There are no trees nor bananas in o... | The critical observation to make is that the optimal rectangle should always have a lower-left vertex at the origin. This is due to the fact that the line has positive y-intercept and negative slope: any rectangle which doesn't have a vertex at the origin could easily be extended to have a vertex at the origin and even... | [
"brute force",
"math"
] | 1,300 |
#include <queue>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.