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 ⌀ |
|---|---|---|---|---|---|---|---|
902 | A | Visiting a Friend | Pig is visiting a friend.
Pig's house is located at point $0$, and his friend's house is located at point $m$ on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightm... | Note that if we can get to some point x, then we can get to all points <= x. So we can support the rightmost point where we can get to. Then if this point can use the teleport (if this point is to the right of the teleport), we'll try to move it (If the limit of the teleport is to the right of the current point, then m... | [
"greedy",
"implementation"
] | 1,100 | null |
902 | B | Coloring a Tree | You are given a rooted tree with $n$ vertices. The vertices are numbered from $1$ to $n$, the root is the vertex number $1$.
Each vertex has a color, let's denote the color of vertex $v$ by $c_{v}$. Initially $c_{v} = 0$.
You have to color the tree into the given colors using the smallest possible number of steps. On... | Consider the process from the end, we will "delete" any subtree from the tree, whose color of the ancestor of the highest vertex differs from the color of the highest vertex and the colors of all vertices in the subtree are the same. Thus, we can show that the answer is the number of edges whose ends have different col... | [
"dfs and similar",
"dsu",
"greedy"
] | 1,200 | null |
903 | A | Hungry Student Problem | Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains $3$ chunks; a large one — $7$ chunks. Ivan wants to eat exactly $x$ chunks. Now he wonders whether he can buy exac... | There are lots of different approaches to this problem. For example, you could just iterate on the values of $a$ and $b$ from $0$ to $33$ and check if $3a + 7b = x$. | [
"greedy",
"implementation"
] | 900 | null |
903 | B | The Modcrab | Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has $h_{2}$ health points and an attack power of $a_{2}$. Knowing that... | A simple greedy solution works: simulate the process until the Modcrab is dead, and make Vova drink a potion if his current health is less than $a_{2} + 1$, and monster's current health is greater than $a_{1}$ (because in this case Vova can't finish the Modcrab in one strike, but the Modcrab can win if Vova doesn't hea... | [
"greedy",
"implementation"
] | 1,200 | null |
903 | C | Boxes Packing | Mishka has got $n$ empty boxes. For every $i$ ($1 ≤ i ≤ n$), $i$-th box is a cube with side length $a_{i}$.
Mishka can put a box $i$ into another box $j$ if the following conditions are met:
- $i$-th box is not put into another box;
- $j$-th box doesn't contain any other boxes;
- box $i$ is smaller than box $j$ ($a_{... | You can always show that the answer is equal to the amount of boxes of the size appearing the most in array. Result can be easily obtained by constructive algorithm: take these most appearing boxes, put smaller boxes in decreasing order of their size into free ones (there always be space) and put resulting boxes into t... | [
"greedy"
] | 1,200 | null |
903 | D | Almost Difference | Let's denote a function
$d(x,y)=\left\{y-x,\quad\mathrm{if}\ |x-y|>1$
You are given an array $a$ consisting of $n$ integers. You have to calculate the sum of $d(a_{i}, a_{j})$ over all pairs $(i, j)$ such that $1 ≤ i ≤ j ≤ n$. | Starting pretty boring this came out as the most fun and controversial problem of the contest... Well, here is the basis of the solution. You maintain some kind of map/hashmap with amounts each number appeared in array so far. Processing each number you subtract $a_{i}$ $i$ times ($1$-indexed), add prefix sum up to $(i... | [
"data structures",
"math"
] | 2,200 | null |
903 | E | Swapping Characters | We had a string $s$ consisting of $n$ lowercase Latin letters. We made $k$ copies of this string, thus obtaining $k$ identical strings $s_{1}, s_{2}, ..., s_{k}$. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the s... | If we don't have two distinct strings then we just have to swap any pair of characters in any of the given strings and print it. Otherwise we have to find two indices $i$ and $j$ such that $s_{i} \neq s_{j}$. Then let's store all positions $p$ such that $s_{i, p} \neq s_{j, p}$ in array $pos$. If the number of thos... | [
"brute force",
"hashing",
"implementation",
"strings"
] | 2,200 | null |
903 | F | Clear The Matrix | You are given a matrix $f$ with $4$ rows and $n$ columns. Each element of the matrix is either an asterisk (*) or a dot (.).
You may perform the following operation arbitrary number of times: choose a square submatrix of $f$ with size $k × k$ (where $1 ≤ k ≤ 4$) and replace each element of the chosen submatrix with a ... | Constraints lead us to some kind of dp solution (is it usually called dp on broken profile?). Let $dp[i][j][mask]$ will be the minimum price to get to $i$-th column and $j$-th row with $mask$ selected. $mask$ is the previous $12$ cells inclusive from $(i, j)$ (if $j = 4$ then its exactly current column and two previous... | [
"bitmasks",
"dp"
] | 2,200 | null |
903 | G | Yet Another Maxflow Problem | In this problem you will have to deal with a very special network.
The network consists of two parts: part $A$ and part $B$. Each part consists of $n$ vertices; $i$-th vertex of part $A$ is denoted as $A_{i}$, and $i$-th vertex of part $B$ is denoted as $B_{i}$.
For each index $i$ ($1 ≤ i < n$) there is a directed ed... | First of all, let's calculate minimum cut instead of maximum flow. The value of the cut is minimum if we choose $S$ (the first set of the cut) as $x$ first vertices of part $A$ and $y$ first vertices of part $B$ ($1 \le x \le n$, $0 \le y < n$). That's because if $i$ is the minimum index such that $A_{i}\notin S$... | [
"data structures",
"flows",
"graphs"
] | 2,700 | null |
906 | A | Shockers | Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac... | From last action, selected letter can be found; let it be $c$ (without loss of generality). For each of other $25$ letters, answers on some actions are contradicting with assumption that this letter was selected; moreover, for each letter $d$ not equal to $c$, we can find the earlest such action with number $A_{d}$ (fo... | [
"implementation",
"strings"
] | 1,600 | null |
906 | B | Seating of Students | Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
The class can be represented as a matrix with $n$ rows and $m$... | The problem has many solutions, including random ones. Consider one of deterministic solutions. Without loss of generality, assume that $n \le m$. There are a couple of corner cases: $n = 1, m = 1$. In this case, good seating exists. $n = 1, m = 2$. In this case, seating does not exist (obviously). $n = 1, m = 3$. In... | [
"brute force",
"constructive algorithms",
"math"
] | 2,200 | null |
906 | C | Party | Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.
At each step he selects... | Let's formulate and prove several facts. 1. If we change an call order, the result doesn't change. Let's consider two vertices which are called consecutively. If they are not connected by edge, then regardless of the order, we get that at the end, neighbours of each vertex form a clique. If they are connected, then ind... | [
"bitmasks",
"brute force",
"dp",
"graphs"
] | 2,400 | null |
906 | D | Power Tower | Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from $k - 1$ rocks, possesses power $p$ and we wan... | Let's learn to calculate $a_{1}^{a_{2}^{\ldots a n}}\mathrm{\\\,mod{\}}m$. Assume that we want to find $n^{x}\ {\mathrm{mod}}\ m$ where $n$ and $m$ non necessary co-prime, and $x$ is some big number which we can calculate only modulo some value. We can solve this problem for co-prime $n$ and $m$ via Euler's theorem. Le... | [
"chinese remainder theorem",
"math",
"number theory"
] | 2,700 | null |
906 | E | Reverses | Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing mini... | After inverses we have transform $A_{1}B_{1}A_{2}B_{2}... A_{k}B_{k}A_{k + 1} \rightarrow A_{1}B_{1}^{r}A_{2}B_{2}^{r}... A_{k}B_{k}^{r}A_{k + 1}$. Consider operator $mix(A, B) = a_{1}b_{1}a_{2}b_{2}... a_{n}b_{n}$ for strings of equal lengths. Under such operator string will turn into $X_{1}Y_{1}X_{2}Y_{2}... X_{k}Y... | [
"dp",
"string suffix structures",
"strings"
] | 3,300 | null |
907 | A | Masha and Bears | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg... | Sizes of cars should satisfy the following constraints: in $i$-th car, Masha and corresponding bear are able to get into, so size of the car should not be less than $max(V_{i}, V_{m})$; each bear likes its car, so size of $i$-th car is no more than $2 \cdot V_{i}$; Masha doesn't like first two cars, then their sizes ar... | [
"brute force",
"implementation"
] | 1,300 | null |
907 | B | Tic-Tac-Toe | Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
Players are making moves by turns. At first move a player can put his chip in any cell of any small field... | Let us describe each cell of the field by four numbers $(x_{b}, y_{b}, x_{s}, y_{s})$, $0 \le x_{b}, y_{b}, x_{s}, y_{s} \le 2)$, where $(x_{b}, y_{b})$ are coordinates of small field containing the cell, and $(x_{s}, y_{s})$ are coordinates of the cell in it's small field. It can be seen that for cell with "usual"... | [
"implementation"
] | 1,400 | null |
908 | A | New Year and Counting Cards | Your friend has $n$ cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a c... | Let's start off a bit more abstractly. We would like to know if the statement "if P then Q" is true, where P and Q are some statements (in this case, P is "card has vowel", and Q is "card has even number"). To do determine this, we need to flip over any cards which could be counter-examples (i.e. could make the stateme... | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
signed main() {
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
#endif
string s;
cin >> s;
int res = 0;
string v = "aeiou";
for (auto c : s) {
if (find(v.begin(), v.end(), c) != v.end() || (isdigit(c) && (... |
908 | B | New Year and Buggy Bot | Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex... | This problem is intended as an implementation problem. The bounds are small enough that a brute force works. We can iterate through all mapping of numbers to directions (i.e. using next permutation in C++ or doing some recursive DFS if there is no built in next permutation in your language), and simulate the robot's mo... | [
"brute force",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const int maxn = 55;
string s[maxn];
signed main() {
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
#endif
int n, m;
cin >> n >> m;
int sx = -1, sy = -1;
for (int i = 0; i < n; ++i) {
cin >> s[i];
for... |
908 | C | New Year and Curling | Carol is currently curling.
She has $n$ disks each with radius $r$ on the 2D plane.
Initially she has all these disks above the line $y = 10^{100}$.
She then will slide the disks towards the line $y = 0$ one by one in order from $1$ to $n$.
When she slides the $i$-th disk, she will place its center at the point $(x... | This is another simulation problem with some geometry. As we push a disk, we can iterate through all previous disks and see if their $x$-coordinates are $ \le 2r$. If so, then that means these two circles can possibly touch. If they do, we can compute the difference of heights between these two circles using pythagore... | [
"brute force",
"geometry",
"implementation",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const int maxn = 2018;
ld x[maxn];
ld y[maxn];
signed main() {
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
#endif
cout << fixed;
cout.precision(10);
int n;
ld r;
cin >> n >> r;
for (int i = 0; i < n; +... |
908 | D | New Year and Arbitrary Arrangement | You are given three integers $k$, $p_{a}$ and $p_{b}$.
You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability $p_{a} / (p_{a} + p_{b})$, add 'a' to the end of the sequence. Otherwise (with probability $p_{b} / (p_{a} + p... | The main trickiness of this problem is that the sequence could potentially get arbitrary long, but we want an exact answer. In particular, it helps to think about how to reduce this problem to figuring out what state we need to maintain from a prefix of the sequence we've built in order to simulate our algorithm correc... | [
"dp",
"math",
"probabilities"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const int mod = 1e9 + 7;
template<typename T>
T add(T x) {
return x;
}
template<typename T, typename... Ts>
T add(T x, Ts... y) {
T res = x + add(y...);
if (res >= mod)
res -= mod;
return res;
}
template<typename T... |
908 | E | New Year and Entity Enumeration | You are given an integer $m$.
Let $M = 2^{m} - 1$.
You are also given a set of $n$ integers denoted as the set $T$. The integers will be provided in base 2 as $n$ binary strings of length $m$.
A set of integers $S$ is called "good" if the following hold.
- If $a\in S$, then $a\mathrm{\XOR}\,\,M\in S$.
- If $a.b\in ... | Let's ignore $T$ for now, and try to characterize good sets $S$. For every bit position $i$, consider the bitwise AND of all elements of $S$ which have the $i$-th bit on (note, there is at least one element in $S$ which has the $i$-th bit on, since we can always $\mathrm{XOR}$ by $m$). We can see that this is equivalen... | [
"bitmasks",
"combinatorics",
"dp",
"math"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const int mod = 1e9 + 7;
template<typename T>
T add(T x) {
return x;
}
template<typename T, typename... Ts>
T add(T x, Ts... y) {
T res = x + add(y...);
if (res >= mod)
res -= mod;
return res;
}
template<typename T... |
908 | F | New Year and Rainbow Roads | Roy and Biv have a set of $n$ points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it... | Let's make a few simplifying observations It is not optimal to connect a red and blue point directly: Neither Roy or Biv will see this edge. If we have a sequence like red green red (or similarly blue green blue), it is not optimal to connect the outer two red nodes. We can replace the outer edge with two edges that ha... | [
"graphs",
"greedy",
"implementation"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
signed main() {
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
#endif
int n;
cin >> n;
ll pr = -1e12;
ll gmin = 1e12, gmax = -1e12;
ll bmin = 1e12, bmax = -1e12;
ll rmin = 1e12, rmax = -1e12;
vector<int> ... |
908 | G | New Year and Original Order | Let $S(n)$ denote the number that represents the digits of $n$ in sorted order. For example, $S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555$.
Given a number $X$, compute $\textstyle\sum_{1\leq k\leq X}S(k)$ modulo $10^{9} + 7$. | This is a digit dp problem. Let's try to solve the subproblem "How many ways can the i-th digit be at least j?". Let's fix j, and solve this with dp. We have a dp state dp[a][b][c] = number of ways given we've considered the first $a$ digits of $X$, we need $b$ more occurrences of digits at least $j$, and $c$ is a bool... | [
"dp",
"math"
] | 2,800 | // vvvvvvvvvvvvvvvvv Library code start
#define NDEBUG
NDEBUG
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstring>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <t... |
908 | H | New Year and Boolean Bridges | Your friend has a hidden directed graph with $n$ nodes.
Let $f(u, v)$ be true if there is a directed path from node $u$ to node $v$, and false otherwise. For each pair of distinct nodes, $u, v$, you know at least one of the three statements is true:
- $f(u,v)\ \mathrm{AND}\ f(v,u)$
- $f(u,v)\ \mathrm{OR}\ \,f(v,u)$
-... | First, let's find connected components using only AND edges. If there are any XOR edges between two nodes in the same component, the answer is -1. Now, we can place all components in a line. However, it may be optimal to merge some components together. It only makes sense to merge components of size 2 or more, of which... | [] | 3,100 | // vvvvvvvvvvvvvvvvv Library code start
#define NDEBUG
NDEBUG
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstring>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <t... |
909 | A | Generate Login | The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and ... | The most straightforward solution is to generate all possible logins (by trying all non-empty prefixes of first and last names and combining them) and find the alphabetically earliest of them. To get a faster solution, several observations are required. First, in the alphabetically earliest login the prefix of the last... | [
"brute force",
"greedy",
"sortings"
] | 1,000 | null |
909 | B | Segments | You are given an integer $N$. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and $N$, inclusive; there will be $\textstyle{\frac{n(n+1)}{2}}$ of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (t... | Consider a segment $[i, i + 1]$ of length 1. Clearly, all segments that cover this segment must belong to different layers. To cover it, the left end of the segment must be at one of the points $0, 1, ..., i$ ($i + 1$ options), and the right end - at one of the points $i + 1, i + 2, ..., N$ ($N - i$ options). So the nu... | [
"constructive algorithms",
"math"
] | 1,300 | null |
909 | C | Python Indentation | In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
\textbf{Simple statements} are written in a single line, one per li... | This problem can be solved using dynamic programming. Let's consider all possible programs which end with a certain statement at a certain indent. Dynamic programming state will be an array $dp[i][j]$ which stores the number of such programs ending with statement $i$ at indent $j$. The starting state is a one-dimension... | [
"dp"
] | 1,800 | null |
909 | D | Colorful Points | You are given a set of points on a straight line. Each point has a color assigned to it. For point $a$, its neighbors are the points which don't have any other points between them and $a$. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set ... | We can simulate the process described in the problem step by step, but this is too slow - a straightforward simulation (iterate over all points when deciding which ones to delete) has an $O(N^{2})$ complexity and takes too long. A solution with better complexity is required. Let's consider continuous groups of points o... | [
"data structures",
"greedy",
"implementation"
] | 2,100 | null |
909 | E | Coprocessor | You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depen... | We want to minimize the number of communications between main processor and the coprocessor. Thus, we need to always act greedily: while there are tasks that can be executed on the main processor right away, execute them; then switch to the coprocessor and execute all tasks that can be executed there; then switch back ... | [
"dfs and similar",
"dp",
"graphs",
"greedy"
] | 1,900 | null |
909 | F | AND-permutations | Given an integer $N$, find two permutations:
- Permutation $p$ of numbers from 1 to $N$ such that $p_{i} ≠ i$ and $p_{i} & i = 0$ for all $i = 1, 2, ..., N$.
- Permutation $q$ of numbers from 1 to $N$ such that $q_{i} ≠ i$ and $q_{i} & i ≠ 0$ for all $i = 1, 2, ..., N$.
$&$ is the bitwise AND operation. | If $N$ is odd, the answer is NO. Indeed, any number in odd-numbered position $i$ $p_{i}$ must be even, otherwise the last bit of $p_{i}&i$ is 1. For odd $N$ there are less even numbers than odd-numbered positions, so at least one of the positions will hold an odd number, thus it's impossible to construct a required per... | [
"constructive algorithms"
] | 2,500 | null |
911 | A | Nearest Minimums | You are given an array of $n$ integer numbers $a_{0}, a_{1}, ..., a_{n - 1}$. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. | This task can be done by one array traversal. Maintain $cur$ - current minimum value, $pos$ - position of the last occurrence of $cur$, $ans$ - current minumum distance between two occurrences of $cur$. Now for each $i$ if $a_{i} < cur$ then do $cur: = a_{i}$, $pos: = i$, $ans: = \infty $. For $a_{i} = cur$ do $ans = ... | [
"implementation"
] | 1,100 | null |
911 | B | Two Cakes | It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into $a$ pieces, and the second one — into $b$ pieces.
Ivan knows that there will be $n$ people at the celebration (including himself), so Ivan has set ... | Let's fix $x$ - number of plates to have pieces of the first cake. $n - x$ plates left for the other cake. Obviously, the most optimal way to distribute $a$ pieces to $x$ plates will lead to the minimum of $\left\lfloor{\frac{\Omega}{x}}\right\rfloor$ pieces on a plate. Now try every possible $x$ and take maximum of $m... | [
"binary search",
"brute force",
"implementation"
] | 1,200 | null |
911 | C | Three Garlands | Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if $i$-th garland is switched on during $x$-th s... | There are pretty few cases to have YES: One of $k_{i}$ is equal to $1$; At least two of $k_{i}$ are equal to $2$; All $k_{i}$ equal $3$; $k = {2, 4, 4}$. It's easy to notice that having minimum of $k_{i}$ equal to $3$ produce the only case, greater numbers will always miss some seconds. Let's consider minimum of $2$, l... | [
"brute force",
"constructive algorithms"
] | 1,400 | null |
911 | D | Inversion Counting | A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_{i} < a_{j}$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1... | Permutaion with one swap is called transposition. Any permutation can be expressed as the composition (product) of transpositions. Simpler, you can get any permutation from any other one of the same length by doing some number of swaps. The sign of the permutation is the number of transpositions needed to get it from t... | [
"brute force",
"math"
] | 1,800 | null |
911 | E | Stack Sorting | Let's suppose you have an array $a$, a stack $s$ (initially empty) and an array $b$ (also initially empty).
You may perform the following operations until both $a$ and $s$ are empty:
- Take the first element of $a$, push it into $s$ and remove it from $a$ (if $a$ is not empty);
- Take the top element from $s$, append... | Let's denote $A(l, r)$ as some stack-sortable array which contains all integers from $l$ to $r$ (inclusive). We can see that if the first element of $A(l, r)$ is $x$, then $A(l, r) = [x] + A(l, x - 1) + A(x + 1, r)$, where by $+$ we mean concatenation of arrays. It's easy to prove this fact: if the first element is $x$... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 2,000 | null |
911 | F | Tree Destruction | You are given an unweighted tree with $n$ vertices. Then $n - 1$ following operations are applied to the tree. A single operation consists of the following steps:
- choose two leaves;
- add the length of the simple path between them to the answer;
- remove one of the chosen leaves from the tree.
Initial answer (befor... | The solution is to choose some diameter of given tree, then delete all the leaves which don't belong to diameter (iteratively), and then delete the diameter. I.e. while tree includes vertices aside from the ones forming diameter we choose some leaf, increase answer by the length of the path between this leaf and farthe... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | 2,400 | null |
911 | G | Mass Change Queries | You are given an array $a$ consisting of $n$ integers. You have to process $q$ queries to this array; each query is given as four numbers $l$, $r$, $x$ and $y$, denoting that for every $i$ such that $l ≤ i ≤ r$ and $a_{i} = x$ you have to set $a_{i}$ equal to $y$.
Print the array after all queries are processed. | We can represent a query as a function $f$: $f(i) = i$ if $i \neq x$, $f(x) = y$. If we want to apply two functions, then we can calculate a composition of these functions in time $O(max a_{i})$; in this problem $max a_{i}$ is $100$. So we can do the following: Use scanline technique. Build a segment tree over querie... | [
"data structures"
] | 2,500 | null |
912 | A | Tricky Alchemy | During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already $2018$, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a \textbf{yellow} ball one needs ... | Note that the crystals of each color are bought independently. One needs $2 \cdot x + y$ yellow and $3 \cdot z + y$ blue crystals. The answer therefore is $max(0, 2 \cdot x + y - A) + max(0, 3 \cdot z + y - B)$. | [
"implementation"
] | 800 | a, b = map(int, input().split())
x, y, z = map(int, input().split())
yellow = 2 * x + y
blue = y + 3 * z
ans = max(0, yellow - a) + max(0, blue - b)
print(ans) |
912 | B | New Year's Eve | Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains $n$ sweet candies from the good ol' bakery, each labeled from $1$ to $n$ corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a... | If $k = 1$, the answer is $n$. Otherwise, let's take a look at the most significant bit of answer and denote it by $p$ (with the $0$-th bit being the least possible). It must be the same as the most significant bit of $n$. This means the answer cannot exceed $2^{p + 1} - 1$. Consider the numbers $2^{p}$ and $2^{p} - 1$... | [
"bitmasks",
"constructive algorithms",
"number theory"
] | 1,300 | import sys
n, k = map(int, input().split())
if k == 1:
print(n)
sys.exit(0)
# Calculate 2^(p+1) - 1 using recursive formula
ans = 1
while ans < n:
ans = ans * 2 + 1
print(ans) |
912 | C | Perun, Ult! | A lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerines — the leftovers from New Year celebration — he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun.
Perun has an ultimate abi... | The statement almost directly states the formula for the answer - it is calculated as $\operatorname*{max}_{t\in[0,+\infty)}f(t)\cdot(b o u n t y+i n c r e a s e\cdot t)$, where $f(t)$ is amount of enemies we can kill at $t$-th second. Thus, we need to learn how to calculate $f(t)$ and find such values of $t$ that are ... | [
"brute force",
"greedy",
"sortings"
] | 2,500 | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <unordered_set>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include <queue>
#include <numeric>
#include <bitset>
... |
912 | D | Fishes | While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size $n × m$, divided into cells of size $1 × 1$, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).
The gift bundle also includes a square scoop of size $r × r$, designed for fi... | Let's solve a simplified problem first. Assume we know all fishes' positions $(x_{i}, y_{i})$ ($1$-indexed). Denote as $g(x, y)$ the amount of fish that is inside a scoop with lower-left angle located at $(x, y)$. Then the expected value is equal to: ${\bf E}={\frac{1}{(n-r+1)\cdot(m-r+1)}}\cdot\sum_{x=1}^{n-r+1\cdot m... | [
"data structures",
"graphs",
"greedy",
"probabilities",
"shortest paths"
] | 2,100 | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include <queue>
#include <numeric>
#include <bitset>
using namespace std;
c... |
912 | E | Prime Gift | Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of $n$ \textbf{distinct prime} numbers alongsi... | The initial idea that emerges in such kind of problems is to use binary search to determine the $k$-th element. Still we have to somehow answer the following query: "how many elements no greater than $x$ satisfy the conditions?" It's easy to see that all such numbers can be represented as $p_{1}^{a1} \cdot ... \cdot p_... | [
"binary search",
"dfs and similar",
"math",
"meet-in-the-middle",
"number theory",
"two pointers"
] | 2,400 | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <unordered_set>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include <queue>
#include <numeric>
#include <bitset>
... |
913 | A | Modular Exponentiation | The following problem is well-known: given integers $n$ and $m$, calculate
\begin{center}
$2^{n}\operatorname{mod}m$,
\end{center}
where $2^{n} = 2·2·...·2$ ($n$ factors), and $x\ {\mathrm{mod}}\ y$ denotes the remainder of division of $x$ by $y$.
You are asked to solve the "reverse" problem. Given integers $n$ and ... | Why is it hard to calculate the answer directly by the formula in the problem statement? The reason is that $2^{n}$ is a very large number, for $n = 10^{8}$ it consists of around 30 million decimal digits. (Anyway, it was actually possible to get the problem accepted directly calculating the result in Python or Java us... | [
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
scanf("%d %d", &n, &m);
printf("%d\n", n >= 31 ? m : m % (1 << n));
return 0;
} |
913 | B | Christmas Spruce | Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex $u$ is called a child of vertex $v$ and vertex $v$ is called a parent of vertex $u$ if there exists a directed edge from $v$ to $u$. A vertex is called a leaf if it doesn't have children and has a ... | Lets calculate amount of children for each vertex. To do that lets increase by $1$ $c[p_{i}]$ for every $p_{i}$. Then iterate over all vertexes. If $i$-th vertex has $0$ children (i.e. $c[i] = 0$), skip this vertex. Else again iterate over all vertexes and calculate number of vertexes $j$ such that $c[j] = 0$ and $p_{j... | [
"implementation",
"trees"
] | 1,200 | n = int(input())
p = [int(input()) - 1 for _ in range(n - 1)]
leafs = list(filter(lambda x: not x in p, range(n)))
lp = [x for i, x in enumerate(p) if i + 1 in leafs]
x = min(lp.count(k) for k in p)
print("Yes" if x >= 3 else "No") |
913 | C | Party Lemonade | A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of $n$ different volumes at different costs. A single bottle of type $i$ has volume $2^{i - 1}$ liters and c... | Note that if $2 \cdot a_{i} \le a_{i + 1}$, then it doesn't make sense to buy any bottles of type $i + 1$ - it won't ever be worse to buy two bottles of type $i$ instead. In this case let's assume that we actually have an option to buy a bottle of type $i + 1$ at the cost of $2 \cdot a_{i}$ and replace $a_{i + 1}$ wi... | [
"bitmasks",
"dp",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, L;
scanf("%d %d", &n, &L);
vector<int> c(n);
for (int i = 0; i < n; i++) {
scanf("%d", &c[i]);
}
for (int i = 0; i < n - 1; i++) {
c[i + 1] = min(c[i + 1], 2 * c[i]);
}
long long ans = (long long) 4e18;
long long sum = 0;
fo... |
913 | D | Too Easy Problems | You are preparing for an exam on scheduling theory. The exam will last for exactly $T$ milliseconds and will consist of $n$ problems. You can either solve problem $i$ in exactly $t_{i}$ milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.
Unfortunately, your teacher... | The first observation is that if we solve a problem which doesn't bring us any points, we could as well ignore it and that won't make our result worse. Therefore, there exists an answer in which all problems we solve bring us points. Let's consider only such answers from now on. Fix $k$. How to check if we can get exac... | [
"binary search",
"brute force",
"data structures",
"greedy",
"sortings"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, T;
scanf("%d %d", &n, &T);
vector< vector< pair<int, int> > > at(n + 1);
for (int i = 0; i < n; i++) {
int foo, bar;
scanf("%d %d", &foo, &bar);
at[foo].emplace_back(bar, i);
}
vector<int> res;
set< pair<int, int> > s;
int s... |
913 | E | Logical Expression | You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
- Operation AND ('&', ASCII code 38)
- Operation OR ('|', ASCII code 124)
- Operation NOT ('!', ASCII code 33)
- Variabl... | The number of functions of three variables is $2^{23} = 256$. Note that for an expression, we're only interested in its truth table and the nonterminal from which this expression can be formed. So, there are $3 \cdot 256$ different states. And the problem is to find an expression of minimum length, and the lexicographi... | [
"bitmasks",
"dp",
"shortest paths"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
string res[256][3];
bool changed;
void update(string &a, string &b) {
if (a == "" || (b.length() < a.length() || (b.length() == a.length() && b < a))) {
changed = true;
a = b;
}
}
int main() {
res[(1 << 4) + (1 << 5) + (1 << 6) + (1 << 7)][0] = "x";
res[... |
913 | F | Strongly Connected Tournament | There is a chess tournament in All-Right-City. $n$ players were invited to take part in the competition. The tournament is held by the following rules:
- Initially, each player plays one game with every other player. There are no ties;
- After that, the organizers build a complete directed graph with players as vertic... | Probability of player $i$ to win player $j$ depends on whether $i < j$ only, so the answer for subset of players of size $s$ doesn't depend on the set, only on its size. Let $ans(s)$ be the answer for set of $s$ players. Lets calculate the answer using dynamic programming. $ans(0) = ans(1) = 0$. For larger $s$ lets use... | [
"dp",
"graphs",
"math",
"probabilities"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int md = 998244353;
inline void add(int &a, int b) {
a += b;
if (a >= md) a -= md;
}
inline void sub(int &a, int b) {
a -= b;
if (a < 0) a += md;
}
inline int mul(int a, int b) {
return (int) ((long long) a * b % md);
}
inline int power(int a, long lon... |
913 | G | Power Substring | You are given $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$.
For every $a_{i}$ you need to find a positive integer $k_{i}$ such that the decimal notation of $2^{ki}$ contains the decimal notation of $a_{i}$ as a substring among its last $min(100, length(2^{ki}))$ digits. Here $length(m)$ is the length of the decima... | Lets solve the problem for every $a_{i}$ separately. Let $n = length(a_{i})$. Let us choose $m$ and $b$ such that $0 \le b < 10^{m}$. Lets find $k$ such that decimal notation of $2^{k}$ ends with $x = a_{i} \cdot 10^{m} + b$. Equation $2^{k}\equiv x\mathrm{~~mod~}10^{n+m}$ is necessary and sufficient for that. Lets f... | [
"math",
"number theory"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
inline long long mul(long long a, long long b, long long md) {
long long res = 0;
while (b > 0) {
if (b & 1) {
res += a; if (res >= md) res -= md;
}
a += a; if (a >= md) a -= md;
b >>= 1;
}
return res;
}
inline long long power(long long a, l... |
913 | H | Don't Exceed | You generate real numbers $s_{1}, s_{2}, ..., s_{n}$ as follows:
- $s_{0} = 0$;
- $s_{i} = s_{i - 1} + t_{i}$, where $t_{i}$ is a real number chosen independently uniformly at random between 0 and 1, inclusive.
You are given real numbers $x_{1}, x_{2}, ..., x_{n}$. You are interested in the probability that $s_{i} ≤ ... | If $t_{i}$ were random integers and not reals, it would be natural to solve the problem using dynamic programming: $f(i, j)$ - the probability that the required inequalities are satisfied if $s_{i} = j$. But in case of real numbers, the probability that a random real number equals to something is zero. What to do then?... | [
"math",
"probabilities"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
const int md = 998244353;
inline void add(int &a, int b) {
a += b;
if (a >= md) a -= md;
}
inline void sub(int &a, int b) {
a -= b;
if (a < 0) a += md;
}
inline int mul(int a, int b) {
return (int) ((long long) a * b % md);
}
inline int power(int a, long lon... |
914 | A | Perfect Squares | Given an array $a_{1}, a_{2}, ..., a_{n}$ of $n$ integers, find the largest number in the array that is not a perfect square.
A number $x$ is said to be a perfect square if there exists an integer $y$ such that $x = y^{2}$. | For each number, check whether the number is a square or not (by checking factors smaller than the square root of the number or using sqrt function). The answer is the largest number which isn't a square. (negative numbers can't be squares) Make sure you initialize your max variable to $- 10^{6}$ instead of $0$. | [
"brute force",
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main()
{
long long ans=LLONG_MIN, n, x;
cin>>n;
for (long long i = 0; i < n; i++)
{
cin>>x;
for (long long j = 0; j*j<=x; j++)
if (j*j == x)
x = LLONG_MIN;
ans = max(ans, x);
}
cout << ans << endl;
return 0;
} |
914 | B | Conan and Agasa play a Card Game | Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has $n$ cards, and the $i$-th card has a number $a_{i}$ written on it.
They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he remo... | Let $A = max (a_{1}, a_{2}, ..., a_{n})$. Observe that if $A$ occurs an odd number of times, Conan can simply begin by removing one instance of $A$. If there are any cards left, they all have the same number $A$ on them. Now each player can only remove one card in their turn, and they take turns doing so. Since there w... | [
"games",
"greedy",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int cnt[100005];
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
while(n--) {
int x;
cin >> x;
cnt[x]++;
}
for (int i = 1; i <= 1e5; i++) {
if (cnt[i] % 2 == 1) {
cout << "Conan\n";
return 0;
}... |
914 | C | Travelling Salesman and Special Numbers | The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer $x$ and reduce it to the number of bits set to $1$ in the binary representation of $x$. For example for number $13$ it's true that $... | Let us denote the minimum number of steps it takes to reduce a number to $1$ as the order of that number. Since the number of set bits in numbers smaller than $2^{1000}$ is less than $1000$, any number smaller than $2^{1000}$ would reduce to a number less than $1000$ in one step. We can precompute the order of the firs... | [
"brute force",
"combinatorics",
"dp"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
int dp[1004];
long long ncr[1004][1004];
int ones(int n)
{
int cnt = 0;
while(n)
{
if(n%2 == 1)
{
cnt++;
}
n /= 2;
}
return cnt;
}
void calcncr()
{
for(int i = 0; i <= 1000; i++)
{
ncr[i][0] = 1;
}
for(... |
914 | D | Bash and a Tough Math Puzzle | Bash likes playing with arrays. He has an array $a_{1}, a_{2}, ... a_{n}$ of $n$ integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.
Suppose he guesses that the g... | Build a segment tree on the array to answer range gcd queries. We can handle single element updates in the segment tree. Let us see how to answer an $(l, r, x)$ query. The segment tree decomposes the query range into $O(logn)$ nodes that cover the range. If the gcds of all of these nodes are multiples of $x$, then the ... | [
"data structures",
"number theory"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int tree[2000000];
int trstp = 1;
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
void query(int root, int u, int v, int x, int s, int e, int& ans) {
if (e < s || v < u || e < u || v < s) {
return;
} else if (u <= s && e <= v)... |
914 | E | Palindromes in a Tree | You are given a tree (a connected acyclic undirected graph) of $n$ vertices. Vertices are numbered from $1$ to $n$ and each vertex is assigned a character from a to t.
A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.
For each vertex, output the number... | The problem can be solved by centroid decomposition. A path will be palindromic at most one letter appears odd number of times in the path. We maintain a bitmask for each node, where $i$-th bit is $1$ if the $i$-th character occurs odd number of times, otherwise $0$. The path from $u$ to $v$ is valid if mask[$u$] ^ mas... | [
"bitmasks",
"data structures",
"divide and conquer",
"trees"
] | 2,400 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define db long double
#define ii pair<int,int>
#define vi vector<int>
#define fi first
#define se second
#define sz(a) (int)(a).size()
#define al... |
914 | F | Substrings in a String | Given a string $s$, process $q$ queries, each having one of the following forms:
- $1 i c$ — Change the $i$-th character in the string to $c$.
- $2 l r y$ — Consider the substring of $s$ starting at position $l$ and ending at position $r$. Output the number of times $y$ occurs as a substring in it. | Let $N = |s|$. Divide the given string into blocks of size $K={\sqrt{N}}$ and use any suffix structure for each block. Complexity: $O(|s|)$. To update a character in the string, rebuild a suffix structure for that block. This takes $O(K)$ per update. We answer queries as follows. Remember that it's given that the total... | [
"bitmasks",
"brute force",
"data structures",
"string suffix structures",
"strings"
] | 3,000 | #include <bits/stdc++.h>
#define fr(x) scanf("%d", &x)
#define SQRN 150
using namespace std;
const int sa = 2 * SQRN + 10;
const int LEN = 100010;
char s[LEN], sq[LEN], zstring[2*LEN];
int z[2*LEN];
string temps;
struct SuffixAutomaton {
int edges[26][sa], link[sa], length[sa], isTerminal[sa], dp1[sa], last;
int ... |
914 | G | Sum the Fibonacci | You are given an array $s$ of $n$ non-negative integers.
A 5-tuple of integers $(a, b, c, d, e)$ is said to be valid if it satisfies the following conditions:
- $1 ≤ a, b, c, d, e ≤ n$
- $(s_{a}$ | $s_{b})$ & $s_{c}$ & $(s_{d}$ ^ $s_{e}) = 2^{i}$ for some integer $i$
- $s_{a}$ & $s_{b} = 0$
Here, '|' is the bitwise ... | Apologies, we didn't expect an $O(3^{17})$ solution. The expected solution was as follows. Let $A[i]$ be the number of pairs $(x, y)$ in the array such that their bitwise OR is $i$ and $x&y = 0$, multiplied by $Fib[i]$. This can be done using subset convolution. Let $B[i]$ be the count of each element in array, multipl... | [
"bitmasks",
"divide and conquer",
"dp",
"fft",
"math"
] | 2,600 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define db long double
#define ii pair<int,int>
#define vi vector<int>
#define fi first
#define se second
#define sz(a) (int)(a).size()
#define al... |
914 | H | Ember and Storm's Tree Game | Ember and Storm play a game. First, Ember picks a labelled tree $T$ of $n$ vertices, such that the degree of every vertex is at most $d$. Then, Storm picks two distinct vertices $u$ and $v$ in this tree and writes down the labels of the vertices in the path from $u$ to $v$ in a sequence $a_{1}, a_{2}... a_{k}$. Finally... | Ember wins if the path chosen by Storm is monotonic or bitonic. In this case, there can be two $(i, op)$ pairs. Let $S$ be the set of trees having $n$ vertices in which all paths are bitonic or monotonic. We need to find $2n(n - 1)|S|$. For every tree in $S$, there exists at least one vertex such that every path starti... | [
"combinatorics",
"dp",
"games",
"trees"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll mod;
const int maxn = 2e2 + 2;
ll tree[maxn][maxn][maxn];
ll c[maxn][maxn];
int main() {
ios::sync_with_stdio(false);
int n, d;
cin >> n >> d >> mod;
c[0][0] = 1;
for (int i = 1; i <= n; i++) {
c[i][0] = 1;
for (int j = 1; j <=... |
915 | A | Garden | Luba thinks about watering her garden. The garden can be represented as a segment of length $k$. Luba has got $n$ buckets, the $i$-th bucket allows her to water some continuous subsegment of garden of length \textbf{exactly} $a_{i}$ each hour. \textbf{Luba can't water any parts of the garden that were already watered, ... | In this problem we just need to find maximum divisor of $k$ that belongs to array $a$. Let's call it $r$. Then we need to print $\displaystyle{\frac{k}{r}}$. | [
"implementation"
] | 900 | null |
915 | B | Browser | Luba is surfing the Internet. She currently has $n$ opened tabs in her browser, indexed from $1$ to $n$ from left to right. The mouse cursor is currently located at the $pos$-th tab. Luba needs to use the tabs with indices from $l$ to $r$ (inclusive) for her studies, and she wants to close all the tabs that don't belon... | If $l = 1$ and $r = n$ then the answer is $0$. If $l = 1$ and $r \neq n$ or $l \neq 1$ and $r = n$ then answer is $|pos - l| + 1$ or $|pos - r| + 1$ respectively. And in the other case (when $l \neq 1$ and $r \neq n$) the answer is $r - l + min(|pos - l|, |pos - r|) + 2$. | [
"implementation"
] | 1,300 | null |
915 | C | Permute Digits | You are given two positive integer numbers $a$ and $b$. Permute (change order) of the digits of $a$ to construct maximal number not exceeding $b$. No number in input and/or output can start with the digit 0.
It is allowed to leave $a$ as it is. | Let's construct the answer digit by digit starting from the leftmost. Obviously, we are asked to build lexicographically maximal answer so in this order we should choose the greatest digit on each step. Precalc $cnt_{i}$ - number of digits $i$ in number $a$. Iterate over all possible digits starting from the greatest. ... | [
"dp",
"greedy"
] | 1,700 | null |
915 | D | Almost Acyclic Graph | You are given a directed graph consisting of $n$ vertices and $m$ edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't cont... | The constraits are set in such a way that naive $O(m \cdot (n + m))$ solution won't pass (unmark every edge one by one and check if graph of marked edges doesn't contain cycles with dfs/bfs). Thus we should somehow limit the number of edges to check. Let's take arbitrary cycle in graph. Do dfs, store the vertex you use... | [
"dfs and similar",
"graphs"
] | 2,200 | null |
915 | E | Physical Education Lessons | This year Alex has finished school, and now he is a first-year student of Berland State University. For him it was a total surprise that even though he studies programming, he still has to attend physical education lessons. The end of the term is very soon, but, unfortunately, Alex still hasn't attended a single lesson... | Let's store current intervals with non-working days in set sorted by the right border. When new query comes you search for the first interval to have its right border greater or equal than the currect left border and update all intervals to intersect the query (either fully delete or insert back its part which doesn't ... | [
"data structures",
"implementation",
"sortings"
] | 2,300 | null |
915 | F | Imbalance Value of a Tree | You are given a tree $T$ consisting of $n$ vertices. A number is written on each vertex; the number written on vertex $i$ is $a_{i}$. Let's denote the function $I(x, y)$ as the difference between maximum and minimum value of $a_{i}$ on a simple path connecting vertices $x$ and $y$.
Your task is to calculate $\sum_{i=1... | Let's calculate the answer as the difference between sum of maxima and sum of minima over all paths. These sums can be found by the following approach: Consider the sum of maxima. Let's sort all vertices in ascending order of values of $a_{i}$ (if two vertices have equal values, their order doesn't matter). This order ... | [
"data structures",
"dsu",
"graphs",
"trees"
] | 2,400 | null |
915 | G | Coprime Arrays | Let's call an array $a$ of size $n$ coprime iff $gcd(a_{1}, a_{2}, ..., a_{n}) = 1$, where $gcd$ is the greatest common divisor of the arguments.
You are given two numbers $n$ and $k$. For each $i$ ($1 ≤ i ≤ k$) you have to determine the number of coprime arrays $a$ of size $n$ such that for every $j$ ($1 ≤ j ≤ n$) $1... | For a fixed upper bound $i$, this is a well-known problem that can be solved using inclusion-exclusion: Let's denote by $f(j)$ the number of arrays with elements in range $[1, i]$ such that $gcd(a_{1}, ..., a_{n})$ is divisible by $j$. Obviously, $f(j)=(\lfloor{\frac{i}{j}}\rfloor)^{n}$. With the help of inclusion-excl... | [
"math",
"number theory"
] | 2,300 | null |
916 | A | Jamie and Alarm Snooze | Jamie loves sleeping. One day, he decides that he needs to wake up at exactly $hh: mm$. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every $x$ minutes until $hh: mm$ is reached, and only then he will wake up. He wants ... | Let's use brute force the find the answer. We first set the alarm time as $hh: mm$ and initialize the answer as 0. While the time is not lucky, set the alarm time to $x$ minute before and add 1 to the answer. Why does this solution run in time? As $x \le 60$, $hh$ decrease at most $1$ for every iteration. Also, after... | [
"brute force",
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
typedef long long lint; typedef pair<int, int> ii;
const int MOD = 1'000'000'007, MOD2 = 1'000'000'009;
const int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;
int x, n, m;
int solve(){
cin >> x >> n >> m;
int ti = n * 60 + m;
for(int i=0;;i++){
int h... |
916 | B | Jamie and Binary Sequence (changed after round) | Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find $k$ integers such that the sum of two to the power of each number equals to the number $n$ and the largest integer in the answer is as small as possible. ... | The main idea of the solution is $2^{x} = 2 \cdot 2^{x - 1}$, that means you can replace 1 $x$ element with 2 $(x - 1)$ elements. To start with, express $n$ in binary - powers of two. As we can only increase the number of elements, there is no solution if there exists more than $k$ elements. Let's fix the $y$ value fir... | [
"bitmasks",
"greedy",
"math"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long lint; typedef pair<int, int> ii;
const int MOD = 1'000'000'007, MOD2 = 1'000'000'009;
const int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;
lint n;
int m = 0, k;
map<int, int> cnt;
int solve(){
cin >> n >> k;
for(int i=0;i<=63;i++) ... |
916 | C | Jamie and Interesting Graph | Jamie has recently found undirected weighted graphs with the following properties very interesting:
- The graph is connected and contains exactly $n$ vertices and $m$ edges.
- All edge weights are integers and are in range $[1, 10^{9}]$ inclusive.
- The length of shortest path from $1$ to $n$ is a prime number.
- The ... | First, observe that only $n - 1$ edges are required to fulfil the requirement, so we will make the other $m - n + 1$ edges with a very large number so they would not contribute to the shortest path or the MST. Now, the problem is reduced to building a tree with prime weight sum and two nodes in the tree have prime dist... | [
"constructive algorithms",
"graphs",
"shortest paths"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
typedef long long lint; typedef pair<int, int> ii;
const int MOD = 1'000'000'007, MOD2 = 1'000'000'009;
const int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;
int n, m;
const int LPRIME = 100'003;
const int LNUM = 1'000'000'000;
int solve(){
cin >> n >> ... |
916 | D | Jamie and To-do List | Why I have to finish so many assignments???
Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment \textbf{(lower value means more important)} so he can decide wh... | Let's solve a version that does not consist of undo operation first. The task can be divided to two parts: finding the priority of a string and finding the rank of a priority. Both parts can be solved using trie trees. The first part is basic string trie with get and set operation so I will not describe it here in deta... | [
"data structures",
"interactive",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long lint; typedef pair<int, int> ii;
const int MOD = 1'000'000'007, MOD2 = 1'000'000'009;
const int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;
struct StringTrie{
StringTrie *chi[26];
int dat;
StringTrie(){
for(int i=0;i<26;i++) chi[... |
916 | E | Jamie and Tree | To your surprise, Jamie is the final boss! Ehehehe.
Jamie has given you a tree with $n$ vertices, numbered from $1$ to $n$. Initially, the root of the tree is the vertex with number $1$. Also, each vertex has a value on it.
Jamie also gives you three types of queries on the tree:
$1 v$ — Change the tree's root to ve... | Let's solve the problem without operation 1 first. That means the subtree of a vertex does not change. For operation 2, the subtree of smallest size that contains $u$ and $v$ means the lowest common ancestor ($lca$) of $u$ and $v$, and we update the subtree of $lca$. For operation 3, we query the sum of the subtree roo... | [
"data structures",
"trees"
] | 2,400 | #include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll arr[100010], seg_t[400010], seg_lazy[400010];
int ord[100010], uord[100010], dep[100010], subt_size[100010], ancs[100010][18], now_ord;
v... |
917 | A | The Monster | As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him.
Thus, he came up with a puzzle to tel... | First, let's denote $s[l..r]$ as the substring $s_{l}s_{l + 1}... s_{r}$ of string $s$. Also $s.count(t)$ is the number of occurrences of $t$ in $s$. A string consisting of parentheses and question marks is pretty if and only if: $|s|$ is even. $0 \le s[1..i].count('(') + s[1..i].count('?') - s[1..i].count(')')$ for ... | [
"dp",
"greedy",
"implementation",
"math"
] | 1,800 | null |
917 | B | MADMAX | As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with $n$ vertices and $m$ edges. There's a character written on each edge, a l... | Denote $dp(v, u, c)$ as the winner of the game (the person that starts it or the other one?, a boolean, true if first person wins) if the first person's marble is initially at vertex $v$ and the second one's initially at $u$ and our set of letters is ${ichar(c), ichar(c + 1), ..., 'z'}$ if $ichar(i) = char('a' + i)$ ($... | [
"dfs and similar",
"dp",
"games",
"graphs"
] | 1,700 | null |
917 | C | Pollywog | As we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and $x - 1$ other pollywogs are playing a game. There are $n$ stones in a row, numbered from $1$ through $n$ from left to right. At most $1$ pollywog may be sitting on each stone at a time. Initially... | What would we do if $n$ was small? Notice that at any given time if $i$ is the position of the leftmost pollywog and $j$ is the position of the rightmost pollywog, then $j - i < k$. Thus, at any given time there's an $i$ such that all pollywogs are on stones $i, i + 1, ... i + k - 1$, in other words, $k$ consecutive st... | [
"combinatorics",
"dp",
"matrices"
] | 2,900 | null |
917 | D | Stranger Trees | Will shares a psychic connection with the Upside Down Monster, so everything the monster knows, Will knows. Suddenly, he started drawing, page after page, non-stop. Joyce, his mom, and Chief Hopper put the drawings together, and they realized, it's a labeled tree!
A tree is a connected acyclic graph. Will's tree has $... | Solution #1: First, for every $K$ such that $0 \le K \le N - 1$ we are going to find for every $K$ edges in the original tree we are going to find the number of labeled trees having these $K$ edges, then we will add them all to $res[K]$. But Mr. Author aren't we going to count some tree that has exactly $E$ (where ... | [
"dp",
"math",
"matrices",
"trees"
] | 2,600 | null |
917 | E | Upside Down | As we all know, Eleven has special abilities. Thus, Hopper convinced her to close the gate to the Upside Down World with her mind. Upside down monsters like to move between the worlds, so they are going to attack Hopper and Eleven in order to make them stop. The monsters live in the vines. The vines form a tree with $n... | Assume $t_{i}$ is reverse of $s_{i}$. Use centroid-decomposition. When solving the problem for subtree $S$, assume its centroid is $c$. For a fixed query, assume $v$ and $u$ are both in $S$ and path from $v$ to $u$ goes through the centroid $c$ (this happens exactly one time for each $v$ and $u$). Assume $x$ is string ... | [
"data structures",
"string suffix structures",
"strings",
"trees"
] | 3,400 | null |
918 | A | Eleven | Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly $n$ characters.
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the $... | Calculate the first $x$ Fibonacci sequence elements, where $x$ is the greatest integer such that $f_{x} \le n$. Let $s$ be a string consisting of $n$ lowercase 'o' letters. Then for each $i \le x$, perform $s_{fi}$ = 'O'. The answer is $s$. Total time complexity: ${\mathcal{O}}(n)$ | [
"brute force",
"implementation"
] | 800 | null |
918 | B | Radio Station | As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has $n$ servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name o... | Save the names and ips of the servers. Then for each command find the server in ${\mathcal{O}}(n)$ and print its name. Total time complexity: $O(n m)$ | [
"implementation",
"strings"
] | 900 | null |
919 | A | Supermarket | We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what "yuan" is), the same as $a/b$ yuan for a kilo.
Now imagine you'd... | We can use greedy algorithm. Obviously, if you can pay the least money for per kilo, you can pay the least money for $m$ kilos. So you can find the minimum of $a_i/b_i$, we say it is $x$. Then $m \cdot x$ is the final answer. Time complexity: $\mathcal{O}(n)$. | [
"brute force",
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
#define N 5010
using namespace std;
int n, m, a[N], b[N];
int main(){
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++){
scanf("%d%d", &a[i], &b[i]);
}
int minA = a[1], minB = b[1];
for (int i = 2; i <= n; i++){
if (minA * b[i] > minB * a[i]){
minA = a[i];
minB = b[i];
}... |
919 | B | Perfect Number | We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer. | Let's use brute force the find the answer. You may find the answer is not too large (i.e. not bigger than $2 \cdot 10^7$), then you can find it in the given time limit. You can check every possible answer from $1$ (or from $19$), until we find the $k$-th perfect integer. That's all what we need to do. :P Time complexit... | [
"binary search",
"brute force",
"dp",
"implementation",
"number theory"
] | 1,100 | def cal(x):
ans = 0
while (x):
ans += x % 10
x /= 10
return ans
n = input()
now = 0
while (n):
now += 1
if cal(now) == 10:
n -= 1
print now |
919 | C | Seat Arrangements | Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.
The classroom contains $n$ rows of seat... | We can find out how many consecutive empty positions in every row and column separately and add them together to form the final answer. If the length of consecutive empty positions is no smaller than $k$, we assume that it is $len$. Then we can add $len-k+1$ to the final answer. But, be careful. When $k=1$, the algorit... | [
"brute force",
"implementation"
] | 1,300 | a = raw_input().split()
n, m, k = int(a[0]), int(a[1]), int(a[2])
mat = []
for i in range(n):
s = raw_input()
mat.append([])
for j in range(m):
if s[j] == '*':
mat[i].append(0)
else:
mat[i].append(1)
ans = 0
for i in range(n):
res = 0
for j in range(m):
... |
919 | D | Substring | You are given a graph with $n$ nodes and $m$ \textbf{directed} edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is ... | It is obvious that we can use dynamic programming algorithm to solve this stupid problem. :P We can make an array $f[i][j]$ to respect when you are at the point $i$, then how many letters $j$ you can get. Note that $i$ is ranging from $1$ to $n$ and $j$ is from $1$ to $26$. Then, you can do this dynamic programming alg... | [
"dfs and similar",
"dp",
"graphs"
] | 1,700 | #include <bits/stdc++.h>
#define N 300010
using namespace std;
struct Edge{
int from, to, next;
} edge[N];
int head[N], tot;
inline void addedge(int u, int v){
edge[++tot] = (Edge){u, v, head[u]}, head[u] = tot;
}
int f[N][26], n, m, d[N];
char s[N];
queue<int> Q;
int main(){
scanf("%d%d", &n, &m);
scanf(... |
919 | E | Congruence Equation | Given an integer $x$. Your task is to find out how many positive integers $n$ ($1 \leq n \leq x$) satisfy $$n \cdot a^n \equiv b \quad (\textrm{mod}\;p),$$ where $a, b, p$ are all known constants. | Trying all integers from $1$ to $x$ is too slow to solve this problem. So we need to find out some features of that given equation. Because we have $a^{p-1} \equiv 1 \quad (\textrm{mod}\;p)$ when $p$ is a prime, it is obvious that $a^z \; \textrm{mod} \; p$ falls into a loop and the looping section is $p-1$. Also, $z \... | [
"chinese remainder theorem",
"math",
"number theory"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int a, b, p;
LL x;
inline int pow(int a, int b, int p){
LL ans = 1, base = a;
while (b){
if (b & 1){
(ans *= base) %= p;
}
(base *= base) %= p;
b >>= 1;
}
return (int)ans;
}
inline int inv(int x, int p){
return pow(x, p - 2, p);
}... |
919 | F | A Game With Numbers | Imagine that Alice is playing a card game with her friend Bob. They both have exactly $8$ cards and there is an integer on each card, ranging from $0$ to $4$. In each round, Alice or Bob in turns choose two cards from different players, let them be $a$ and $b$, where $a$ is the number on the player's card, and $b$ is t... | First we should notice that the useful number of states isn't something like $(8^5)^2$, because the order of the numbers in each player's hand does not matter. Therefore, the useful states of each player is $\binom{5 + 8 - 1}{8}$. Then the useful states is estimated as $\binom{5 + 8 - 1}{8}^2$, which is $245\,025$. The... | [
"games",
"graphs",
"shortest paths"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
#define re return
#define sz(a) (int)a.size()
#define mp(a, b) make_pair(a, b)
#define fi first
#define se second
#define re return
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef ... |
920 | A | Water The Garden | It is winter now, and Max decided it's about time he watered the garden.
The garden can be represented as $n$ consecutive garden beds, numbered from $1$ to $n$. $k$ beds contain water taps ($i$-th tap is located in the bed $x_{i}$), which, if turned on, start delivering water to neighbouring beds. If the tap on the be... | The answer is the maximal value among the following values: $\operatorname*{min}_{i=2}^{k}|\frac{a(i)-a(i,-1)+2}{2}\rfloor$ (to cover all water beds within some segment), $a[1]$ (to cover water beds before the first tap), $n - a[k] + 1$ (to cover all water beds after the last tap). | [
"implementation"
] | 1,000 | null |
920 | B | Tea Queue | Recently $n$ students from city S moved to city P to attend a programming camp.
They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.
$i$-th s... | Let's store the last moment when somebody gets a tea in the variable $lst$. Then if for the $i$-th student $lst \ge r_{i}$ then he will not get a tea. Otherwise he will get it during $max(lst + 1, l_{i})$ second. And if he gets a tea then $lst$ will be replaced with the answer for this student. | [
"implementation"
] | 1,200 | null |
920 | C | Swap Adjacent Elements | You have an array $a$ consisting of $n$ integers. Each integer from $1$ to $n$ appears exactly once in this array.
For some indices $i$ ($1 ≤ i ≤ n - 1$) it is possible to swap $i$-th element with $(i + 1)$-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is ... | Take a look at some pair $(i, j)$ such that $i < j$ and initial $a_{i} > a_{j}$. It means that all the swaps from $i$ to $j - 1$ should be allowed. Then it's easy to notice that it's enough to check only $i$ and $i + 1$ as any other pair can be deducted from this. You can precalc $pos[a_{i}]$ for each $i$ and prefix su... | [
"dfs and similar",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,400 | null |
920 | D | Tanks | Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly $V$ ml of water.
Petya has got $N$ tanks, $i$-th of them initially containing $a_{i}$ ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is).
Also Petya has go... | Eliminate the obvious corner case when we don't have enough water ($\sum_{i=1}^{N}a_{i}<V$). Now we don't consider it in editorial. Let's fix some set of tanks $S$, and let $d$ be $\sum_{i\in G}a_{i}$ (the total amount of water in the set). If $d \equiv V (mod K)$ ($d$ and $V$ have the same remainders modulo $k$), th... | [
"dp",
"greedy",
"implementation"
] | 2,400 | null |
920 | E | Connected Components? | You are given an undirected graph consisting of $n$ vertices and ${\frac{n(n-1)}{2}}-m$ edges. Instead of giving you the edges that exist in the graph, we give you $m$ unordered pairs ($x, y$) such that there is no edge between $x$ and $y$, and if some pair of vertices is not listed in the input, then there is an edge ... | Let $S$ be the set of unvisited vertices. To store it, we will use some data structure that allows us to do the following: insert $s$ - insert some value $s$ into the set; erase $s$ - delete $s$ from the set; upper_bound $s$ - find the smallest integer $y$ from the set such that $y > s$. For example, std::set<int> from... | [
"data structures",
"dfs and similar",
"dsu",
"graphs"
] | 2,100 | null |
920 | F | SUM and REPLACE | Let $D(x)$ be the number of positive divisors of a positive integer $x$. For example, $D(2) = 2$ ($2$ is divisible by $1$ and $2$), $D(6) = 4$ ($6$ is divisible by $1$, $2$, $3$ and $6$).
You are given an array $a$ of $n$ integers. You have to process two types of queries:
- REPLACE $l$ $r$ — for every $i\in[l,r]$ re... | At first let's notice that this function converges very quickly, for values up to $10^{6}$ it's at most $6$ steps. Now we should learn how to skip updates on the numbers $1$ and $2$. The function values can be calculated from the factorization of numbers in $O(M A X N\log M A X N)$ with Eratosthenes sieve. Let's write ... | [
"brute force",
"data structures",
"dsu",
"number theory"
] | 2,000 | null |
920 | G | List Of Integers | Let's denote as $L(x, p)$ an infinite sequence of integers $y$ such that $gcd(p, y) = 1$ and $y > x$ (where $gcd$ is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of $L(x, p)$ are $1$-indexed; for example, $9$, $13$ and $15$ are the first, the second and the third elements... | Let's use binary searching to find the answer. Denote as $A(p, y)$ the number of positive integers $z$ such that $z \le y$ and $gcd(z, p) = 1$; the answer is the smallest integer $d$ such that $A(p, d) \ge A(p, x) + k$. We may use, for example, $10^{18}$ as the right border of segment where we use binary searching;... | [
"binary search",
"bitmasks",
"brute force",
"combinatorics",
"math",
"number theory"
] | 2,200 | null |
922 | A | Cloning Toys | Imp likes his plush toy a lot.
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only one origina... | Consider a few cases: If $y = 0$, the answer is always <<No>>. If $y = 1$, then the answer <<Yes>> is possible only if $x = 0$; if $x > 0$, the answer is <<No>>. We can observe that the original was cloned $y - 1$ times to produce the requested amount of originals, then the additional copies were created by cloning the... | [
"implementation"
] | 1,300 | x, y = map(int, input().split())
if y == 0:
print('No')
exit(0)
if y == 1:
if x == 0:
print('Yes')
else:
print('No')
exit(0)
print('Yes' if x >= y - 1 and (x - y + 1) % 2 == 0 else 'No') |
922 | B | Magic Forest | Imp is in a magic forest, where xorangles grow (wut?)
A xorangle of order $n$ is such a non-degenerate triangle, that lengths of its sides are integers not exceeding $n$, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order $n$ to get out of the forest.
Formally,... | Consider some triple $(a, b, c)$ for which $a\oplus b\oplus c=0$ holds. Due to xor invertibility, we can see that $a\oplus b=c$. So, we only need to iterate through two of three possible sides of the xorangle as the third can be deduced uniquely. Time complexity: $O(n^{2})$ One could also apply some constant optimizati... | [
"brute force"
] | 1,300 | #pragma GCC optimize("unroll-loops")
#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
const int N = 100002, M = 350;
mt19937 gen(time(NULL));
#define forn(i, n) for (int i = 0; i < n; i++)
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#define all(a) (a).begin(), (a... |
922 | C | Cave Painting | Imp is watching a documentary about cave painting.
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number $n$ by all integers $i$ from $1$ to $k$. Unfortunately, there are too many integers to analyze for Imp.
Imp w... | Consider the way remainders are obtained. Remainder $k - 1$ can be obtained only when $n$ is taken modulo $k$. Remainder $k - 2$ can either be obtained when taken modulo $k - 1$ or $k$. Since the remainder modulo $k$ is already fixed, the only opportunity left is $k - 1$. Proceeding this way, we come to a conclusion th... | [
"brute force",
"number theory"
] | 1,600 | n, k = map(int, input().split())
if k > 70:
print('No')
exit(0)
s = set()
for i in range(1, k + 1):
s.add(n % i)
print('Yes' if len(s) == k else 'No') |
922 | D | Robot Vacuum Cleaner | Pushok the dog has been chasing Imp for a few hours already.
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string $t$ consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string $t$ as the number of occurrences of string "sh"... | Denote $\mathbf{f}(t)$ as the noise function. We are gonna sort the string set in the following way: for each pair $(a, b)$ we will put $a$ earlier if $\mathbf{f}(a+b)>\mathbf{f}(b+a)$. The claim is that the final concatenation will be optimal. Let $A$ be the number of subsequences $sh$ in $a$, $B$ - in $b$. Then $\mat... | [
"greedy",
"sortings"
] | 1,800 | #define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
const int N = 20000;
mt19937 gen(time(NULL));
#define forn(i, n) for (int i = 0; i < n; i++)
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#define all(a) (a).begin(), (a).end()
#define pii pair<int, int>
#define mp mak... |
922 | E | Birds | Apart from plush toys, Imp is a huge fan of little yellow birds!
To summon birds, Imp needs strong magic. There are $n$ trees in a row on an alley in a park, there is a nest on each of the trees. In the $i$-th nest there are $c_{i}$ birds; to summon one bird from this nest Imp needs to stay under this tree and it cost... | The problem can be solved by utilizing dynamic programming. Let us denote by $\mathrm{d}\mathbf{p}[n][k]$ the maximum possible remaining amount mana for the state $(n, k)$, where $n$ stands for the number of nests passed by and $k$ stands for the number of birds summoned. The base is $\mathrm{d}{\mathfrak{p}}[0](0)=W$ ... | [
"dp"
] | 2,200 | #define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
const int N = 1005, M = 10005;
mt19937 gen(time(NULL));
#define forn(i, n) for (int i = 0; i < n; i++)
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#define all(a) (a).begin(), (a).end()
#define pii pair<int, int>
#def... |
922 | F | Divisibility | Imp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more.
Let's define $f(1)$ for some set of integers $\left\vert\right.\L$ as the number of pairs $a$, $b$ in $\left.\right]_{}^{}$, such that:
- $a$ is \textbf{strictly less} than $b$;
- $a$ \textbf{divides} $b$... | Let the sought pairs be the edges in a graph with $n$ vertices. Then the problem is reduced to finding such a vertex subset that the induced graph contains exactly $k$ edges. Let $e(n)$ be the number of edges in the graph on ${1, 2, ..., n}$ and $d(n)$ be the number of divisors of $n$ (strictly less than $n$). We claim... | [
"constructive algorithms",
"dp",
"greedy",
"number theory"
] | 2,400 | #include <iostream>
#include <map>
#include <vector>
using namespace std;
const int MAXN = 300005;
int smallest_divisor[MAXN];
int nd[MAXN];
bool ban[MAXN];
int num_divisors(int x)
{
if (nd[x] == 0) {
int i = x;
if (i == 0) {
return 0;
}
map<int, int> cnt;
... |
923 | A | Primal Sport | Alice and Bob begin their day with a quick game. They first choose a starting number $X_{0} ≥ 3$ and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the $i$-th turn, the player whose turn it is selects a prime number smaller than the current number, an... | Let $P(N)$ be the largest prime factor of $N$. Clearly, we can obtain $N$ from any number in interval $[N - P(N) + 1, N]$ by picking $P(N)$ as the prime, and we cannot obtain $N$ from any other number. By factorizing $X_{2}$, we can find the range for $X_{1}$. By factorizing all numbers from the range of $X_{1}$, we ca... | [
"math",
"number theory"
] | 1,700 | null |
923 | B | Producing Snow | Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day $i$ he will make a pile of snow of volume $V_{i}$ and put it in her garden.
Each day, every... | We can directly simulate the process, but it takes $O(N^{2})$ time, which is too slow. There are multiple approaches how to make this simulation faster. We present two of them. In the first solution, instead of calculating the total volume of the snow melted, we first calculate two quantities: $F[i]$ - the number of pi... | [
"binary search",
"data structures"
] | 1,600 | null |
923 | C | Perfect Security | Alice has a very important message $M$ consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key $K$ of the length equal to the message's length. Alice computes the bitwise xor of each element of t... | We decrypt the message greedily, one number at a time. Note that $f(X):X\oplus Y$ is a bijection on non-negative integers. For that reason, there is always a unique number from the key that lexicographically minimises the string. We can always pick and remove that number, output its xor with the current number from the... | [
"data structures",
"greedy",
"strings",
"trees"
] | 1,800 | null |
923 | D | Picking Strings | Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
- A $\to$ BC
- B $\to$ AC
- C $\to$ AB
- AAA $\to$ empty string
Note that a substring is one or more consecutive characters. For given queries, determine... | First note that $B$ can be always changed to $C$ and vice versa: $\mathbf{B}\rightarrow A\mathbf{C}\rightarrow A A\mathbf{B}\rightarrow\mathbf{AAA}C\rightarrow C$. Hence we can replace all $C$'s with $B$'s. Furthermore, see that: $A\mathbf{B}\rightarrow A A\mathbf{C}\rightarrow\mathbf{AAA}B\rightarrow B$. The above imp... | [
"constructive algorithms",
"implementation",
"strings"
] | 2,500 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.