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 ⌀ |
|---|---|---|---|---|---|---|---|
494 | E | Sharti | During the last 24 hours Hamed and Malek spent all their time playing "Sharti". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round.
"Sharti" is played on a $n × n$ board with some of cells colored white and others colored black. The rows of the board a... | Let's first solve this problem for another game: Suppose that we've an $n \times n$ table. Each cell have some(possibly zero) marbles on it. During each move the player chooses a square with side-length at most $k$ which its lower-right cell has at least one marble, he removes one marble from it and puts one marble i... | [
"data structures",
"games"
] | 3,200 | null |
495 | A | Digital Counter | Malek lives in an apartment block with $100$ floors numbered from $0$ to $99$. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with $7$ light sticks by turning them on or off. The picture below shows how the elevator sho... | For each digit $x$ you can count the number of digits $y$ that because of some broken sticks $x$ is shown instead of $y$ by hand. for example when $x = 3$, $y$ can be $3$, $8$ and $9$. Let's denote this number by $a_{x}$. Then if the input is $xy$ (the first digit shown in the counter is $x$ and the second is $y$) the ... | [
"implementation"
] | 1,100 | null |
495 | B | Modular Equations | Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define $i$ modulo $j$ as the remainder of division of $i$ by $j$ and denote it by $i\,\mathrm{mod}\,j$. A Modular Equation, as Hamed's teacher described, is an equation of the form $a{\bmod{x}}=b$ in which $a$ and $b... | If $a < b$ then there is no answer since $a\operatorname*{mod}x\leq a<b$. If $a = b$ then $x$ can be any integer larger than $a$. so there are infinite number of answers to the equation. The only remaining case is when $a > b$. Suppose $x$ is an answer to our equation. Then $x|a - b$. Also since $a{\bmod{x}}=b$ then $b... | [
"math",
"number theory"
] | 1,600 | null |
496 | A | Minimum Difficulty | Mike is trying rock climbing but he is awful at it.
There are $n$ holds on the wall, $i$-th hold is at height $a_{i}$ off the ground. Besides, let the sequence $a_{i}$ increase, that is, $a_{i} < a_{i + 1}$ for all $i$ from 1 to $n - 1$; we will call such sequence a \underline{track}. Mike thinks that the track $a_{1}... | For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^{2})$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the diff... | [
"brute force",
"implementation",
"math"
] | 900 | null |
496 | B | Secret Combination | You got a box with a combination lock. The lock has a display showing $n$ digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the dis... | We observe that the order of operations is not important: we may first perform all the shifts, and after that all the additions. Note that after $n$ shifts the sequence returns to its original state, therefore it is sufficient to consider only the options with less than $n$ shifts. Also, after 10 times of adding 1 to a... | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,500 | null |
496 | C | Removing Columns | You are given an $n × m$ rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
\begin{verbatim}
abcd
edfg
hijk
\end{verbatim}
w... | Let's look at the first column of the table. If its letters are not sorted alphabetically, then in any valid choice of removing some columns it has to be removed. However, if its letters are sorted, then for every valid choice that has this column removed it can be restored back to the table; it is clear that the new c... | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,500 | null |
496 | D | Tennis Game | Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores $t$ points, he wins the set; then the ... | Choose some $t$; now emulate how the match will go, ensure that the record is valid for this $t$ and by the way find the corresponding value of $s$. Print all valid options for $s$ and $t$. This solution works in $O(n^{2})$ time, which is not good enough, but we will try to optimize it. Suppose the current set if finis... | [
"binary search"
] | 1,900 | null |
496 | E | Distributing Parts | You are an assistant director in a new musical play. The play consists of $n$ musical parts, each part must be performed by exactly one actor. After the casting the director chose $m$ actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.
First, each a... | Sort all the parts and actors altogether by increasing lower bounds (if equal, actors precede parts); process all the enitities in this order. We maintain a set of actors which have already occured in the order; if we meet an entry for an actor, add it to the set. If we currently process a part, we have to assign it to... | [
"greedy",
"sortings"
] | 2,100 | null |
497 | D | Gears | \url{CDN_BASE_URL/e4fa6a6323e7ecee665f560536ee7fd5} | When a collision happens, a vertex of one polygon lands on a side of the other polygon. Consider a reference system such that the polygon $A$ is not moving. In this system the polygon $B$ preserves its orientation (that is, does not rotate), and each of its vertices moves on some circle. Intersect all the circles for v... | [
"brute force",
"geometry",
"math"
] | 2,900 | null |
497 | E | Subsequences Return | Assume that $s_{k}(n)$ equals the sum of digits of number $n$ in the $k$-based notation. For example, $s_{2}(5) = s_{2}(101_{2}) = 1 + 0 + 1 = 2$, $s_{3}(14) = s_{3}(112_{3}) = 1 + 1 + 2 = 4$.
The sequence of integers $a_{0}, ..., a_{n - 1}$ is defined as $a_{j}=s_{k}(j){\bmod{k}}$. Your task is to calculate the numbe... | Consider some string; how does one count the number of its distinct subsequences? Let us append symbols to the string consequently and each time count the number of subsequences that were not present before. Let's append a symbol $c$ to a string $s$; in the string $s + c$ there are as many subsequences that end in $c$ ... | [
"dp",
"matrices"
] | 2,900 | null |
498 | A | Crazy Town | Crazy Town is a plane on which there are $n$ infinite line roads. Each road is defined by the equation $a_{i}x + b_{i}y + c_{i} = 0$, where $a_{i}$ and $b_{i}$ are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an... | It can be easily proved that, if two points from statement are placed on different sides of some line, this line will be crossed anyway. So, all we need to do is to cross all these lines, so the answer is the number of these lines. To check if two points lies on different sides of a line one can simply use its coordina... | [
"geometry"
] | 1,700 | null |
498 | B | Name That Tune | It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of $n$ songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on.
The $i... | Let's numerate all the songs and seconds starting from 0. Problem will be solved using DP approach. State will be described by two integers $(i, j)$: $dp[i][j]$ is probability of that we named exactly $i$ songs, and the last named song was named exactly before $j$'th second (after $j - 1$ seconds). $dp[0][0] = 1$ obvio... | [
"dp",
"probabilities",
"two pointers"
] | 2,400 | null |
498 | C | Array and Operations | You have written on a piece of paper an array of $n$ positive integers $a[1], a[2], ..., a[n]$ and $m$ good pairs of integers $(i_{1}, j_{1}), (i_{2}, j_{2}), ..., (i_{m}, j_{m})$. Each good pair $(i_{k}, j_{k})$ meets the following conditions: $i_{k} + j_{k}$ is an odd number and $1 ≤ i_{k} < j_{k} ≤ n$.
In one opera... | We will divide only by prime numbers. First, let's build a graph, where each of $n$ numbers have own vertex group: Find all prime factors of current number. Every factor will have its own vertex in a group, furthermore, if some factor $p$ has power of $a_{i}$ in current number, it will have exactly $a_{i}$ vertexes in ... | [
"flows",
"graph matchings",
"number theory"
] | 2,100 | null |
498 | D | Traffic Jams in the Land | Some country consists of $(n + 1)$ cities, located along a straight highway. Let's number the cities with consecutive integers from $1$ to $n + 1$ in the order they occur along the highway. Thus, the cities are connected by $n$ segments of the highway, the $i$-th segment connects cities number $i$ and $i + 1$. Every se... | The solution of a problem - 60 (LCM of a numbers from 2 to 6) segment trees. In $v$'th segment tree we will hold for every segment $[l, r]$ the next value: minimum time needed to get from $l$ to $r$ if we start in a moment of time equal to $v$ modulo 60. Using these trees' values it is easy to quickly answer the questi... | [
"data structures",
"dp",
"number theory"
] | 2,400 | null |
498 | E | Stairs and Lines | You are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height $i$ is $w_{i}$ squares. Formally, the figure is created by consecutively joining rectangles of size $w_{i} × i$ so that the $w_{i}$ sides lie on one straight line. Thus, for example, if all $w_{i} = 1$, the figu... | The problem is solved using DP approach $dp[i][mask]$ - the number of ways to paint first $i$ blocks of a ladder the way that the last layer of vertical edges is painted as described in mask $mask$. This could be easily recalculated using matrix $M[mask1][mask2]$ - the number of ways to paint horizontal edges between t... | [
"dp",
"matrices"
] | 2,700 | null |
499 | A | Watching a movie | You have decided to watch the best moments of some movie. There are two buttons on your player:
- Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.
- Skip exactly $x$ minutes of the movie ($x$... | One can solve the problem using greedy algorithm: if we can skip $x$ minutes at current moment without skipping any good moment - we do that, otherwise - watch another minute of the film. | [
"greedy",
"implementation"
] | 1,000 | null |
499 | B | Lecture | You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | In this task you must find for every string in the text the pair containing that string, and from two strings of that pair output the shortest one. | [
"implementation",
"strings"
] | 1,000 | null |
500 | A | New Year Transportation | New Year is coming in Line World! In this world, there are $n$ cells numbered by integers from $1$ to $n$, as a $1 × n$ board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0... | Let's assume that I am in the cell $i$ ($1 \le i \le n$). If $i \le n - 1$, I have two choices: to stay at cell $i$, or to go to cell $(i + a_{i})$. If $i = t$, we are at the target cell, so I should print "YES" and terminate. If $i > t$, I cannot go to cell $t$ because I can't use the portal backwards, so one sh... | [
"dfs and similar",
"graphs",
"implementation"
] | 1,000 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#incl... |
500 | B | New Year Permutation | User ainta has a permutation $p_{1}, p_{2}, ..., p_{n}$. As the New Year is coming, he wants to make his permutation as pretty as possible.
Permutation $a_{1}, a_{2}, ..., a_{n}$ is prettier than permutation $b_{1}, b_{2}, ..., b_{n}$, if and only if there exists an integer $k$ ($1 ≤ k ≤ n$) where $a_{1} = b_{1}, a_{2... | It seems that many contestants were confused by the statement, so let me clarify it first. Given a permutation $p_{1}, p_{2}, ..., p_{n}$ and a $n \times n$-sized binary matrix $A$, the problem asks us to find the lexicographically minimum permutation which can be achieved by swapping two distinct elements $p_{i}$ an... | [
"dfs and similar",
"dsu",
"graphs",
"greedy",
"math",
"sortings"
] | 1,600 | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <deque>
#include <u... |
500 | C | New Year Book Reading | New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has $n$ books numbered by integers from 1 to $n$. The weight of the $i$-th ($1 ≤ i ≤ n$) book is $w_{i}$.
As Jaehyun's house is not large enough to have a bookshelf, he keeps the $n$ books by stacking them vertically. When he ... | In order to calculate the minimum possible lifted weight, we should find the initial stack first. Let's find the positions one by one. First, let's decide the position of book $b_{1}$. After day 1, book $b_{1}$ will be on the top of the stack, regardless of the order of the initial stack. Therefore, in order to minimiz... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,600 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#incl... |
500 | D | New Year Santa Network | New Year is coming in Tree World! In this world, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to $n$, and the roads are numbered by integers from $1$ to $n - 1$. Let's define $d(u... | The problem asks us to calculate the value of Let's write it down.. So, we need to calculate the value of $\sum_{1<u,v<n,u>v}d(u,v)$. I'll denote the sum as $S$. How should we calculate this? For simplicity, I'll set node 1 as the root of the tree. Let's focus on an edge $e$, connecting two vertices $u$ and $p$. See th... | [
"combinatorics",
"dfs and similar",
"graphs",
"trees"
] | 1,900 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#incl... |
500 | E | New Year Domino | Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos
User ainta, who lives in a 2D world, is going to post a video as well.
There are $n$ dominoes on a 2D Cartesian plane. $i$-th domino ($1 ≤ i ≤ n$) can be represe... | From the statement, it is clear that, when domino $i$ falls to the right, it makes domino $j$ also fall if and only if $p_{i} < p_{j} \le p_{i} + l_{i}$. For each domino $i$, let's calculate the rightmost position of the fallen dominoes $R[i]$ when we initially pushed domino $i$. From the definition, $R[i]=\operatorn... | [
"data structures",
"dp",
"dsu"
] | 2,300 | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <deque>
#include ... |
500 | F | New Year Shopping | Dohyun is running a grocery store. He sells $n$ items numbered by integers from 1 to $n$. The $i$-th ($1 ≤ i ≤ n$) of them costs $c_{i}$ dollars, and if I buy it, my happiness increases by $h_{i}$. Each item can be displayed only for $p$ units of time because of freshness. As Dohyun displays the $i$-th item at time $t_... | The $i$-th item is available during $[t_{i}, t_{i} + p - 1]$. In other words, at time $T$, item $i$ is available if and only if $t_{i} \le T \le t_{i} + p - 1$. This can be re-written as ($t_{i} \le T$ and $T - p + 1 \le t_{i}$), which is $T - p + 1 \le t_{i} \le T$. With this observation, we can transform ... | [
"divide and conquer",
"dp"
] | 2,700 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#incl... |
500 | G | New Year Running | New Year is coming in Tree Island! In this island, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists exactly one path between them. For every person in Tree Island, it takes exactly one minute to pass by exactly one road.
There is a weird New Year... | Before starting the editorial, I'd like to give a big applause to Marcin_smu, who solved the problem for the first time! Warning: The editorial is very long and has many mistakes. There are lots of lots of mistakes.. Keep calm, and please tell me by comments, if you discovered any errors. This problem can be solved by ... | [
"number theory",
"trees"
] | 3,200 | #include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
#define N_ 200010
#define INF 99999999999999999LL
vector<int>E[N_];
int n, Q;
int Dep[N_];
int par[18][N_];
void DFS(int node, int dep, int pp){
int i, x;
Dep[node] = dep;
par[0][node] = pp;
for (i = 0; i < E[node].size(); i++){
x... |
501 | A | Contest | Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs $a$ points and Vasya solved the problem that costs $b$ points. Besides, Misha submitted the problem $c$ minutes after the ... | In this problem one need to determine the number of points for both guys and find out who got more points. Time complexity: $O(1)$. | [
"implementation"
] | 900 | null |
501 | B | Misha and Changing Handles | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the re... | The problem can be formulated as follows: The directed graph is given, its vertices correspond to users' handles and edges - to requests. It consists of a number of chains, so every vertex ingoing and outgoing degree doesn't exceed one. One need to find number of chains and first and last vertices of every chain. The a... | [
"data structures",
"dsu",
"strings"
] | 1,100 | #include <bits/stdc++.h>
#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define... |
501 | C | Misha and Forest | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of $n$ vertices. For each vertex $v$ from $0$ to $n - 1$ he wrote down two integers, $degree_{v}$ and $s_{v}$, were the first integer is the number of vertices adjacent to verte... | Note that every non-empty forest has a leaf(vertex of degree $1$). Let's remove edges one by one and maintain actual values $(degree_{v}, s_{v})$ as long as graph is not empty. To do so, we can maintain the queue(or stack) of the leaves. On every iteration we dequeue vertex $v$ and remove edge $(v, s_{v})$ and update v... | [
"constructive algorithms",
"data structures",
"greedy",
"sortings",
"trees"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int degree[n], xorsum[n];
queue <int> Q;
int used = 0;
for(int i = 0; i < n; ++i)
{
cin >> degree[i] >> xorsum[i];
if (degree[i] == 1)
Q.push(i);
if (degree[i] == 0)
{
if (xorsum[i] ... |
501 | D | Misha and Permutations Summation | Let's define the sum of two permutations $p$ and $q$ of numbers $0, 1, ..., (n - 1)$ as permutation $P e r m((O r d(p)+O r d(q))\bmod{n!})$, where $Perm(x)$ is the $x$-th lexicographically permutation of numbers $0, 1, ..., (n - 1)$ (counting from zero), and $Ord(p)$ is the number of permutation $p$ in the lexicographi... | To solve the problem, one need to be able to find the index of given permutation in lexicographical order and permutation by its index. We will store indices in factorial number system. Thus number $x$ is represented as $\sum_{k=1}^{n}d_{k}\times k!$. You can find the rules of the transform here. To make the transform,... | [
"data structures"
] | 2,000 | null |
501 | E | Misha and Palindrome Degree | Misha has an array of $n$ integers indexed by integers from $1$ to $n$. Let's define palindrome degree of array $a$ as the number of such index pairs $(l, r)(1 ≤ l ≤ r ≤ n)$, that the elements from the $l$-th to the $r$-th one inclusive can be rearranged in such a way that the \textbf{whole} array will be a palindrome.... | Note that if the amount of elements, which number of occurrences is odd, is greater than one, the answer is zero. On the other hand, if array is the palindrome, answer is $\textstyle{\frac{n(n+1)}{2}}$. Let's cut equal elements from the end and the beginning of array while it is possible. Let's call remaining array as ... | [
"binary search",
"combinatorics",
"implementation"
] | 2,500 | null |
504 | D | Misha and XOR | After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number $x$ to the basket, Misha should answer the que... | Firstly, we convert each number into a binary system: it can be done in $O(MAXBITS^{2})$, where $MAXBITS \le 2000$ with rather small constant(we store number in system with big radix). To solve the problem we need to modify Gauss elimination algorithm. For each row we should store set of row's indices which we alread... | [
"bitmasks"
] | 2,700 | null |
504 | E | Misha and LCP on Tree | Misha has a tree with characters written on the vertices. He can choose two vertices $s$ and $t$ of this tree and write down characters of vertices lying on a path from $s$ to $t$. We'll say that such string corresponds to pair $(s, t)$.
Misha has $m$ queries of type: you are given $4$ vertices $a$, $b$, $c$, $d$; you... | Let's build heavy-light decomposition of given tree and write all strings corresponding to heavy paths one by one in one string $T$, every path should be written twice: in the direct and reverse order. Maintaining query we can split paths $(a, b)$ and $(c, d)$ into parts, which completely belongs to some heavy paths. T... | [
"binary search",
"dfs and similar",
"hashing",
"string suffix structures",
"trees"
] | 3,000 | #include <bits/stdc++.h>
#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define... |
505 | A | Mr. Kitayuta's Gift | Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into $s$ to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "tes... | Since the string is short (at most 10 characters), you can simply try every possible way of inserting a letter ("where" and "what" to insert), and check if the resulting string is a palindrome. | [
"brute force",
"implementation",
"strings"
] | 1,100 | // Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define all(x) (x).begin(),(x).end()
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) re... |
505 | B | Mr. Kitayuta's Colorful Graph | Mr. Kitayuta has just bought an undirected graph consisting of $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.
Mr. Kitayuta wants you to process the following $q$ queries.
In the $i$-th query, he ... | Since neither the graph nor the number of queries is too large, for each query you can simply count the number of the "good" colors (the colors that satisfies the condition) by checking if each color is "good". To do that, you can perform Depth First Search (or Breadth First Search) and verify whether you can reach $v_... | [
"dfs and similar",
"dp",
"dsu",
"graphs"
] | 1,400 | null |
505 | C | Mr. Kitayuta, the Treasure Hunter | The Shuseki Islands are an archipelago of $30001$ small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from $0$ to $30000$ from the west to the east. These islands are known to contain many treasures. There are $n$ gems in the Shuseki Islands in total, and the $i$-th gem is located on ... | Below is the explanation from yosupo, translated by me. [From here] Let $m$ be the number of the islands (that is, $30001$). First, let us describe a solution with time and memory complexity of $O(m^{2})$. We will apply Dynamic Programming. let $dp[i][j]$ be the number of the gems that Mr. Kitayuta can collect after he... | [
"dfs and similar",
"dp",
"two pointers"
] | 1,900 | null |
505 | D | Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are $n$ cities in the kingdom, numbered from $1$ to $n$.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionall... | Let $G_{1}$ be the directed graph built from the input, and $G_{2}$ be a directed graph that satisfies the given conditions. What we seek is the minimum number of edges in $G_{2}$. Also, we say that two vertices $u$ and $v$ in a directed graph are "weakly connected" if we can reach $v$ from $u$ by traversing edges, not... | [
"dfs and similar"
] | 2,200 | // Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int... |
505 | E | Mr. Kitayuta vs. Bamboos | Mr. Kitayuta's garden is planted with $n$ bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the $i$-th bamboo is $h_{i}$ meters, and it grows $a_{i}$ meters at the end of each day.
Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, bu... | Below is the explanation from yosupo, translated by me. [From here] Let us begin by applying Binary Search. The problem becomes: "is it possible that all the bamboos are at most $X$ meters after $m$ days?" It is complicated by the fact that the height does not become negative; the excessive decrease will be wasted. We ... | [
"binary search",
"greedy"
] | 2,900 | // Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int... |
506 | D | Mr. Kitayuta's Colorful Graph | Mr. Kitayuta has just bought an undirected graph with $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.
Mr. Kitayuta wants you to process the following $q$ queries.
In the $i$-th query, he gives you... | Below is the explanation from hogloid. [From here] For each color, make a new graph that consists of the edges of the color and vertices connected by the edges. Make UnionFind for each graph, and you can check whether a color connects vertex $A$ and $B$ , using it. For each query, find a vertex which has smaller degree... | [
"brute force",
"dfs and similar",
"dsu",
"graphs"
] | 2,400 | // Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int... |
506 | E | Mr. Kitayuta's Gift | Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly $n$ lowercase English letters into $s$ to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "t... | First of all, let us note that we are asked to count the resulting palindromes, not the ways to obtain them. For example, if we are to insert "b" into "abba", there are 5 possible positions, but only 3 strings will be produced ("babba", "abbba" and "abbab"). Rather than trying to count the ways of inserting a letter $n... | [
"combinatorics",
"dp",
"matrices",
"strings"
] | 3,000 | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <utility>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cs... |
507 | A | Amr and Music | Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has $n$ instruments, it takes $a_{i}$ days to learn $i$-th instrument. Being busy, Amr dedicated $k$ days to learn how to play the maximum possible number of instruments.
Amr asked for... | Problem: We have to split the number $k$ into maximum number of elements of $a_{i}$ such that their sum is less than or equal to $k$. Hint: To maximize the answer we have to split the number into the smallest numbers possible. Solution: So and since the limits are small we can pick up the smallest element of the array ... | [
"greedy",
"implementation",
"sortings"
] | 1,000 | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric... |
507 | B | Amr and Pins | Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius $r$ and center in point $(x, y)$. He wants the circle center to be in new position $(x', y')$.
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any ... | Problem: We have a circle with radius $R$ at position $(x, y)$ and we want to move it to $(x', y')$ with minimum moves possible. A move is to choose an arbitrary point on the border of the circle and rotate the circle around it with arbitrary angle. Hint: What is the shortest path between two points? A direct line. So ... | [
"geometry",
"math"
] | 1,400 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class ok {
public static void main(String[] args) {
InputReader in = new InputReader(System.i... |
507 | C | Guess Your Way Out! | Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to... | Hint: Simulate the algorithm until we reach a leaf node assume that it's not the exit. Now the question is Are there some nodes that are guaranteed to be visited before trying to reach the exit again? Solution: The first observation is that in order to return to a parent we will have to visit all nodes of the right or ... | [
"implementation",
"math",
"trees"
] | 1,700 | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric... |
507 | D | The Maths Lecture | Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.
First he gave Amr two positive integers $n$ and $k$. Then he asked Amr, how many integer numbers $x > 0$ exist such that:
... | Hint: Dynamic programming problem. To handle repetitions we have to construct the number from right to the left and calculate the answer when we reach a number equivalent to $0$ modulo $k$. Solution: Let's define $c o u n t(i\,,j)$ as a recursive functions calculates the number of numbers consisting of $n$ digits satis... | [
"dp",
"implementation"
] | 2,200 | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric... |
507 | E | Breaking Good | Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of... | Hint: Consider we've chosen a certain path with length $d$ where $d$ is the length of the shortest path from $1$ to $n$ and it has $x$ edges that are working. Assume that $y$ is the total number of edges that are working in the whole country. So we need to make $d - x$ changes (to make the malfunctioning edges on the p... | [
"dfs and similar",
"dp",
"graphs",
"shortest paths"
] | 2,100 | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric... |
508 | A | Pasha and Pixels | Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of $n$ row with $m$ pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos... | To solve this problem let's create matrix with type $bool$ and dimensions $n$ on $m$. Cell $(x, y)$ of this matrix is $true$ - if this cell painted in black color. Let on move number $k$ Pasha paints pixel in position $(i, j)$. Then game ending on this move, if square $2 \times 2$ formed from black cells appears, and... | [
"brute force"
] | 1,100 | null |
508 | B | Anton and currency you all know | Berland, 2016. The exchange rate of \underline{currency you all know} against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exch... | Because of specified number is odd (that mean that last digit of this number is odd) we need to swap last digit with some even digit. How to maximize number after this swap? If number consists only from odd digits print $- 1$. Else, we need to find first even digit, which less than last digit if we will iterate from mo... | [
"greedy",
"math",
"strings"
] | 1,300 | null |
508 | C | Anya and Ghosts | Anya loves to watch horror movies. In the best traditions of horror, she will be visited by $m$ ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly $t$ seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one... | This problem can be solved with help of greedy algorithm. Let's iterate on moments when ghosts will appears. We need to use use array, in wich we will mark moments of time, in wich we lighted candles (for example, put in corresponding positions $1$). Than for every new ghost will count how many candles lights in time o... | [
"constructive algorithms",
"greedy"
] | 1,600 | null |
508 | D | Tanya and Password | While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of $n + 2$ characters. She has written all the possible $n$ three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the passw... | At first, let's convert data from input in directed graph. Vertexes in this graph will all strings with length equals to 2 and consisting of uppercase and lowercase letters of the latin alphabet. For all 3-letters strings from input - $s_{i}$'s, let's add edge from vertex $s_{i}[0]s_{i}[1]$ to $s_{i}[1]s_{i}[2]$. Now w... | [
"dfs and similar",
"graphs"
] | 2,500 | null |
508 | E | Arthur and Brackets | Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length $2n$. Unlike Arthur, Sasha understood the top... | This problem can be solved with help of dynamic dynamic programming. Let's create squre matrix $Z$ with sizes $n \times n$, where $n$ - count of open brackets in sequence. Main hint - if open bracket is in position $l$, and corresponding for her close bracket - in position $r$, than from position $l + 1$ to position ... | [
"dp",
"greedy"
] | 2,200 | null |
509 | A | Maximum in Table | An $n × n$ table $a$ is defined as follows:
- The first row and the first column contain ones, that is: $a_{i, 1} = a_{1, i} = 1$ for all $i = 1, 2, ..., n$.
- Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements ... | In this problem one needed to implement what was written in the statement: create matrix (two-dimensional array) using given rules and find maximal value in the table. It is also possible to see that maximal element is always in bottom-right corner. Easier solution with recursion also was enough to get AC: One may see ... | [
"brute force",
"implementation"
] | 800 | null |
509 | B | Painting Pebbles | There are $n$ piles of pebbles on the table, the $i$-th pile contains $a_{i}$ pebbles. Your task is to paint each pebble using one of the $k$ given colors so that for each color $c$ and any two piles $i$ and $j$ the difference between the number of pebbles of color $c$ in pile $i$ and number of pebbles of color $c$ in ... | Suppose there are two piles with number of pebbles differed by more than $k$, then there is no solution: $a_{i}=\sum_{c=1}^{k}b_{i,c}\leq\sum_{c=1}^{k}(b_{j,c}+1)=a_{j}+k$ Now let $M = max a_{i} \le min a_{i} + k = m + k$. There's a way to construct correct coloring: Chose $m$ peebles from each pile and assign first ... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,300 | null |
509 | C | Sums of Digits | Vasya had a \textbf{strictly increasing} sequence of positive integers $a_{1}$, ..., $a_{n}$. Vasya used it to build a new sequence $b_{1}$, ..., $b_{n}$, where $b_{i}$ is the sum of digits of $a_{i}$'s decimal representation. Then sequence $a_{i}$ got lost and all that remained is sequence $b_{i}$.
Vasya wonders what... | The algorithm is greedy: first, take the minimal number with sum of digits $a_{1}$ - call it $b_{1}$. Then, on the $i$-th step take $b_{i}$ as the minimal number with sum of digits $a_{i}$, which is more than $b_{i - 1}$. It can be easily proven that this algorithm gives an optimal answer. But how to solve the subprobl... | [
"dp",
"greedy",
"implementation"
] | 2,000 | null |
509 | D | Restoring Numbers | Vasya had two arrays consisting of non-negative integers: $a$ of size $n$ and $b$ of size $m$. Vasya chose a positive integer $k$ and created an $n × m$ matrix $v$ using the following formula:
\[
v_{i,j}=(a_{i}+b_{j})\bmod k
\]
Vasya wrote down matrix $v$ on a piece of paper and put it in the table.
A year later Vas... | First we note that if the sequences $a_{i}$ and $b_{i}$ are a valid solution, then so are the sequences $a_{i} - P$ and $b_{i} + P$ for any integer $P$. This means that we can consider $a_{1}$ to be equal to 0 which allows us to recover the sequence $b_{i}$ by simply taking the first row of the matrix. Knowing $b_{i}$ ... | [
"constructive algorithms",
"math"
] | 2,200 | null |
509 | E | Pretty Song | When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's d... | We first calculate the prefix sums of $vowel(s_{i})$ which allows to calculate the sum of $vowel(s_{i})$ on any substring in $O(1)$ time. For all $m$ from $1$ to $\left|\,\S\right|_{\sim}\right|_{\sim}$, we will calculate the sum of simple pretinesses of all substrings of that length, let's call it $SP_{m}$. For that p... | [
"math",
"strings"
] | 2,000 | null |
509 | F | Progress Monitoring | Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree $T$ with $n$ vertices, specified by its adjacency matrix $a[1... n, 1... n]$. What is the output of the following pseudocode?
\begin{verbatim}
used[1 ... n] = {0, ..., 0};
procedure dfs(... | Consider a tree with $n$ vertices rooted at vertex 1 and let $b$ be the pseudocode's (DFS) resulting sequence. Then $b[l_{v}..l_{v} + size_{v} - 1]$, represents vertex $v$'s subtree, where $l_{v}$ is the index of $v$ in $b$ and $size_{v}$ is the size of $v$'s subtree. Let's solve the problem using this fact and Dynamic... | [
"dp",
"trees"
] | 2,300 | null |
510 | A | Fox And Snake | Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a $n$ by $m$ table. Denote $c$-th cell of $r$-th row as $(r, c)$. The tail of the snake is located at $(1, 1)$, then it's body ex... | There are 2 different ways to solve this kind of task: First one is to simulate the movement of the snake head, and you draw '#'s on the board. The code will look like: Another way is to do some observation about the result, you can find this pattern: | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int MAIN()
{
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
bool haveSnake = false;
if(i % 2 == 1) haveSnake = true;
else
{
if(i % 4 == 2) haveSnake = (j == m);
if(i % 4 == 0) haveSnake = (j == 1);
}
c... |
510 | B | Fox And Two Dots | Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size $n × m$ cells, like this:
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain dots of ... | This task is essentially ask if there is a cycle in an undirected graph: treat each cell as a node, and add an edge if two cells are neighborhood and have some color. There are lots of ways to do this, for example: Run dfs / bfs, if an edge lead you to a visited node, then there must be a cycle. For each connected comp... | [
"dfs and similar"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int n, m;
string board[51];
bool visited[51][51];
bool findCycle = false;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
void dfs(int x, int y, int fromX, int fromY, char needColor)
{
if(x < 0 || x >= n || y < 0 || y >= m) return;
if(board[x][y] != needColor) retur... |
510 | C | Fox And Names | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the \underline{lexicographical} order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't ... | Let's first think about what $S < T$ can tell us: suppose $S = abcxyz$ and $T = abcuv$. Then we know that $S < T$ if and only if $x < u$ by the definition. So we can transform the conditions $name_{1} < name_{2}$, $name_{2} < name_{3}$ ... into the order of letters. Then the question become: do we have a permutation th... | [
"dfs and similar",
"graphs",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int n;
int e[27][27];
string s[101];
bool visited[27];
int getID(char c)
{
if(c == ' ') return 0;
return c - 'a' + 1;
}
int MAIN()
{
memset(e, 0, sizeof(e));
for(int i = 1; i <= 26; i++)
e[0][i] = true;
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> s[i];
s[... |
510 | D | Fox And Jumping | Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also $n$ cards, each card has 2 attributes: length $l_{i}$ and cost $c_{i}$. If she pays $c_{i}$ dollars then she can apply $i$... | This task equals to: what is the minimal sum of costs that we can select k cards, so their GCD is 1. First observation is that: $GCD(x_{1}, x_{2}, ..., x_{k}) = 1$ means that for any prime $p$, there exist i such that $x_{i}$ is not dividable by $p$. So we only care about what prime factors a number contain. (So for ex... | [
"bitmasks",
"brute force",
"dp",
"math"
] | 1,900 | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <map>
#include <set>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
int n, N;
int x[301];
in... |
510 | E | Fox And Dinner | Fox Ciel is participating in a party in Prime Kingdom. There are $n$ foxes there (include Fox Ciel). The i-th fox is $a_{i}$ years old.
They will have dinner around some round tables. You want to distribute foxes such that:
- Each fox is sitting at some table.
- Each table has at least 3 foxes sitting around it.
- Th... | First finding is: if $a + b$ is a prime, then one of them is an odd number, another is an even number. (that's why we set $2 \le x_{i}$) Then we could find: every odd number have exactly 2 even number as neighborhood, and every even number have exactly 2 odd number as neighborhood. And that means we need $|#even| = |... | [
"flows"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int n;
int x[201];
vector <int> id1;
vector <int> idOdd, idEven;
#define MAXN 200001
int maxint = ~0U>>1;
int flow;
int pi[MAXN+1], v[MAXN+1];
int S, T;
struct etype
{
int t, c;
etype* next;
etype* pair;
etype(){next=0;}
etype(int _t, int _c, etype* _n){t=_t, c=_c,... |
512 | D | Fox And Travelling | Fox Ciel is going to travel to New Foxland during this summer.
New Foxland has $n$ attractions that are linked by $m$ undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has $k$ days to visit this city and each day she will visit exactly one attraction.
There is one important ... | We could find that some nodes cannot be visited. And more specific, if one node is in a cycle then it cannot be visited. So what about the structure of nodes that we can visit? Let's first find a way to get all nodes that could be visited. We can deal with this by something like biconnected decomposition, but that is n... | [
"dp",
"trees"
] | 2,900 | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <map>
#include <set>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
const int MAXN = 101; // ... |
512 | E | Fox And Polygon | Fox Ciel just designed a puzzle game called "Polygon"! It is played using triangulations of a regular $n$-edge polygon. The goal is to transform one \underline{triangulation} to another by some tricky rules.
\underline{Triangulation} of an $n$-edge poylgon is a set of $n - 3$ diagonals satisfying the condition that no... | Triangulation of polygon is something hard to think about. So the first key observation is that, we can transform this task into operations on rooted trees! One Triangulation of polygon can be mapping to one rooted tree. And the flip operation can be mapping to the rotation of trees. (It is the operation we used to bal... | [
"constructive algorithms",
"divide and conquer"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
int n;
vector <int> e[1001];
bool have[1001];
struct node
{
int leftMark, rightMark;
node* sonLeft, *sonRight;
void updateMark()
{
leftMark = sonLeft->leftMark;
rightMark = sonRight->rightMark;
}
}*start, *want;
struct step
{
int fromA, fromB;
int toA, toB;
};... |
514 | A | Chewbaсca and Number | Luke Skywalker gave Chewbacca an integer number $x$. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit $t$ means replacing it with digit $9 - t$.
Help Chewbacca to transform the initial number $x$ to the minimum possible \textbf{positive} number by inverting some (possibly, zero) d... | It is obvious that all the digits, which are greater than 4, need to be inverted. The only exception is 9, if it's the first digit. Complexity: $O(\mathrm{number~length})$ | [
"greedy",
"implementation"
] | 1,200 | null |
514 | B | Han Solo and Lazer Gun | There are $n$ Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates $(x, y)$ on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point $(x_{0}, y_{0})$. In one shot ... | Let's run through every point, where the stormtroopers are situated. If in current point stormtroopers are still alive, let's make a shot and destroy every stormtrooper on the same line with gun and current point. Points $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, $(x_{3}, y_{3})$ are on the same line, if $(x_{2} - x_{1})(y_{3... | [
"brute force",
"data structures",
"geometry",
"implementation",
"math"
] | 1,400 | null |
514 | C | Watto and Mechanism | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with $n$ strings. Then the mechanism should be able to process queries of the following type: "Given string $s$, determine if the memory of the ... | While adding a string to the set, let's count its polynomial hash and add it to an array. Then let's sort this array. Now, to know the query answer, let's try to change every symbol in the string and check with binary search if its hash can be found in the array (recounting hashes with $O(1)$ complexity). If the hash i... | [
"binary search",
"data structures",
"hashing",
"string suffix structures",
"strings"
] | 2,000 | null |
514 | D | R2D2 and Droid Army | An army of $n$ droids is lined up in one row. Each droid is described by $m$ integers $a_{1}, a_{2}, ..., a_{m}$, where $a_{i}$ is the number of details of the $i$-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has $m$ weapons, the $i$-th weapon can af... | To destroy all the droids on a segment of $l$ to $r$, we need to make $\sum_{j=1}^{m}\operatorname*{max}_{l\leq l\leq r}(c n t[i]|j])$ shots, where $cnt[i][j]$ - number of $j$-type details in $i$-th droid. Let's support two pointers - on the beginning and on the end of the segment, which we want to destroy all the droi... | [
"binary search",
"data structures",
"two pointers"
] | 2,000 | null |
514 | E | Darth Vader and Tree | When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly $n$ sons, at that for each node, the distance between it an its $i$-th left child equals to $d_{i}$. The Sith Lord loves counting the number of nodes in the tree that are at a distanc... | It's easy to realize that $d p[i]=\sum_{j=1}^{100}c n t[j]\cdot d p[i-j]$, where $dp[i]$ is number of vertices, which are situated on a distance $i$ from the root, and $cnt[j]$ is number of children, which are situated on a distance $j$. Answer $a n s=\sum_{i=0}^{x}d p[i]$. Let the dynamics condition Let's build a tran... | [
"dp",
"matrices"
] | 2,200 | null |
515 | A | Drazil and Date | Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point $(0, 0)$ and Varda's home is located in point $(a, b)$. In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position $(x, y)$ he can go to posit... | If Drazil chooses the shortest path from (0,0) to (a,b), it takes $|a| + |b|$ steps. So we know that all numbers less than $|a| + |b|$ are impossible to be the number of steps that Drazil took. Now consider when the number of steps is not less than $|a| + |b|$. When Drazil arrives at $(a, b)$, he can take two more step... | [
"math"
] | 1,000 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
515 | B | Drazil and His Happy Friends | Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\... | You may notice that Drazil invites his friends periodically, and the period of invitation patterns is at most $n * m$ (because there are only $n * m$ possible pairs of boys and girls). So if no one changes from unhappy to happy in consecutive $n * m$ days, there won't be any changes anymore since then. We can simulate ... | [
"brute force",
"dsu",
"meet-in-the-middle",
"number theory"
] | 1,300 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
515 | C | Drazil and Factorial | Drazil is playing a math game with Varda.
Let's define $\operatorname{F}(x)$ for positive integer $x$ as a product of factorials of its digits. For example, $\mathbf{F}(\,135)=\,1!*31*51=720$.
First, they choose a decimal number $a$ consisting of $n$ digits that contains at least one digit larger than $1$. This numbe... | Conclusion first: First, we transform each digit of the original number as follows: 0, 1 -> empty 2 -> 2 3 -> 3 4 -> 322 5 -> 5 6 -> 53 7 -> 7 8 -> 7222 9 -> 7332 Then, sort all digits in decreasing order as a new number, then it will be the answer. Proof: We can observe that our answer won't contain digits 4,6,8,9, be... | [
"greedy",
"math",
"sortings"
] | 1,400 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
515 | D | Drazil and Tiles | Drazil created a following problem about putting $1 × 2$ tiles into an $n × m$ grid:
"There is a grid with some cells that are empty and some cells that are occupied. You should use $1 × 2$ tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."
Bu... | Again we give conclusion first: First, view each cell as a vertex and connect two adjacent cells by an edge. Then, build a queue and push all vertices of degree 1 in it. Finally, in each iteration, we pop a vertex from the queue until the queue is empty. If the vertex is used, go to the next iteration. Otherwise, we pu... | [
"constructive algorithms",
"greedy"
] | 2,000 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
515 | E | Drazil and Park | Drazil is a monkey. He lives in a circular park. There are $n$ trees around the park. The distance between the $i$-th tree and ($i + 1$)-st trees is $d_{i}$, the distance between the $n$-th tree and the first tree is $d_{n}$. The height of the $i$-th tree is $h_{i}$.
Drazil starts each day with the morning run. The mo... | There are many methods for this problem. I'll only explain the one that I used. Let's split a circle at some point (for example between 1 and n) and draw a picture twice (i. e. 1 2 3 ... n 1 2 3 ... n), thus changing the problem from a circle to a line. Remember that if two trees Drazil chooses are x and y, the energy ... | [
"data structures"
] | 2,300 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
516 | D | Drazil and Morning Exercise | Drazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.
Let's consider rooms and small tunnels as th... | We can use dfs twice to get the farthest distance from each node to any leaves (detail omitted here), and denote the longest distance from the $i$-th node to any leaves as $d_{i}$. Then we choose a node with minimum value of $d_{i}$ as the root. We will find that for any node $x$, $d_{x}$ isn't greater than $d_{y}$ for... | [
"dfs and similar",
"dp",
"dsu",
"trees",
"two pointers"
] | 2,800 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
516 | E | Drazil and His Happy Friends | Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\... | Simplifying this question, suppose that $n$ and $m$ are coprime. If $n$ and $m$ are not coprime and the gcd of $n$ and $m$ is $g$, then we can divide all people into $g$ groups by the values of their id mod $g$ and find the maximum answer between them. Obviously, If there is at least one group of friends which are all ... | [
"math",
"number theory"
] | 3,100 | #include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y... |
518 | A | Vitaly and Strings | Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings $s$ and $t$ to Vitaly. The strings have the same length, they consist of lowercase Englis... | To solve this problem we can, for example, find string $next$, which lexicographically next to string $s$ and check that string $next$ is lexicographically less than string $t$. If string $next$ is lexicographically smaller than string $t$, print string $next$ and finish algorithm. If string $next$ is equal to string $... | [
"constructive algorithms",
"strings"
] | 1,600 | null |
518 | B | Tanya and Postcard | Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string $s$ of length $n$, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string $s... | To solve this problem at first will count array $cnt[]$, where $cnt[c]$ - how many times letter $c$ found in string $t$. We will count two numbers $ans1$ and $ans2$ - how many times Tanya will shouts joyfully $YAY!$ and how many times Tanya will says $WHOOPS$. Let's iterate on string $s$ and if $cnt[s[i]] > 0$, then in... | [
"greedy",
"implementation",
"strings"
] | 1,400 | null |
518 | C | Anya and Smartphone | Anya has bought a new smartphone that uses \underline{Berdroid} operating system. The smartphone menu has exactly $n$ applications, each application has its own icon. The icons are located on different screens, one screen contains $k$ icons. The icons from the first to the $k$-th one are located on the first screen, fr... | To solve this problem we will store two arrays - $a[]$ and $pos[]$. In array $a[]$ will store current order of icons, i. e. in $a[i]$ store number of application, icon which stay on position $i$. In array $pos[]$ will store on which place in list stays icons, i. e. in $pos[i]$ store in which position of array $a[]$ sta... | [
"constructive algorithms",
"data structures",
"implementation"
] | 1,600 | null |
518 | D | Ilya and Escalator | Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.
Let's assume that $n$ people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue ent... | To solve this problem let's use dynamic programming. We will store two-dimensional array $z[][]$ with type $double$. In $z[i][j]$ will store the likelihood that after $i$ seconds $j$ people are on escalator. In dynamic will be following transitions. If $j = n$, i. e. all $n$ people already on escalator then we make tra... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 1,700 | null |
518 | E | Arthur and Questions | After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length $n$ ($a_{1}, a_{2}, ..., a_{n})$, consisting of integers and integer $k$, not exceeding $n$.
This sequence had the following property: if you write out the sums of all its segments consisting of $k$ consecutive elements ... | At first let's take two sums $a_{1} + a_{2} + ... + a_{k}$ and $a_{2} + a_{3} + ... + a_{k + 1}$. It is correct that $a_{1} + a_{2} + ... + a_{k} < a_{2} + a_{3} + ... + a_{k + 1}$. If move from right to left all elements apart from $a_{k + 1}$, all of them will reduce and will left only $a_{1} < a_{k + 1}$. If write f... | [
"greedy",
"implementation",
"math",
"ternary search"
] | 2,200 | null |
518 | F | Pasha and Pipe | On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city.
The city is an $n × m$ rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares a... | At first let's count two two-dimensional arrays of prefix sums $sumv[][]$ and $sumg[][]$. In $sumv[i][j]$ store how many grids are in column $j$ beginning from row $1$ to row $i$. In $sumg[i][j]$ store how many grid are in row $i$ beginning from column $1$ to column $j$. Let's count $ans0$ - how many pipes without bend... | [
"binary search",
"brute force",
"combinatorics",
"dp",
"implementation"
] | 2,300 | null |
519 | A | A and B and Chess | A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
- the queen's weight is 9,
- the rook's weight is 5,
- the bishop's ... | This problem asked to determine whose chess position is better. Solution: Iterate over the board and count scores of both player. Then just output the answer. Complexity: $O(n^{2})$, where n is the length of the side of the board (8 here) | [
"implementation"
] | 900 | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long... |
519 | B | A and B and Compilation Errors | A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed $n$ compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix... | In this problem you were given three arrays. Second array is the same as the first array without one element, third array is the same as second array without first element. You were asked to find deleted elements. Solution: I'll describe easiest solution for this problem: Let's denote $a$ as sum of all elements of firs... | [
"data structures",
"implementation",
"sortings"
] | 1,100 | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long... |
519 | C | A and B and Team Training | A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi... | In this problem we should split $n$ experienced participants and $m$ newbies into teams. Solution: Let's denote number teams with 2 experienced partisipants and 1 new participant as $type1$ and teams with 1 experienced participant and 2 new participants as $type2$. Let's fix number of teams of $type1$ and denote it as ... | [
"greedy",
"implementation",
"math",
"number theory"
] | 1,300 | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long... |
519 | D | A and B and Interesting Substrings | A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a ... | In this problem you were asked to find number of substrings of given string, such that each substring starts and finishes with one and the same letter and sum of weight of letters of that substring without first and last letter is zero. Solution: Let's denote $sum[i]$ as sum of weights of first $i$ letters. Create 26 $... | [
"data structures",
"dp",
"two pointers"
] | 1,800 | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long... |
519 | E | A and B and Lecture Rooms | A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has $n$ rooms connected by $n - 1$ corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from $1$ ... | In this problem we have to answer to the following queries on tree: for given pairs of vertices your program should output number of eqidistand vertices from them. Let's denote: $dist(a, b)$ as distance between vertices $a$ and $b$. $LCA(a, b)$ as lowest common ancestor of vertices $a$ and $b$. $depth[a]$ as distance b... | [
"binary search",
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,100 | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long... |
520 | A | Pangram | A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the l... | [
"implementation",
"strings"
] | 800 | null |
520 | B | Two Buttons | Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | The simplest solution is simply doing a breadth-first search. Construct a graph with numbers as vertices and edges leading from one number to another if an operation can be made to change one number to the other. We may note that it is never reasonable to make the number larger than $2m$, so under provided limitations ... | [
"dfs and similar",
"graphs",
"greedy",
"implementation",
"math",
"shortest paths"
] | 1,400 | null |
520 | C | DNA Alignment | Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings $s$ and $t$ have the same length $n$, then the function $h(s, t)$ is defined as the number of positions... | What is $ \rho (s, t)$ equal to? For every character of $s$ and every character of $t$ there is a unique cyclic shift of $t$ that superposes these characters (indeed, after 0, $...$, $n - 1$ shifts the character in $t$ occupies different positions, and one of them matches the one of the character of $s$); therefore, th... | [
"math",
"strings"
] | 1,500 | null |
520 | D | Cubes | Once Vasya and Petya assembled a figure of $m$ cubes, each of them is associated with a number between $0$ and $m - 1$ (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the $OX$ is the ground, and the $OY$ is directed upwards. Each cube is associated with the coordinates of it... | Basically, the first player should maximize the lexicographical order of numbers, and the second player should minimize it. Thus, at every move the first player should choose the largest available number, and the second should choose the minimal one. First of all, how do we check if the cube can be removed? It is impos... | [
"games",
"greedy",
"implementation"
] | 2,100 | null |
520 | E | Pluses everywhere | Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out $n$ numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, n... | Consider some way of placing all the pluses, and a single digit $d_{i}$ (digits in the string are numbered starting from 0 from left to right). This digit gives input of $d_{i} \cdot 10^{l}$ to the total sum, where $l$ is the distance to the nearest plus from the right, or to the end of string if there are no pluses th... | [
"combinatorics",
"dp",
"math",
"number theory"
] | 2,200 | null |
521 | D | Shop | Vasya plays one very well-known and extremely popular MMORPG game. His game character has $k$ skill; currently the $i$-th of them equals to $a_{i}$. Also this game has a common rating table in which the participants are ranked according to the \textbf{product} of all the skills of a hero in the descending order.
Vasya... | Suppose the only type of upgrades we have is multiplication. It doesn't even matter for the answer which particular skill we are going to multiply, so we just choose several upgrades with greatest values of $b_{i}$. Now we have additions as well; set multiplications aside for a moment. It is clear that for every skill ... | [
"greedy"
] | 2,800 | null |
521 | E | Cycling City | You are organizing a cycling race on the streets of the city. The city contains $n$ junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.
You want the race to be open to b... | We have to find two vertices in an undirected graph such that there exist three vertex- and edge-independent paths between them. This could easily be a flow problem if not for the large constraints. First of all, we can notice that all the paths between vertices should lie in the same biconnected component of the graph... | [
"dfs and similar",
"graphs"
] | 3,100 | null |
524 | C | The Art of Dealing with ATM | ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most $k$ bills from it, and the ... | Intended solution has the complexity $O(n k\log(n k)+q n k)$ or $O(n k\log(n k)+q n k\log(n k))$. For each possible value $x$ that we can get write a pair $(x, m)$ where $m$ is number of bills to achieve this value. Sort this array in ascending order of $x$ and leave only the best possible number of bills for each valu... | [
"binary search",
"sortings"
] | 1,900 | null |
524 | D | Social Network | Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarp... | Let's follow greedily in following way. Iterate over all requests in a chronological order. Let's try to associate each query to the new person. Of course we can't always do that: when there are already $M$ active users on a site, we should associate this request with some existing person. Now we need to choose, who it... | [
"greedy",
"two pointers"
] | 2,100 | null |
524 | E | Rooks and Rectangles | Polycarpus has a chessboard of size $n × m$, where $k$ rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated $q$ rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of ... | Let's understand what does it mean that some cell isn't attacked by any rook. It means that there exists row and column of the rectangle without rooks on them. It's hard to check this condition, so it is a good idea to check the opposite for it. We just shown that the rectangle is good if on of the two conditions holds... | [
"data structures",
"sortings"
] | 2,400 | null |
524 | F | And Yet Another Bracket Sequence | Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations:
- adding any bracket in any position (in the beginning, the end, or between any two existing brackets);
- cyclic shift — moving t... | The main idea is that the bracket sequence can be seen as a sequence of prefix balances, i. e sequence $(a_{i})$ such that $a_{i + 1} = a_{i} \pm 1$. Calculate the number of opening brackets $A$ and closing brackets $B$ in original string. It is true that if $A > = B$ then the string can be fixed by adding $A - B$ cl... | [
"data structures",
"greedy",
"hashing",
"string suffix structures",
"strings"
] | 2,700 | null |
525 | A | Vitaliy and Pie | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with $n$ room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ... | To solve this problem we need to use array $cnt[]$. In this array we will store number of keys of every type, which we already found in rooms, but didn't use. Answer will store in variable ans. Now, we iterate on string. If current element of string $s_{i}$ is lowercase letter (key), we make $cnt[s_{i}]$++. Else if cur... | [
"greedy",
"hashing",
"strings"
] | 1,100 | null |
525 | B | Pasha and String | Pasha got a very beautiful string $s$ for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to $|s|$ from left to right, where $|s|$ is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha ... | At first we need to understand next fact - it doesn't matter in wich order make reverses, answer will be the same for all orders. Let's numerate elements of string from one. To solve given problem we need to count how many reverses will begin in every position of string. Then we need to count array $sum[]$. In $sum[i]$... | [
"constructive algorithms",
"greedy",
"math",
"strings"
] | 1,400 | null |
525 | C | Ilya and Sticks | In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of $n$ sticks and an instrument. Each stick is characterized by its length $l_{i}$.
Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way th... | This problem can be solved with help of greedy. At first count array $cnt[]$. In $cnt[i]$ will store how many sticks with length $i$ we have. Now iterate for len from maximal length of sticks to minimal. If $cnt[len]$ is odd and we have sticks with length $len - 1$ (that is $cnt[len - 1] > 0$), make $cnt[len]$-- and $c... | [
"greedy",
"math",
"sortings"
] | 1,600 | null |
525 | D | Arthur and Walls | Finally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.
Plan of the apartment found by Arthur looks like a rectangle $n × m$ consisting of squares of size $1 × 1$. Each of those squares contains either a wall (such square is d... | To solve this problem we need to observe next fact. If in some square whith size $2 \times 2$ in given matrix there is exactly one asterisk, we must change it on dot. That is if in matrix from dots and asterisks is not square $2 \times 2$ in which exactly one asterisk and three dots, then all maximum size of the ar... | [
"constructive algorithms",
"data structures",
"graphs",
"greedy",
"shortest paths"
] | 2,400 | null |
525 | E | Anya and Cubes | Anya loves to fold and stick. Today she decided to do just that.
Anya has $n$ cubes lying in a line and numbered from $1$ to $n$ from left to right, with natural numbers written on them. She also has $k$ stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.
Anya can... | To solve this problem we need to use meet-in-the-middle. At first sort given array in increasing order and divide it in two parts. In first part must be first $n / 2$ elements, in second part - other. Iterate all submasks of all masks of elements from first part. That is iterate which cubes from first part we take and ... | [
"binary search",
"bitmasks",
"brute force",
"dp",
"math",
"meet-in-the-middle"
] | 2,100 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.