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
747
B
Mammoth's Genome Decoding
The process of mammoth's genome decoding in Berland comes to its end! One of the few remaining tasks is to restore unrecognized nucleotides in a found chain $s$. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, $s...
Let $n$ is the length of the given string. The number of each letter in the resulting string must be equals to $n / 4$. If $n mod 4$ does not equal to 0 - there is no solution. If some letter meets in the given string more than $n / 4$ times - there is no solution. After that we always can build the answer. We need to ...
[ "implementation", "strings" ]
900
null
747
C
Servers
There are $n$ servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from $1$ to $n$. It is known that during the day $q$ tasks will come, the $i$-th of them is characterized with three integers: $t_{i}$ — the moment in seconds in which the task will come, $k_{i}$ — the number o...
The given constraints allow to simply modulate described process. Let's use array $server$, where $server[i]$ is equals to the time when $i$-th server will become free. Than for each query let's find the number of servers which free in moment when this query came. We can do it in $O(n)$, where $n$ is the number of serv...
[ "implementation" ]
1,300
null
747
D
Winter Is Coming
The winter in Berland lasts $n$ days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than $k$ days at any average air temperature. After $k$ days of using it (regardless of the temperature of these days) the set o...
At first let's process the case when there is no solution - when the number of days with negative temperature $cnt$ more than $k$. Now we need to subtract from $k$ the number of days $cnt$. If we will use winter rubber only in days with negative temperature we will get the maximum value of answer: it is the number of s...
[ "dp", "greedy", "sortings" ]
1,800
null
747
E
Comments
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment ex...
Let $pos$ is a global variable equals to the current position in the given string. To solve we can use recursive function $rec(lvl, cnt)$, means that in the current moment we are on the level of replies $lvl$ and there is $cnt$ comments on this level. Than we need iterate by $i$ from 1 to $cnt$ and on each iteration we...
[ "dfs and similar", "expression parsing", "implementation", "strings" ]
1,700
null
747
F
Igor and Interesting Numbers
Igor likes hexadecimal notation and considers \textbf{positive} integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than $t$ times. For example, if $t = 3$, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not inter...
Let's use dynamic programming and $dp[i][j]$ - the number of valid numbers with length $i$ and maximal digit in this numbers is $j$. Let iterate by $n_{j}$ from $j + 1$ and brute $len$ (how many times we will take digit $n_{j}$). Than new length $n_{i} - i + len$, number will ends to $n_{j}$ repeated $len$ times. Then ...
[ "brute force", "combinatorics", "dp", "math" ]
2,500
null
748
A
Santa Claus and a Place in a Class
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are $n$ lanes of $m$ desks each, and there are two working places at each of the desks. The lanes are numbered from $1$ to $n$ from the left to the right, the desks in a lane ...
It can be easily seen that the side on which Santa should sit depends only on the parity of $k$, while the number of desk and the number of lane depend only on a value $p=\lfloor{\frac{k-1}{2}}\rfloor$. We can see that in such numeration the number of lane equals $\left|{\frac{p}{m}}\right|+1$, while the number of desk...
[ "implementation", "math" ]
800
null
748
B
Santa Claus and Keyboard Check
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. I...
Denote the two strings from the input by $s$ and $t$. It's enough to find all pairs of distinct $s_{i}$ and $t_{i}$ and then do the following: Ensure that each symbol is in no more than one different pair, Ensure that if symbol $c$ is in a pair with another symbol $d$, then each occurrence of $c$ in $s$ on the $i$-th p...
[ "implementation", "strings" ]
1,500
null
748
C
Santa Claus and Robot
Santa Claus has Robot which lives on the infinite grid and can move \textbf{along its lines}. He can also, having a sequence of $m$ points $p_{1}, p_{2}, ..., p_{m}$ with integer coordinates, do the following: denote its initial location by $p_{0}$. First, the robot will move from $p_{0}$ to $p_{1}$ along one of the sh...
Solution #1: denote by $dp_{i}$ the least possible number of points if the robot passed only $i$ unit segments, and we assume that $dp_{0} = 0$. Thus, the answer to the problem is $dp_{n}$. It's clear that $dp_{k + 1} \ge dp_{k}$ for every $k$, so for every $i \le n$ one can obtain that $dp_{i} = dp_{j} + 1$, where...
[ "constructive algorithms", "math" ]
1,400
null
748
D
Santa Claus and a Palindrome
Santa Claus likes palindromes very much. There was his birthday recently. $k$ of his friends came to him to congratulate him, and each of them presented to him a string $s_{i}$ having the same length $n$. We denote the beauty of the $i$-th string by $a_{i}$. It can happen that $a_{i}$ is negative — that means that Sant...
Imagine a palindrome split into substrings of equal size (say, $n$). Here is how it may look like: ABC DEF XYX FED CBA We may notice a regular structure: each block, except the middle one, has its pair, which is the same string, but reversed. Here, the first block (ABC) is paired with the last (CBA), the second - with ...
[ "constructive algorithms", "data structures", "greedy" ]
2,100
null
748
E
Santa Claus and Tangerines
Santa Claus has $n$ tangerines, and the $i$-th of them consists of exactly $a_{i}$ slices. Santa Claus came to a school which has $k$ pupils. Santa decided to treat them with tangerines. However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into...
It is obvious that if the total number of slices is less than $k$, then the answer is $- 1$. Otherwise it's at least $1$. Let's find the answer in this case. Let's divide tangerines and parts in halves one by one in order to find the best answer. It's easy to see that it makes no sense to divide a part of size $x$ if t...
[ "binary search", "data structures", "greedy", "two pointers" ]
2,100
null
748
F
Santa Clauses and a Soccer Championship
The country Treeland consists of $n$ cities connected with $n - 1$ bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly $2k$ teams from $2k$ differ...
Firstly, let's prove that there exists a vertex $v$ in the tree such that if we make it a root, all subtrees of its neighbours (which does not contain $v$) contain no more than $k$ vertices in which some games are played (we call these vertices chosen further). We root the tree in some vertex $root$ and denote $f(u)$ t...
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,300
null
749
A
Bachgold Problem
Bachgold problem is very easy to formulate. Given a positive integer $n$ represent it as a sum of \textbf{maximum possible} number of prime numbers. One can prove that such representation exists for any integer greater than $1$. Recall that integer $k$ is called \underline{prime} if it is greater than $1$ and has exac...
We need represent integer number $N$ ($1 < N$) as a sum of maximum possible number of prime numbers, they don't have to be different. If $N$ is even number, we can represent it as sum of only $2$ - minimal prime number. It is minimal prime number, so number of primes in sum is maximal in this case. If $N$ is odd number...
[ "greedy", "implementation", "math", "number theory" ]
800
null
749
B
Parallelogram is Back
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis...
Denote the input points as $A$, $B$, $C$, and the point we need to find as $D$. Consider the case when the segments $AD$ and $BC$ are the diagonals of parallelogram. Vector AD is equal to the sum of two vectors AB + BD = AC + CD. As in the parallelogram the opposite sides are equal and parallel, BD = AC, AB = CD, and w...
[ "brute force", "constructive algorithms", "geometry" ]
1,200
null
749
C
Voting
There are $n$ employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote. Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions...
We will emulate the process with two queues. Let's store in the first queue the moments of time when D-people will vote, and in the second queue - the moments of time of R-people. For every man where will be only one element in the queue. Now compare the first elements in the queues. The man whose moment of time is les...
[ "greedy", "implementation", "two pointers" ]
1,500
null
749
D
Leaving Auction
There are $n$ people taking part in auction today. The rules of auction are classical. There were $n$ bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all. Each bid is define by two integers $(a_{i}, b_{i})$, where $a_{i}$ is the index of the perso...
For every man at the auction we will save two values: his maximum bid and the list of all his bids. Then save all men in the set sorted by the maximal bid. Now, when the query comes, we will remove from the set all men who left the auction, then answer the query, and then add the men back. The total number of deletions...
[ "binary search", "data structures" ]
2,000
null
749
E
Inversions After Shuffle
You are given a permutation of integers from $1$ to $n$. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: - Pick a random segment (continuous subsequence) from $l$ to $r$. All $\textstyle{\frac{n(n+1)}{2}}$ segments are equiprobable. - Let $k...
Lets calculate all available segments count - $\frac{l e n s(l e n+1)}{2}$. It will be a denominator of answer fraction. Also, necessary to understand, that expected value of inversion count in shuffled permutation with length len equal $\frac{l e n s(l e n-1)}{4}$ (It can be prooved by fact, that for each permutation ...
[ "data structures", "probabilities" ]
2,400
null
750
A
New Year and Hurry
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be $n$ problems, sorted by difficulty, i.e. problem $1$ is the easiest and problem $n$ is the hardest. Limak knows it will take him $5·i$ minutes to solve ...
Do you see what is produced by the following piece of code? We iterate over problems (a variable i denotes the index of problem) and in a variable total we store the total time needed to solve them. The code above would print numbers $5, 15, 30, 50, ...$ - the $i$-th of these numbers is the number of minutes the hero w...
[ "binary search", "brute force", "implementation", "math" ]
800
null
750
B
New Year and North Pole
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly $40 000$ kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly $20 000$ kilometers. Limak, a polar bear, lives on t...
Our goal is to simulate Limak's journey and to check if he doesn't make any forbidden moves. To track his position, it's enough to store one variable denoting his current distance from the North Pole. To solve this problem, you should implement checking three conditions given in the statement. Updating dist_from_north ...
[ "geometry", "implementation" ]
1,300
null
750
C
New Year and Rating
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating $1900$ or higher. Those with rating $1899$ or lower belong to the second division. In every contest, according to one's performance, his or her ratin...
We don't know the initial or final rating but we can use the given rating changes to draw a plot of function representing Limak's rating. For each contest we also know in which division Limak was. Red and blue points denote contests in div1 and div2. Note that we still don't know exact rating at any moment. Let's say t...
[ "binary search", "greedy", "math" ]
1,600
null
750
D
New Year and Fireworks
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more par...
A trivial $O(2^{n})$ solution is to simulate the whole process and mark visited cells. Thanks to a low constraint for $t_{i}$, a backtrack with memoization has much better complexity. Let's understand the reason. Parts of the firework move by $t_{i}$ in the $i$-th level of recursion so they can't reach cells further th...
[ "brute force", "data structures", "dfs and similar", "dp", "implementation" ]
1,900
null
750
E
New Year and Old Subsequence
A string $t$ is called nice if a string "2017" occurs in $t$ as a \textbf{subsequence} but a string "2016" doesn't occur in $t$ as a \textbf{subsequence}. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice. The ugliness of a string is the minimum possible num...
It's often helpful to think about an algorithm to solve some easier problem. To check if a string has a subsequence "2017", we can find the find the first '2', then to the right from that place find the first '0', then first '1', then first '7'. If in some of these $4$ steps we can't find the needed digit on the right,...
[ "data structures", "divide and conquer", "dp", "matrices" ]
2,600
null
750
F
New Year and Finding Roots
\textbf{This is an interactive problem. In the interaction section below you will find the information about flushing the output.} The New Year tree of height $h$ is a perfect binary tree with vertices numbered $1$ through $2^{h} - 1$ in some order. In this problem we assume that $h$ is at least $2$. The drawing below...
The goal is to find a vertex with exactly two neighbours - this will be the root. Also, let's notice that for a leaf we would get a list of exactly one neighbour. So we will know if we asked about the root or a leaf. The solution is deterministic. Any randomized solution would likely fail - there are 500 test cases per...
[ "constructive algorithms", "implementation", "interactive", "trees" ]
2,800
null
750
G
New Year and Binary Tree Paths
The New Year tree is an infinite perfect binary tree rooted in the node $1$. Each node $v$ has two children: nodes indexed $(2·v)$ and $(2·v + 1)$. Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nod...
Iterate over $L$ and $R$ - the length of sides of a path. A "side" is a part from LCA (the highest point of a path) to one of the ends of a path. For fixed LCA and length of sides, let the "minimal" path denote a path with the minimum possible sum of values. In each of the sides, this path goes to the left child all th...
[ "bitmasks", "brute force", "combinatorics", "dp" ]
3,200
null
750
H
New Year and Snowy Grid
\textbf{Pay attention to the output section below, where you will see the information about flushing the output.} Bearland is a grid with $h$ rows and $w$ columns. Rows are numbered $1$ through $h$ from top to bottom. Columns are numbered $1$ through $w$ from left to right. Every cell is either allowed (denoted by '.'...
Let's solve an easier problem first. For every query, we just want to say if Limak can get from one corner to the other. He can't do that if and only if blocked cells connect the top-right side with the bottom-left side - this is called a dual problem. On the drawing above, the top-right side and bottom-left side are m...
[ "dfs and similar", "dsu", "graphs", "interactive" ]
3,500
#include <bits/stdc++.h> using namespace std; #define SIDE1 cc[3][0] #define SIDE2 cc[0][3] const int N = 1005; int h, w; char sl[N]; bool allow[N][N]; int cc_cnt, cc[N][N]; // which connected component set<pair<int,int>> edges; // pairs of almost connected CC's // find & union namespace FU { int group[N*N]; vector...
754
A
Lesha and array splitting
One spring day on his way to university Lesha found an array $A$. Lesha likes to split arrays into several parts. This time Lesha decided to split the array $A$ into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays...
Only in one case there is no answer. When array consists entirely of zeros. Because all subarrays of such array has zero sum. Otherwise there are two cases: Array sum is not zero. In this case we can divide array into one subarray $A[1... n]$. Array sum is zero. But we know that array has non-zero elements. Then there ...
[ "constructive algorithms", "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> a(n); long long sum = 0; for (int & x : a) { scanf("%d", &x); sum += x; } if (sum != 0) { puts("YES"); puts("1"); printf("%d %d\n", 1, n); exit(0); } sum = 0; for (int i = 0; i < n; i++) { sum += a[i...
754
B
Ilya and tic-tac-toe game
Ilya is an experienced player in tic-tac-toe on the $4 × 4$ field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by maki...
This problem can be solved by simple bruteforce. Let's brute cell in which Ilya put X. Let's put X in this cell. Next step is to check if there is three consecutive Xs on field. This is done as follows. Let's brute cell which is first of three consecutive Xs. Next let's brute direction of three consecutive Xs. If we kn...
[ "brute force", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { char str[4][4 + 1]; // cells are '.', 'o', 'x' for (int i = 0; i < 4; i++) { cin >> str[i]; } auto check = [&]() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; ...
754
C
Vladik and chat
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download $t$ chats. Vladik coded a script which should have downloaded the chats, however, something went wrong...
Let's number users from $1$ to $n$. Let's us know for every message users mentioned in message. Let's define arrays $A$ and $S$. $A_{i} =$ index of sender of $i$-th message, if sender of $i$-th message is unknown, then $A_{i} = - 1$. $S_{i} =$ set of mentioned users in $i$-th message. Now for every message where sender...
[ "brute force", "constructive algorithms", "dp", "implementation", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() void solve() { int n; cin >> n; vector<string> names(n); for (string& name : names) { cin >> name; } sort(all(names)); auto getIdx = [&](const string& s) { int pos = lower_bound(all(names), s) - names.begin(); if (pos =...
754
D
Fedor and coupons
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has $n$ discount coupons, the $i$-th of them can be used with products wi...
Formalized version of this problem: Given $n$ segments, we need to choose $k$ of them, such that intersection of chosen segments has maximum possible length. Let's use binary search to find maximum possible length of intersection. Let's this length equals to $len$. If exist $k$ segments, which have length of intersecti...
[ "binary search", "data structures", "greedy", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; int nextInt() { int x = 0, p = 1; char c; do { c = getchar(); } while (c <= 32); if (c == '-') { p = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * p; } #define all(x) (x).be...
754
E
Dasha and cyclic table
Dasha is fond of challenging puzzles: Rubik's Cube $3 × 3 × 3$, $4 × 4 × 4$, $5 × 5 × 5$ and so on. This time she has a cyclic table of size $n × m$, and each cell of the table contains a lowercase English letter. Each cell has coordinates $(i, j)$ ($0 ≤ i < n$, $0 ≤ j < m$). The table is cyclic means that to the right...
Let's consider simple bruteforce. Let's $T$ - cyclic table, $P$ - pattern, $R$ - result. Then simple bruteforces looks like that: Let's rewrite bruteforce: Let's define $G$. $G_{c, i, j} = true$, if $T_{i, j} = c$, otherwise $false$. It's easy to understand, that (T[i][j] == c) is equivalent $G[c][i][j]$. Then line of ...
[ "bitmasks", "brute force", "fft", "strings", "trees" ]
2,600
import java.io.*; import java.util.*; public class Main { static class InputReader { BufferedReader bufferedReader; StringTokenizer stringTokenizer; InputReader(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 32768); ...
755
A
PolandBall and Hypothesis
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer $n$ that for each positive integer $m$ number $n·m + 1$ is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorre...
There are many ways to solve the problem. There can't be many primes in a row, so we can just bruteforce until we find a composite number. Note that it is not neccesarily true for huge numbers. More general, there is a prime arithmetic progression of length $k$ for any $k$, but there is no infinitely-long sequence! Ano...
[ "brute force", "graphs", "math", "number theory" ]
800
null
755
B
PolandBall and Game
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
Let PolandBall know $n$ words, EnemyBall $m$ words. Let $k$ be set of words which both Balls know. It's easy to see that Balls should process words from $k$ first. If $k$ contains even number of words, PolandBall will have an advantage of one additional word. Then, if $n \le m$, PolandBall loses. Otherwise - he wins.
[ "binary search", "data structures", "games", "greedy", "sortings", "strings" ]
1,100
null
755
C
PolandBall and Forest
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with $k$ vertices and $k - 1$ edges, where $k$ is some integer. Note that one vertex \textbf{is} a valid tree. There is exactly one relative living in each vertex of each tree, they have unique ids fro...
Property: Look at one tree and take its diameter. Name its endpoints A and B. For each vertex u from this component, $p[u] = A$ or $p[u] = B$. It's easy to prove that. We can just count number of different elements in P and divide it by two. Special case : Isolated vertices (those with $p[i] = i$).
[ "dfs and similar", "dsu", "graphs", "interactive", "trees" ]
1,300
null
755
D
PolandBall and Polygon
PolandBall has such a convex polygon with $n$ veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number $k$ such that $gcd(n, k) = 1$. Vertices of the polygon are numbered from $1$ to $n$ in a clockwise way. PolandBall repeats th...
First, we can set $k = min(k, n - k)$. This changes nothing right now, but we'll use it later. Our diagonals correspond to intervals [$L_{i}$, $R_{i}$], each intersection of two diagonals: A) adds one to result B) is equivalent to intersection of their intervals We will use segment or fenwick tree to store beginnings a...
[ "data structures" ]
2,000
null
755
E
PolandBall and White-Red graph
PolandBall has an undirected simple graph consisting of $n$ vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: whi...
We should definitely start with estimating how big can be $k$. It turns out that we can't obtain diameter greater than $3$. You can prove this fact by yourself or try here: Proof. We can also easily show that answer is $- 1$ for $k = 1$. So, the problem is to solve K = 2 and K = 3. Constructing K = 3: Let's start with ...
[ "constructive algorithms", "graphs", "shortest paths" ]
2,400
null
755
F
PolandBall and Gifts
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are $n$ Balls overall. Each Ball has someone for whom he should bring a present according to some permutation $p$, $p_{i} ≠ i$ for all $i$. Unfortunately, Balls are quite clumsy. We know earlier that exactly $k$ of them will forget ...
Every permutation can be represented as a set of cycles. Maximum: This is the easier case. Greedy works, some careful implementation and it's ok. Answer is usually $2k$ in this case, but not always. Minimum: If there are such cycles $c_{1}$, $c_{2}$, ... $c_{m}$ of length $a_{1}$, $a_{2}$, ..., $a_{n}$ that $a_{1} + a_...
[ "bitmasks", "dp", "greedy" ]
2,600
null
755
G
PolandBall and Many Other Balls
PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly $n$ Balls. Balls are proud of their home land — and they want to prove that it's strong. The Balls decided to start with selecting exactly $m$ groups of Balls, each consisting either of single Ball or two neighboring Balls. Each B...
The modulo instantly suggests an FFT-like approach. First, let's solve this problem using simple dynamic programming. DP[N][K] = DP[N-1][K] + DP[N-1][K-1] + DP[N-2][K-1], because we can either do nothing or add one interval of length 1 or 2. As for start, this works fine. We can calculate DP[1], DP[2], DP[3] and DP[4] ...
[ "combinatorics", "divide and conquer", "dp", "fft", "math", "number theory" ]
3,200
null
756
A
Pavel and barbecue
Pavel cooks barbecue. There are $n$ skewers, they lay on a brazier in a row, each on one of $n$ positions. Pavel wants each skewer to be cooked some time in every of $n$ positions in two directions: in the one it was directed originally and in the reversed direction. Pavel has a plan: a permutation $p$ and a sequence ...
At first, let's deal with the permutation. We can see that $p$ should have exactly one cycle to suit Pavel. The minimum number of changes is $0$ if there is only one cycle, and the number of cycles if there is more than one cycle. What should we do with $b$? We can see that the skewers visit a particular position $x$ i...
[ "constructive algorithms", "dfs and similar" ]
1,700
null
756
B
Travel Card
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: - a ticket ...
Hint: the problem looks difficult because tickets can change, however, it's can be solved with simple dynamic programming. You are asked the difference between neighboring dp's subtasks. More detailed editorial will be added soon.
[ "binary search", "dp" ]
1,600
null
756
C
Nikita and stack
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer $x$ on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made $m$ op...
Hint 1: look at the operations in the reverse order. Let's count the balance for each prefix, i.e. the difference between the number of push(x) operations and the number of pop() operations. Hint 2: Now we have to find the first operation that makes balance positive. This can be done using segment tree. Solution: Let's...
[ "data structures" ]
2,200
null
756
D
Bacterial Melee
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z". The testtube is divided into $n$ consecutive ...
Hint: find a condition when a string is reachable from another string in terms of subsequences, then apply DP for counting suitable subsequences. Solution: How to determine if a string can be obtained from another string after a number of operations? It helps to consider (maximal) blocks of adjacent characters. Let us ...
[ "brute force", "combinatorics", "dp", "string suffix structures" ]
2,400
null
756
E
Byteland coins
There are $n$ types of coins in Byteland. Conveniently, the denomination of the coin type $k$ divides the denomination of the coin type $k + 1$, the denomination of the coin type $1$ equals $1$ tugrick. The ratio of the denominations of coin types $k + 1$ and $k$ equals $a_{k}$. It is known that for each $x$ there are ...
Let's calculate DP[pref][x] - number of ways to pay $x$ tugriks using only $pref$ first types. Of course, $x$ can be very big, but we will store DP only for those $x$ which are not bigger than the sum of all the coins of first $pref$ types and can lead to answer: $x = k \cdot D + (m%D)$ where $D$ is the last coin denom...
[ "combinatorics", "dp", "math" ]
3,200
null
756
F
Long number
Consider the following grammar: - <expression> ::= <term> | <expression> '+' <term> - <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')' - <number> ::= <pos_digit> | <number> <digit> - <digit> ::= '0' | <pos_digit> - <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' This gra...
First of all we need to somehow parse the expression. Let's suppose we've builded a parse tree for the expression. Every number X can be seen as operation "concatenate something and X". We should understand how such an operation changes the number. $YX = Y \cdot 10^{len(X)} + X$. So we can represent each number $X$ as ...
[ "expression parsing", "math", "number theory" ]
3,400
null
757
A
Gotta Catch Em' All!
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
Expected complexity: ${\mathcal{O}}(n)$ Main idea: Maintain counts of required characters. Since we are allowed to permute the string in any order to find the maximum occurences of the string "Bulbasaur", we simply keep the count of the letters 'B', 'u', 'l', 'b', 'a', 's', 'r'. Now the string "Bulbasaur" contains 1 'B...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { map<char, int> m; string s; cin>>s; for(auto x : s) m[x]++; int ans = m['B']; ans = min(ans, m['u']/2); ans = min(ans, m['a']/2); ans = min(ans, m['b']); ans = min(ans, m['s']); ans = min(ans, m['r']); ans = min(ans, m['l']); cout ...
757
B
Bash's Big Day
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of $k > 1$ Pokemon with strengths ${s_{1}...
Expected complexity: $O(n{\sqrt{m a x(s_{i})}})$ Main idea: Square-root factorization and keeping count of prime factors. The problem can be simplified to finding a group of Pokemons such that their strengths have a common factor other that $1$. We can do this by marking just the prime factors, and the answer will be t...
[ "greedy", "math", "number theory" ]
1,400
#include<bits/stdc++.h> using namespace std; int N; unordered_map<int, int> factors; int main() { ios_base::sync_with_stdio(false); cin >> N; while(N--) { int strength; cin >> strength; int root = sqrt(strength); for(int i = 2; i <= root; i++) { if(strength%i == 0) factors[i]++; while(streng...
757
C
Felicity is Coming!
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has $n$ gyms. The $i$-th gym has $g_{i}$ Pokemon in it. There are $m$ distinct Pokemon types in the Himalayan region numbered from $1$ to $m$. There is a special evolution c...
Expected complexity: $O(n l o g n)$ Main idea: Divide pokemon types into equivalence classes based on their counts in each list. Consider a valid evolution plan $f$. Let $c[p, g]$ be the number of times Pokemon $p$ appears in gym $g$. If $f(p) = q$ then $c[p,g_{i}]=c[q,g_{i}]\quad\forall i$. Now consider a group of Pok...
[ "data structures", "hashing", "sortings", "strings" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define PB push_back #define ALL(X) X.begin(), X.end() #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) const int N = 1e6; const LL MOD = 1e9 + 7; LL fact[N+1]; int main() { fast_io; fact[0] = fact[1] = 1; for(LL i=2;i<=N;...
757
D
Felicity's Big Secret Revealed
The gym leaders were fascinated by the evolutions which took place at Felicity camp. So, they were curious to know about the secret behind evolving Pokemon. The organizers of the camp gave the gym leaders a PokeBlock, a sequence of $n$ ingredients. Each ingredient can be of type $0$ or $1$. Now the organizers told the...
Expected complexity: $O(N*2^{20})$ Main idea: DP with Bitmask. This problem can be solved using Dynamic Programming with bitmask. The important thing to note here is that the set of distinct numbers formed will be a maximum of 20 numbers, i.e. from 1 to 20, else it won't fit 75 bits(1*(1 bits) + 2*(2 bits) + 4*(3 bits)...
[ "bitmasks", "dp" ]
2,200
// Saatwik Singh Nagpal #include <bits/stdc++.h> using namespace std; #define TRACE #ifdef TRACE #define TR(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const c...
757
E
Bash Plays with Functions
Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions. Bash defines a function $f_{0}(n)$, which denotes the number of ways of factoring $n$ into two factors $p$ and $q$ such that $gcd(p, q) = 1$. In other words, $f_{0}(n)$ is the number of ordered p...
Expected complexity: $O((N+Q)l o g N)$ Main idea: Multiplicative Functions. We can easily see that $f_{0}$ = $2^{(number of distinct prime factors of n)}$. We can also see that it is a multiplicative function. We can also simplify the definition of $f_{r + 1}$ as: $f_{r+1}(n)=\sum_{d\mid n}f_{r}(d)$ Since $f_{0}$ is a ...
[ "brute force", "combinatorics", "dp", "number theory" ]
2,500
//Kyokai no Kanata // //Written by Satyam Pandey// #include<bits/stdc++.h> using namespace std; typedef pair<int,int> II; typedef vector<II> VII; typedef vector<int> VI; typedef vector< VI > VVI; typedef long long int LL; #define PB push_back #define MP make_pair #define F first #define S second #define SZ(a) (int)...
757
F
Team Rocket Rises Again
It's the turn of the year, so Bash wants to send presents to his friends. There are $n$ cities in the Himalayan region and they are connected by $m$ bidirectional roads. Bash is living in city $s$. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pi...
Expected complexity: $O((N+M)\cdot l o g N)$ Main idea: Building Dominator tree on shortest path DAG. First of all, we run Dijkstra's shortest path algorithm from $s$ as the source vertex and construct the shortest path DAG of the given graph. Note that in the shortest path DAG, the length of any path from $s$ to any o...
[ "data structures", "graphs", "shortest paths" ]
2,800
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <cassert> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define pb push_back #define mp make_pair #define all(...
757
G
Can Bash Save the Day?
Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions. Initially, Meowth gives Bash...
Expected complexity: $\ O((N+Q)\cdot l o g N)$ Main idea: Making the Centroid Tree Persistent. First let's try to solve a much simpler problem given as follows. Question: Given a weighted tree, initially all the nodes of the given tree are inactive. We need to support the following operations fast : $Query v$ : Report ...
[ "data structures", "divide and conquer", "graphs", "trees" ]
3,400
//Toshad Salwekar #include<bits/stdc++.h> #define f(i,a,n) for(int i=a;i<n;i++) #define S second #define F first #define Sc(n) scanf("%lld",&n) #define scc(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define sp(a) scanf("%lld %lld",&a.first,&a.second) #define pb push_back #define mp make_pair #define lb lower_bound #define...
758
A
Holiday Of Equality
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are $n$ citizens, the welfare of each of them is estimated as the integer in $a_{i}$ burles (burle is the currency in Berl...
As it's impossible to decrease numbers, we have to increase them to at least $max(a_{1}, a_{2}, ..., a_{n})$. If all the numbers are already equal to $max(a_{1}, a_{2}, ..., a_{n})$ then there is no need to increase any of them as it will cost extra operations. So you should find $max(a_{1}, a_{2}, ..., a_{n})$ using o...
[ "implementation", "math" ]
800
null
758
B
Blown Garland
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin...
Four consecutive bulbs should not be of the same color, and it is four possible colors, so the color of the fifth bulb is the same as the first bulb has, the color of the sixth is the same as the second bulb has, it means that the color of the $n$-th bulb equals the color of the $(n - 4)$-th bulb. Thus, the coordinates...
[ "brute force", "implementation", "number theory" ]
1,100
null
758
C
Unfair Poll
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where $n$ rows with $m$ pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order o...
Let's learn to count $f(x, y)$ - the number of questions which were asked to the pupil in the $x$-th row, at the $y$-th place in the order. Note that the process of asking is periodic. During one period children were asked in the following order: the pupil from the first row who seats at the first table; the pupil from...
[ "binary search", "constructive algorithms", "implementation", "math" ]
1,700
null
758
D
Ability To Convert
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter $A$ he will write the number $10$. Thus, by converting the number $475$ from decimal to hexadecimal system, h...
Let's compare answers for numbers $k$ and $\left|{\frac{k}{10}}\right|$, that is $k$ without the rightmost digit. Note that for any $x$ number $\textstyle{\left|{\frac{x}{10}}\right|}$ is either contains less substrings (valid digits in base-$n$ numeric system) or it's possible to decrease value of the last substring o...
[ "constructive algorithms", "dp", "greedy", "math", "strings" ]
2,000
null
758
E
Broken Tree
You are given a tree that has $n$ vertices, which are numbered from $1$ to $n$, where the vertex number one is the root. Each edge has weight $w_{i}$ and strength $p_{i}$. Botanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees. The tree is broken if there is ...
First, let's calculate min and max weight for subtrees of each vertex. Minimal weight of a subtree is sum of minimal weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges reduced in weight to minimal possible. Thus, minimal weight is $d p m i n_{x}=\sum_{i=1}^{n_{x}}d ...
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
2,600
null
758
F
Geometrical Progression
For given $n$, $l$ and $r$ find the number of distinct geometrical progression, each of which contains $n$ distinct integers not less than $l$ and not greater than $r$. In other words, for each progression the following must hold: $l ≤ a_{i} ≤ r$ and $a_{i} ≠ a_{j}$ , where $a_{1}, a_{2}, ..., a_{n}$ is the geometrical...
Let $d$ - is the denominator of the progression. $d$ - is the rational number, because all numbers of progression are integers. $d={\frac{\pi}{y}}$,where $x, y$ - are integers, $gcd(x, y) = 1$. Then $a_{n}=a_{1}\cdot{\frac{x^{n-1}}{v^{n-1}}}$. Because all numbers of progression are integers, so $a_{1}\colon y^{n-1}$. L...
[ "brute force", "math", "number theory" ]
2,400
null
760
A
Petr and a calendar
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: Petr wants to ...
Just implement writing dates one by one and keeping current column and row, or use the formula $answer = ((d - 1) + ndays - 1) / 7 + 1$, where $ndays$ is the number of days in the month.
[ "implementation", "math" ]
800
null
760
B
Frodo and pillows
$n$ hobbits are planning to spend the night at Frodo's house. Frodo has $n$ beds standing in a row and $m$ pillows ($n ≤ m$). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets h...
Let's do binary search on the answer. How to check if Frodo can have $x$ pillows or more? We need to calculate the least amount of pillows we need to give to all the hobbits and compare it to m. The number of pillows is minimized if we give $x - 1$ pillows to Frodo's neighbors, $x - 2$ pillows to the hobbits at the dis...
[ "binary search", "greedy" ]
1,500
null
761
A
Dasha and Stairs
On her way to programming school tiger Dasha faced her first test — a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number ...
It's obvious, that if $|a - b| > 1$ - the answer is <<NO>>. <<NO>> answer was also in the case, when $a$ and $b$ are equal to $0$, because according to the statement, such interval should exist. In other cases the answer is <<YES>>. Complexity: $O(1)$.
[ "brute force", "constructive algorithms", "implementation", "math" ]
1,000
null
761
B
Dasha and friends
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length $L$, in distinct points of which there are $n$ barriers. Athlete always run the track in counterclockwise direction if...
Let's add distances between pairs of adjacent barriers of both tracks in arrays and check if it possible to get one of them from another using cycling shift of the elements. Complexity: $O(n^{2})$.
[ "brute force", "implementation", "math" ]
1,300
null
761
C
Dasha and Password
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length $n$ which satisfies the following requirements: - There is at least one digit in the string, - There is at least one lowercase (small) letter of the Latin alphabet in the string, -...
Let's iterate the string, where we want to get a digit to the password, then the string, where we'll get a letter to the password and the string, where we'll get one of the characters '&', '*', '#'. Obviously, in the other strings we can pick any character, so we only need to compute minimal number of moves we have to ...
[ "brute force", "dp", "implementation" ]
1,500
null
761
D
Dasha and Very Difficult Problem
Dasha logged into the system and began to solve problems. One of them is as follows: Given two sequences $a$ and $b$ of length $n$ each you need to write a sequence $c$ of length $n$, the $i$-th element of which is calculated as follows: $c_{i} = b_{i} - a_{i}$. About sequences $a$ and $b$ we know that their elements...
Let's match each element of $a$ interval of values, which corresponding element of $c$ could take, i.e for $i$-th element interval $[l - a_{i};r - a_{i}]$. Let $pos_{i}$ be the index of element equal to $i$ in permutation $p$. Now you can know, that solving the initial task is reduced to picking a number of each interv...
[ "binary search", "brute force", "constructive algorithms", "greedy", "sortings" ]
1,700
null
761
E
Dasha and Puzzle
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are $n - 1$ edges in a tree with $n$ vertices. The puzzle is ...
The answer doesn't exist, when there is a vertex with degree > $4$. We'll use power of two as length of each edge in the tree. Let's dfs our tree and store in the recursion: the direction, where our parent is located (one of four possible), and the length of the edge we'll build from current vertex. Then iterate the ne...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
2,000
null
761
F
Dasha and Photos
Dasha decided to have a rest after solving the problem $D$ and began to look photos from previous competitions. Let's call photos as the matrix with the size $n × m$, which consists of lowercase English letters. Some $k$ photos especially interested her, because they can be received from photo-template by painting a ...
Let special photo be the matrix, made by changing subrectangle in the initial, and changed submatrix - changed subrectangle itself. Firsly, let's calculate $cnt(x, y, ch)$ - the number of special photos, in which cell (x, y) belongs to changed submatrix, such that cell (x, y) contains character $ch$. It can be done usi...
[ "brute force", "data structures", "dp", "implementation" ]
2,600
null
762
A
k-th divisor
You are given two integers $n$ and $k$. Find $k$-th smallest divisor of $n$, or report that it doesn't exist. Divisor of $n$ is any such natural number, that $n$ can be divided by it without remainder.
If you find all the small divisors of n that are less than sqrt(n), you can find the rest of them dividing n by the small ones. By the way, this problem is widely known and googlable :) You can, for example, check out this link: http://stackoverflow.com/questions/26753839/efficiently-getting-all-divisors-of-a-given-num...
[ "math", "number theory" ]
1,400
null
762
B
USB vs. PS/2
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis! The computers bought for the room were different. Some of them had only USB ...
Try coming up either with greedy algorithm or with two pointers algorithm. Try to prove the following greedy: in each step we can choose the cheapest remaining mouse. If there is a computer left that has only one type of port suitable for this mouse, plug it there. Else if there is a computer with both types, plug it t...
[ "greedy", "implementation", "sortings", "two pointers" ]
1,400
null
762
C
Two strings
You are given two strings $a$ and $b$. You have to remove the minimum possible number of \textbf{consecutive} (standing one after another) characters from string $b$ in such a way that it becomes a subsequence of string $a$. It can happen that you will not need to remove any characters at all, or maybe you will have to...
Try thinking not about erasing a substring from B, but rather picking some number of characters (possibly zero) from the left, and some from the right. Two pointers For every prefix of B, count how big of a prefix of A you will require. Call these values p[i]. Put infinity in the cells where even whole A is not enough....
[ "binary search", "hashing", "strings", "two pointers" ]
2,100
null
762
D
Maximum path
You are given a rectangular table $3 × n$. Each cell contains an integer. You can move from one cell to another if they share a side. Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maxi...
The toughest thing about this task, is that you can go to the left. Try to come up with something to handle that. Try to prove that in optimal solution you don't need to go more than one cell to the left before coming back.
[ "dp", "greedy", "implementation" ]
2,300
null
762
E
Radio stations
In the lattice points of the coordinate line there are $n$ radio stations, the $i$-th of which is described by three integers: - $x_{i}$ — the coordinate of the $i$-th station on the line, - $r_{i}$ — the broadcasting range of the $i$-th station, - $f_{i}$ — the broadcasting frequency of the $i$-th station. We will s...
Try to come up with a solution where you iterate over each frequency Try to group stations that will be on the left side in a pair in one vector, and stations that will be on the right side in a pair into another. Iterate over each frequncy. Suppose you are now on frequency $i$. Put all radio stations with frequencly $...
[ "binary search", "data structures" ]
2,200
null
762
F
Tree nesting
You are given two trees (connected undirected acyclic graphs) $S$ and $T$. Count the number of subtrees (connected subgraphs) of $S$ that are isomorphic to tree $T$. Since this number can get quite large, output it modulo $10^{9} + 7$. Two subtrees of tree $S$ are considered different, if there exists a vertex in $S$...
One of the possible ways to make your life easier is to count the number of automorphisms of tree $T$. This way you will be able to first calculate the number of labeled matchings of vertices of tree $T$ to the vertices of tree $S$, and then divide this number by the number of automorphisms. Although solution that I wi...
[ "combinatorics", "graphs", "trees" ]
2,800
null
763
A
Timofey and a tree
Each New Year Timofey and his friends cut down a tree of $n$ vertices and bring it home. After that they paint all the $n$ its vertices, so that the $i$-th vertex gets color $c_{i}$. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes...
Take any edge which vertices are colored in different colors. If such edge doesn't exist you can print any vertex, because all the tree is colored in the same color. Otherwise, try to make a root from each of these vertices. Check if is possible with simple dfs. If it succeedes for one of them, print "YES" and this ver...
[ "dfs and similar", "dp", "dsu", "graphs", "implementation", "trees" ]
1,600
"//Codeforces Round #395 Div2C/Div1A solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define ...
763
B
Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane $n$ rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have \textbf{odd} length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in ...
Let's consider vertical touchings graph, where vertex is rectangle. For each vertex we keep x coordinate of bottom-right angle. While moving to next rectangle it changes by odd number. In this graph doesn't exist cycle of odd length (sum of odd number of odd numbers can't be zero). Similar to this you can see about hor...
[ "constructive algorithms", "geometry" ]
2,100
"//Codeforces Round #395 Div2D/Div1B solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define ...
763
C
Timofey and remoduling
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime $m$. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of \textbf{distinct} integers $a_{1}...
First, let's think about the case when $2n < m$. In this editorial we say that an outcoming sequence is $s, s + d, s + 2d, ..., s + (n - 1)d$ Assume $x$ is the difference of some two elements $a$ and $b$ of $A$ ($x=b-a\mod m$). Let's say that $a$ was on $i$-th place in the sequence and $b$ was on $i + k$-th place. Then...
[ "brute force", "implementation", "math", "number theory" ]
2,600
"//Codeforces Round #395 Div2E/Div1C solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include ...
763
D
Timofey and a flat tree
Little Timofey has a big tree — an undirected connected graph with $n$ vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex. Timofey assumes t...
There are only $2 \cdot (n - 1)$ subtrees in the whole tree: two for each edge. Let's calculate hashes of each of them. We can calculate hash of a subtree, for example, in a following. Let's associate each vertex with a correct bracket sequence. Leaves are associated with "()", other vertices are associated with their ...
[ "data structures", "graphs", "hashing", "shortest paths", "trees" ]
2,900
"//Codeforces Round #395 Div1D solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include <ctime...
763
E
Timofey and our friends animals
After his birthday party, Timofey went to his favorite tree alley in a park. He wants to feed there his favorite birds — crows. It's widely known that each tree is occupied by a single crow family. The trees in the alley form a row and are numbered from $1$ to $n$. Some families are friends to each other. For some rea...
Let's build a segment tree on crow families. Let's save DSU in each vertex, having information about number of components of connectivity on it. In one vertex will be DSU with size $n$. In two vertices will be DSU with size $n / 2$. In four vertices will be DSU with size $n / 4$. It's easy to show that we will store on...
[ "data structures", "divide and conquer", "dsu" ]
2,900
"//Codeforces Round #395 Div1E solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include <ctime...
764
A
Taymyr is calling you
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every $n$ minutes, i.e. in minutes $n$, $2n$, $3n$ and so on. Artists come to the comrade every $m$ minutes, i.e. in minutes $m$, $2m$, $3m$ and so on. The day is $z$ minutes long,...
You can look over all minutes of the day. If both events happen on the some minute, we increment our answer.
[ "brute force", "implementation", "math" ]
800
"#Codeforces Round #395 Div2A solution\nfrom math import gcd\n\nn, m, z = map(int, input().split())\ng = gcd(n, m)\nlcm = n * m // g\nprint(z // lcm)"
764
B
Timofey and cubes
Young Timofey has a birthday today! He got kit of $n$ cubes as a birthday present from his parents. Every cube has a number $a_{i}$, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Su...
Note that Dima's operations are reversible. If we apply them to the current order, we will get the initial. Also note that all the elements on even positions will remain on their places. Such numbers are affected an even number of times, so nothing will change. Similarly all elements on odd positions will change places...
[ "constructive algorithms", "implementation" ]
900
"//Codeforces Round #395 Div2B solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define forab(...
765
A
Neverending competitions
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
Each competition adds two flights to the list - there and back. The only exception is the last competition: if Jinotega is now there, it adds only one flight. So if $n$ is odd, the answer is contest, otherwise home.
[ "implementation", "math" ]
900
null
765
B
Code obfuscation
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest. To obfuscate the code, Kostya first looks at the first variable name used in his program and rep...
In this problem you needed to check that the first occurrences of letters $a$, $b$, ... appear in order (that is, first "$a$" is before first "$b$", which, in order, is before first "$c$", so on). One possible solution: for each letter $x$ check that there is at least one letter $x - 1$ before it.
[ "greedy", "implementation", "strings" ]
1,100
null
765
C
Table Tennis Game 2
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly $k$ points, the score is reset and a new set begins. Across all the sets Misha scored $a$ poi...
There are several possible cases how the game could go: The first player won all the sets. In this case, each set gave him exactly $k$ points, hence $a$ must be divisible by $k$. Moreover, $b \le (a / k) \cdot (k - 1)$ since the second player could get at most $k - 1$ points per set. If we have $k|a$ and $0 \le b ...
[ "math" ]
1,200
null
765
D
Artsem and Saunders
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let $[n]$ denote the set ${1, ..., n}$. We will also write $f: [x] → [y]$ when a function $f$ is defined in integer points $1$, ..., $x$, and all its values are integers from 1 to $y$. Now then, you are given a...
Suppose that $h(g) \equiv f$ (that is, the functions match on all inputs), and $g(h)\equiv1$ (the identity function). Hence, we must have $f(f(x))=h(g(h(g(x))))=h({\bf1}(g(x)))=h(g(x))=f(x)$. It means that if $f(x) = y$, then $f(y) = f(f(x)) = f(x) = y$, that is, all distinct values of $f$ must be its stable points. ...
[ "constructive algorithms", "dsu", "math" ]
1,700
null
765
E
Tree Folding
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex $v$, and two disjoint (except for $v$) paths of equal length $a_{0} = v$, $a_{1}$, ..., $a_{k}$, and $b_{0} = v$, $b_{1}$, ..., $b_{k}$. Additionally, vertices $a_{1}$, ..., $a_{k}$, $b_{1}$, ..., $b_{k}$ must not hav...
Let's look at the performed actions in reverse. First, we have some path of odd length (by saying length we mean the number of edges} and double it several times. Now we do several "unfoldings". Among two leaves of this path exactly one (or its copy) participate in each unfolding; depending on it we call the unfolding ...
[ "dfs and similar", "dp", "greedy", "implementation", "trees" ]
2,200
null
765
F
Souvenirs
Artsem is on vacation and wants to buy souvenirs for his two teammates. There are $n$ souvenir shops along the street. In $i$-th shop Artsem can buy one souvenir for $a_{i}$ dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs wit...
We will answer queries offline, moving right endpoint to the right and storing the answer for each left endpoint in a segment tree. The tree will support two operations: set minimum on a segment and get a value in the point. More, we assume that among two elements $a_{i}$ and $a_{j}$ in our array $a_{i} > a_{j}$ and $i...
[ "data structures" ]
3,100
null
765
G
Math, math everywhere
If you have gone that far, you'll probably skip unnecessary legends anyway... You are given a binary string $s=s_{0}\cdot\cdot\cdot s_{m-1}$ and an integer $N=p_{1}^{\alpha_{1}}\cdot\cdot\cdot p_{n}^{\alpha_{n}}$. Find the number of integers $k$, $0 ≤ k < N$, such that for all $i = 0$, $1$, ..., $m - 1$ \[ \operatorn...
First I'll describe our original approach to this problem, and then some issues we encountered after the round finished. Suppose that $p_{1} = 2$. If we have $x\equiv0(\mathrm{mod}\,2)$, then the string $s$ must look like 0?0?0?..., that is, all even positions 0, 2, 4, ... will have 0's (for all others, we can't say), ...
[ "brute force", "dp", "math", "meet-in-the-middle", "number theory" ]
3,200
null
766
A
Mahmoud and Longest Uncommon Subsequence
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings $a$ and $b$, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence ...
If the strings are the same, Any subsequence of $a$ is indeed a subsequence of $b$ so the answer is "-1", Otherwise the longer string can't be a subsequence of the other (If they are equal in length and aren't the same, No one can be a subsequence of the other) so the answer is maximum of their lengths. Time complexity...
[ "constructive algorithms", "strings" ]
1,000
"#include <iostream>\n#include <string.h>\nusing namespace std;\nint main()\n{\n\tstring a,b;\n\tcin >> a >> b;\n\tif (a==b)\n\tcout << -1;\n\telse\n\tcout << max(a.size(),b.size());\n}"
766
B
Mahmoud and a Triangle
Mahmoud has $n$ line segments, the $i$-th of them has length $a_{i}$. Ehab challenged him to use \textbf{exactly $3$} line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the l...
Let $x$, $y$ and $z$ be the lengths of 3 line segments such that $x \le y \le z$, If they can't form a non-degenerate triangle, Line segments of lengths $x - 1$, $y$ and $z$ or $x$, $y$ and $z + 1$ can't form a non-degenerate triangle, So we don't need to try all the combinations, If we try $y$ as the middle one, W...
[ "constructive algorithms", "geometry", "greedy", "math", "number theory", "sortings" ]
1,000
"#include <iostream>\n#include <algorithm>\nusing namespace std;\nbool check(int a,int b,int c)\n{\n\tint tmp[]={a,b,c};\n\tsort(tmp,tmp+3);\n\treturn (tmp[0]+tmp[1]>tmp[2]);\n}\nint main()\n{\n\tint n;\n\tcin >> n;\n\tif (n>=45)\n\tcout << \"YES\";\n\telse\n\t{\n\t\tint arr[n];\n\t\tfor (int i=0;i<n;i++)\n\t\tcin >> a...
766
C
Mahmoud and a Message
Mahmoud wrote a message $s$ of length $n$. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number $i$ in the English...
Let $dp[i]$ be the number of ways to split the prefix of $s$ ending at index $i$ into substrings that fulfills the conditions. Let it be 1-indexed. Our base case is $dp[0] = 1$. Our answer is $dp[n]$. Now let's calculate it for every $i$. Let $l$ be the minimum possible index such that the substring from $l$ to $i$ sat...
[ "brute force", "dp", "greedy", "strings" ]
1,700
"#include <iostream>\n#include <string.h>\nusing namespace std;\n#define mod 1000000007\nstring s;\nint arr[26],dp[1005],dp2[1005];\nint main()\n{\n\tint n,l=0;\n\tcin >> n >> s;\n\tfor (int i=0;i<26;i++)\n\tcin >> arr[i];\n\tdp[0]=1;\n\tdp2[0]=0;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tint f=0;\n\t\tdp2[i]=n;\n\t\tfor (in...
766
D
Mahmoud and a Dictionary
Mahmoud wants to write a new dictionary that contains $n$ words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words. He know that if two words hav...
Let's build a graph containing the words, For every relation in the input add a new edge with the weight of $0$ if they are equal and $1$ if they are opposites, If adding the edge doesn't make the graph cyclic, Our relation is valid, Otherwise it may be valid or invalid so we'll answer them offline. Check if adding tha...
[ "data structures", "dfs and similar", "dp", "dsu", "graphs" ]
2,000
#include <iostream> #include <string.h> #include <vector> #include <map> using namespace std; map<string,int> m; pair<int,int> arr[100005]; vector<pair<int,int> > v[100005]; vector<pair<pair<int,int>,pair<int,int> > > sus; bool valid[100005],vis[100005]; int n,cum[100005]; int find(int x) { if (x!=arr[x].first) ...
766
E
Mahmoud and a xor trip
Mahmoud and Ehab live in a country with $n$ cities numbered from $1$ to $n$ and connected by $n - 1$ undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number $a_{i}$ attached to it. We define the distance from city $x$ to city $y$ as the xor of numbers atta...
If we have an array $ans[i]$ which represents the number of paths that makes the $i^{th}$ bit sit to $1$, Our answer will be $\sum_{i=0}^{l o g(n)}2^{i}*a n s[i]$ Let $arr[i][x]$ be the binary value of the $x^{th}$ bit of the number attached to node $i$(just to make work easier). There are 2 types of paths from node $u...
[ "bitmasks", "constructive algorithms", "data structures", "dfs and similar", "dp", "math", "trees" ]
2,100
"#include <iostream>\n#include <iomanip>\n#include <string.h>\n#include <vector>\nusing namespace std;\nvector<int> v[100005];\nint arr[100005][25];\nlong long dp[100005][25][2],ans[25];\nvoid dfs(int node,int pnode)\n{\n\tlong long s[25][2];\n\tmemset(s,0,sizeof(s));\n\tfor (int i=0;i<25;i++)\n\tdp[node][i][arr[node][...
767
A
Snacktower
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time $n$ snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should b...
It is enough to do what is written in the statements. You can maintain an array $has$, and mark in it which snacks has already fallen, and which hasn't. Create another variable $next$ which tracks the next snack which should be put on the top. Let's proceed with the integers in the input one by one. After reading next ...
[ "data structures", "implementation" ]
1,100
null
767
B
The Queue
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow. He know...
Let's calculate the point of time when each visitor would be served. Let array $a$ contain the points of time when visitors arrive. The receptionist would begin to serve the first visitor at the point of time when the receptionist begins to work $t_{s}$, if the first visitor came to the passport office before it, or wh...
[ "brute force", "greedy" ]
2,100
null
767
C
Garland
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the nu...
We can note that the given graph is a tree. Let's perform a dfs from the root of the tree. Let's calculate the sums if $t_{i}$ in each subtree, let this value be $s_{v}$ for the subtree of the vertex $v$. In order to compute $s_{v}$ we need to recursively call dfs from all sons of $v$ and add the value $t_{v}$. Let the...
[ "dfs and similar", "graphs", "greedy", "trees" ]
2,000
null
767
D
Cartons of milk
Olya likes milk very much. She drinks $k$ cartons of milk each day if she has at least $k$ and drinks all of them if she doesn't. But there's an issue — expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's frid...
Let $t$ be the maximum expiry date in the input. The key observation in this problem is the fact that if we can buy some $x$ cartons from the shop and not have to throw away the cartons, we can buy $x$ cartons with the biggest expiry dates and we won't have to throw away any cartons either. It happens because if we inc...
[ "binary search", "data structures", "greedy", "sortings", "two pointers" ]
2,100
null
767
E
Change-free
Student Arseny likes to plan his life for $n$ days ahead. He visits a canteen every day and he has already decided what he will order in each of the following $n$ days. Prices in the canteen do not change and that means Arseny will spend $c_{i}$ rubles during the $i$-th day. There are $1$-ruble coins and $100$-ruble n...
The first thing to note is that during day $i$ it makes sense to either pay $c_{i}\mathrm{~div~}100$ notes and $c_{i}{\mathrm{~mod~}}100$ coins (in this case, the cashier's dissatisfaction would be equal to $0$), or just $c_{i}\,\mathrm{div}\,100+1$ notes (in that case, the cashier's dissatisfaction would be equal to $...
[ "greedy" ]
2,400
null
768
A
Oath of the Night's Watch
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
You just have to find the number of elements greater than the minimum number occurring in the array and less than the maximum number occurring in the array. This can be done in $O(n)$ by traversing the array once and finding the minimum and maximum of the array, and then in another traversal, find the good numbers. Com...
[ "constructive algorithms", "sortings" ]
900
#include<bits/stdc++.h> using namespace std; int a[100005]; int main() { int n,c1=0,c2=0,mx=0,mn=1000000007; cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; mx=max(mx,a[i]),mn=min(mn,a[i]); } for(int i=0;i<n;i++) { if(a[i]==mx) c1++; if(a[i]==mn) c2++; } if(mx==mn) cout<<0; else cout<<(n-c1-c2); return 0...
768
B
Code For 1
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
It is easy to see that the total number of elements in the final list will be $2^{\lfloor\log_{2}n\rfloor+1}-1$ . The problem can be solved by locating each element in the list and checking whether it is $'1'$ .The $i^{th}$ element can be located in $O(logn)$ by using Divide and Conquer strategy. Answer is the total nu...
[ "constructive algorithms", "dfs and similar", "divide and conquer" ]
1,600
#include<bits/stdc++.h> using namespace std; long long int cnt(long long int temp) //returns the length of final list { long long int x=1; while(temp>1) { temp/=2; x*=2; } return x; } int is_one(long long int pos,long long int target,long long int num) { if(num<2) return num; if(pos+1==2*tar...
768
C
Jon Snow and his Favourite Number
Jon Snow now has to fight with White Walkers. He has $n$ rangers, each of which has his own strength. Also Jon Snow has his favourite number $x$. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon n...
The range of strengths of any ranger at any point of time can be [0,1023]. This allows us to maintain a frequency array of the strengths of the rangers. Now, the updation of the array can be done in the following way: Make a copy of the frequency array. If the number of rangers having strength less than a strength $y$ ...
[ "brute force", "dp", "implementation", "sortings" ]
1,800
#include<bits/stdc++.h> #define rep(i,start,lim) for(int i=start;i<lim;i++) using namespace std; #define N 100005 int freq[1100],tmp[1024]; int main() { int n,k,maxm=0,minm=INT_MAX,p,x; cin>>n>>k>>x; rep(i,0,n) cin>>p,freq[p]++; rep(i,0,k) { rep(j,0,1024) tmp[j]=freq[j]; int par=0; rep(j,0,1024) { if(fr...
768
D
Jon and Orbs
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are $k$ different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, ...
This problem can be solve using inclusion-exclusion principle but precision errors need to be handled. Therefore, we use the following dynamic programming approach to solve this problem. On $n - th$ day there are two possibilities, Case-1 : Jon doesn't find a new orb then the probability of it is $\scriptstyle{\frac{\p...
[ "dp", "math", "probabilities" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = 1004; const double eps = 1e-7; double dp[N]; int ans[N]; int main(){ int k, q, d = 1; cin >> k >> q; dp[0] = 1; for(int n = 1; d <= 1000; ++n){ for(int x = k; x > 0; --x){ dp[x] = (x * dp[x] + (k - x + 1) * dp[x - 1]) / k; } while(d <= 1000 && 2...
768
E
Game of Stones
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: - The game starts with $n$ piles of stones indexed from $1$ to $n$. The $i$-th pile contains $s_{i}$ stones. - The players make their moves alternatively....
This problem can be solved using DP with Bitmasks to calculate the grundy value of piles. Let us have a 2-dimensional dp table, $dp[i][j]$, where the first dimension is for number of stones in the pile and second dimension is for bitmask. The bitmask has $k$-th bit set if we are allowed to remove $k + 1$ stones from th...
[ "bitmasks", "dp", "games" ]
2,100
#include<bits/stdc++.h> using namespace std; typedef long long ll; map<pair<int, ll>, int> grundy; map<pair<int, ll>, bool> mp; int retgrundy(int ps, ll bm, int prev = 63){ for(int i=ps ; i<prev ; ++i){ if(((bm>>i)&1LL) == 1LL) bm ^= (1LL<<i); } if(mp[{ps, bm}]) return grundy[...
768
F
Barrels and boxes
Tarly has two different type of items, food boxes and wine barrels. There are $f$ food boxes and $w$ wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no t...
Every arrangement of stacks can expressed in the form of linear arrangement. In this linear arrangement, every contiguous segment of wine barrels are separated by food boxes. For the arrangement to be liked by Jon each of the $f + 1$ partitions created by $f$ food boxes must contain either $0$ or greater than $h$ wine ...
[ "brute force", "combinatorics", "math", "number theory", "probabilities" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 212345; const int mod = 1000000007; int fac[N], ifac[N], inv[N]; void prep(){ fac[0] = ifac[0] = inv[1] = 1; for(int i = 1; i < N; ++i) fac[i] = 1LL * i * fac[i - 1] % mod; for(int i = 2; i < N; ++i) inv[i] = mod - 1LL * (mod / i...
768
G
The Winds of Winter
Given a rooted tree with $n$ nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest. The root of a tree in the forest is the node in that tree which does not have a parent. W...
We are given a tree. We remove one node from this tree to form a forest. Strength of forest is defined as the size of largest tree in forest. We need to minimize the strength by changing the parent of atmost one node to some other node such that number of components remain same. To find the minimum value of strength we...
[ "binary search", "data structures" ]
3,300
#include <bits/stdc++.h> using namespace std; const int N = 100005; vector<int> adj[N]; int sz[N], ans[N]; int n, root; bool big[N]; map<int,int> mp, mpo, par; void getsz(int s){ sz[s] = 1; ans[s] = n - 1; for(auto it : adj[s]){ getsz(it); sz[s] += sz[it]; } mpo[sz[s]]++; } void b...