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
356
A
Knight Tournament
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname...
Let's the current fight $(l, r, x)$ consists of $K$ knights fighting. Then all we have to do is to find all these knights in time $O(K)$ or $O(KlogN)$. There are several ways to do that, let's consider some of them. The first way is to store the numbers of all alive knights in std::set (C++) or TreeSet (Java). Then in ...
[ "data structures", "dsu" ]
1,500
null
356
B
Xenia and Hamming
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance. The Hamming distance between two strings $s = s_{1}s_{2}... s_{n}$ and $t = t_{1}t_{2}... t_{n}$ of equal length $n$ is value $\sum_{i=1}^{n}[s_{i}\neq t_{i}]$. Record $[s_{i} ≠ t_{i}]$ is the Iverson notation and represents...
Let's denote the length of the first string as $lenX$, the length of the second string as $lenY$. Let $L = LCM(lenX, lenY)$. It's obvious that $L$ is a period of the long strings $a$ and $b$, so we can find the distance of its' prefixes of length $L$ and multiply the answer by $\frac{t e n(a)}{L}$. Let's fix the positi...
[ "implementation", "math" ]
1,900
null
356
C
Compartments
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of $n$ compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they ...
In the problem you should come up with some right greedy algorithm. One of correct approaches acts as follows: Firstly, it joins all "twos" and "ones" (to get "threes"). Several "ones" should be moved. Then you should consider two cases depend on amounts of "ones" and "twos". If initially you have more "ones", you shou...
[ "combinatorics", "constructive algorithms", "greedy", "implementation" ]
2,100
null
356
D
Bags and Coins
When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite si...
It's easy to see that bags and their relations "lies directly in" should form directed forest. Each vertex should be given value $c_{i}$ - the number of coins in the corresponding bag. Let's denote the sum of values $c_{j}$ in the subtree of vertex $i$ as $f_{i}$. The following conditions should be met: $f_i = a_i$ the...
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
2,700
null
356
E
Xenia and String Problem
Xenia the coder went to The Olympiad of Informatics and got a string problem. Unfortunately, Xenia isn't fabulous in string algorithms. Help her solve the problem. String $s$ is a sequence of characters $s_{1}s_{2}... s_{|s|}$, where record $|s|$ shows the length of the string. Substring $s[i... j]$ of string $s$ is ...
During the contest most of participants write the solutions that are very similar to the author's one. One of the author's solution uses hashes (but there exist solution without it), you can see short description of the solution below: For each position $i$ calculate with hashes the maximal value of $L_{i}$, such that ...
[ "dp", "hashing", "implementation", "string suffix structures", "strings" ]
3,000
null
357
A
Group of Students
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to $m$ points. We know that $c_{1}$ schoolchildren g...
In this problem you need to iterate over all possible values of passing rate from 1 to 100 and for each value calculate the sizes of two groups.
[ "brute force", "greedy", "implementation" ]
1,000
null
357
B
Flag Day
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: - overall, there must be $m$ dances; - exactly three people must take part in each dance; - each da...
Let's process the dances in the given order and determine the colors of dancers' clothes. If there are no dancer from some previous dance, we can give the dances different colors arbitrarily. And if there is such dancer, we already know the color of his clothes. So, we arbitrarily distribute the other two colors betwee...
[ "constructive algorithms", "implementation" ]
1,400
null
358
A
Dima and Continuous Line
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of $n$ distinct points on the abscissa axis and asked to consecutively connect th...
If our line has self-intersections, that some pair of semi-circles exists, which intersect each other. Let points $x_{1}$ < $x_{2}$ are connected with a semi-circle and points $x_{3}$ < $x_{4}$ are connected with another semi-circle. Then this semis-circles intersect if one of the conditions is true: 1). $x_{1} < x_{3}...
[ "brute force", "implementation" ]
1,400
null
358
B
Dima and Text Messages
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. ...
It's clear, that adding new random symbols means, that we can simply omit them, they don't change the structure of the phrase: $< 3word_{1} < 3word_{2} < 3... word_{N} < 3$. Let's determine the phrase before inserting random elements: $s = " < 3" + word1 + " < 3" + ... + " < 3" + wordN + " < 3"$. Lets $i$ -is an index ...
[ "brute force", "strings" ]
1,500
null
358
C
Dima and Containers
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck. Inna wants her present to show Dima how great a programmer he is. For that, she is going to g...
We know all the numbers at the beginning, so, it's clear, that we want pop three maximums. We can "precalculate " maximums with finding next zero and iterating through all numbers between two zeroes. We should do pops from different containers, so let's save maximums in the top of the stack, in the beginning of the que...
[ "constructive algorithms", "greedy", "implementation" ]
2,000
null
358
D
Dima and Hares
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her $n$ hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to $n$ from left to right and started feeding them wit...
Let's look at the first hare: we chose them befoe second, or after. If it is chosen after the second, than the solution from the 2nd hare to the last doesn't depend on the first one, otherwise, we will receive the same but before the second hair will be obviously the feed hair. So, we have two dinamics: 1). $d0i$ - ans...
[ "dp", "greedy" ]
1,800
null
358
E
Dima and Kicks
Dima is a good person. In fact, he's great. But all good things come to an end... Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle $n × m$ consisting of unit squares. For the beginning, Seryozha put Dima in a center of some square. Then...
The first thing to understand is that the answer is the divisor of maximal-length sequence of standing one by one ones. $(1111 \dots 11)$ Let's iterate trough this number. Now we should check the table knowing the value of $K$. Let's find the most left of ones, and choose from them the most top. Let it be $(X, Y)$. the...
[ "brute force", "dsu", "graphs", "implementation" ]
2,300
null
359
A
Table
Simon has a rectangular table consisting of $n$ rows and $m$ columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the $x$-th row and the $y$-th column as a pair of numbers $(x, y)$. The table corners are ce...
If there are some good cell, which is located in the first row or in the first column, the answer is two. Similarly, if If there are some good cell, which is located in the last row or in the last column, the answer is two. Otherwise, the answer is four
[ "constructive algorithms", "greedy", "implementation" ]
1,000
null
359
B
Permutation
A permutation $p$ is an ordered group of numbers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each is no more than $n$. We'll define number $n$ as the length of permutation $p_{1}, p_{2}, ..., p_{n}$. Simon has a positive integer $n$ and a non-negative integer $k$, such that $2k ≤ n$. Help...
The answer is a slightly modified permutation $1, 2, ..., 2n$. Let's reverse numbers $2i - 1$ and $2i$ for each $1 \le i \le k$. It's not hard to understand, that this permutation is good.
[ "constructive algorithms", "dp", "math" ]
1,400
null
359
C
Prime Number
Simon has a prime number $x$ and an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. Simon loves fractions very much. Today he wrote out number ${\frac{1}{x^{a}!}}+{\frac{1}{x^{a}2}}+\ddots\div\nonumber+{\frac{1}{x^{a}n}}$ on a piece of paper. After Simon led all fractions to a common denominator and summed ...
Obviously, the answer is $x^{v}$. Let $sum = a_{1} + a_{2} + ... + a_{n}$. Also let $s_{i} = sum - a_{i}$ (the array of degrees). After that let's find value $v$ by the following algorithm: Let's consider a sequence of degrees as decreasing sequence. Now we will perform the following operation until it's possible to pe...
[ "math", "number theory" ]
1,900
null
359
D
Pair of Numbers
Simon has an array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Today Simon asked you to find a pair of integers $l, r$ $(1 ≤ l ≤ r ≤ n)$, such that the following conditions hold: - there is integer $j$ ($l ≤ j ≤ r$), such that all integers $a_{l}, a_{l + 1}, ..., a_{r}$ are divisible by $a_{j}$; -...
Quite simple note: if the pair $(l, r)$ satisfies the condition 1 from the statements, then $min(l, r) = GCD(l, r)$, where $min(l, r)$ is smallest number $a_{i}$ from the segment (l, r) and $GCD(l, r)$ is a GCD of all numbers from the segment (l, r). Calculate some data structure that will allow us to respond quickly t...
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
2,000
null
359
E
Neatness
Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house. Simon's house looks like a rectangular table consisting of $n$ rows and $n$ columns from above. All rows of the table are numbered from $1$ to $n$ from top to bottom. All columns of the table are numbered from $1$ to $n$ f...
You should write recursive function, that will turn on the light in all rooms, where it's possible. Also this function will visit all rooms, which it may visit. Let this function is called paint(x, y), where x, y is the current room. $Paint(x, y)$ will use following idea: Let's look at all neighbors. If there is a ligh...
[ "constructive algorithms", "dfs and similar" ]
2,400
null
360
A
Levko and Array Recovery
Levko loves array $a_{1}, a_{2}, ... , a_{n}$, consisting of integers, very much. That is why Levko is playing with array $a$, performing all sorts of operations with it. Each operation Levko performs is of one of two types: - Increase all elements from $l_{i}$ to $r_{i}$ by $d_{i}$. In other words, perform assignment...
Let's find such value $b[i]$ that $a[i] \le b[i]$ for all indeces $i$. Let's simulate all operations and $diff[i]$ will be the difference between current value of $i$-th element and its initial value. If we have operation of first type, we change values of $diff[i]$. If we have operation of second type, we know that ...
[ "greedy", "implementation" ]
1,700
null
360
B
Levko and Array
Levko has an array that consists of integers: $a_{1}, a_{2}, ... , a_{n}$. But he doesn’t like this array at all. Levko thinks that the beauty of the array $a$ directly depends on value $c(a)$, which can be calculated by the formula: \[ c(a)=\operatorname*{max}_{1<i<n-1}|a_{i+1}-a_{i}|,n>1;c(a)=0,0\leq n\leq1. \] Th...
Let's solve this problem using binary search. We need to check whether we can achieve an array, when $c(a)$ will be at most $x$. Lets make dp. $dp[i]$ means minimal number of elements with indeces less than $i$, which we need to change, but we don't change $i$-th element. Let's iterate next element $j$, which we don't ...
[ "binary search", "dp" ]
2,000
null
360
C
Levko and Strings
Levko loves strings of length $n$, consisting of lowercase English letters, very much. He has one such string $s$. For each string $t$ of length $n$, Levko defines its beauty relative to $s$ as the number of pairs of indexes $i$, $j$ $(1 ≤ i ≤ j ≤ n)$, such that substring \textbf{$t[i..j]$ is lexicographically larger t...
Let's count amount of such substrings of $t$ that are bigger than corresponding substring of $s$ and begin at the position $i$. If $t[i] < s[i]$, this amount equals $0$. If $t[i] > s[i]$, this amount equals $n - i$. If $t[i] = s[i]$, then let's find such nearest position $j, j > i$ , that $t[j] \neq s[j]$. If $t[j] >...
[ "combinatorics", "dp" ]
2,500
null
360
D
Levko and Sets
Levko loves all sorts of sets very much. Levko has two arrays of integers $a_{1}, a_{2}, ... , a_{n}$ and $b_{1}, b_{2}, ... , b_{m}$ and a prime number $p$. Today he generates $n$ sets. Let's describe the generation process for the $i$-th set: - First it has a single number $1$. - Let's take any element $c$ from thi...
$p$ is prime, so there exist primitive root $g$ modulo $p$(We don't need to find it, but we know that it exists). We can write $a_{i} = g^{ri}$. Note, that $i$-th set consists of all numbers $\frac{\vec{\mathbf{a}}}{a_{i}^{j=1}}b_{j}.c_{j}$, where $c_{j} \ge 0$, or we can write it as ${g^{t}}_{j=1}^{\infty}b_{j}.c_{j...
[ "number theory" ]
2,600
null
360
E
Levko and Game
Levko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game. The city consists of $n$ intersections connected by $m + k$ directed roads. Two or more roads can connect the same pair of intersections. Besides, there ...
Algorithm: Firstly we will solve problem if first player can win. Let's make all roads that we can change equal to $r[i]$ and do two Dijkstra's algorithms from vertices $s_{1}$ and $s_{2}$. Let's $d1[i]$ be the distance from $s_{1}$ to $i$, $d2[i]$ be the distance from $s_{2}$ to $i$. Consider a road, that we can chang...
[ "graphs", "greedy", "shortest paths" ]
2,800
null
361
A
Levko and Table
Levko loves tables that consist of $n$ rows and $n$ columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals $k$. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Matrix,in which all diagonal elements equal $k$ and other elements equal $0$, satisfied all conditions. For example, if n = 4 and k = 7, our matrix will be 7 0 0 0 0 7 0 0 0 0 7 0 0 0 0 7
[ "constructive algorithms", "implementation" ]
800
null
361
B
Levko and Permutation
Levko loves permutations very much. A permutation of length $n$ is a sequence of distinct positive integers, each is at most $n$. Let’s assume that value $gcd(a, b)$ shows the greatest common divisor of numbers $a$ and $b$. Levko assumes that element $p_{i}$ of permutation $p_{1}, p_{2}, ... , p_{n}$ is good if $gcd(i...
$gcd(1, m) = 1$, so if $n = k$, there is no suitable permutation. It is well known that $gcd(m, m - 1) = 1$. Lets construct following permutation. It has exactly $k$ good elements. $n - k 1 2 3 ... n - k - 1 n - k + 1 n - k + 2 ... n$
[ "constructive algorithms", "math", "number theory" ]
1,200
null
362
A
Two Semiknights Meet
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: $2$ squares forward and $2$ squares to the right, $2$ squares forward and $2$ squares to the left, $2$ squares backward and $2$ to the right and $2$ squares backward a...
Autors have proposed different solutions. One can notice that if semiknights did not have a meeting after first step (it is not necessary they have a meeting in "good" square), they will not meet at all. This fact appears from board size and possible semiknight's moves. As the initial semiknight's squares are considere...
[ "greedy", "math" ]
1,500
null
362
B
Petya and Staircases
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. No...
One has to note that the number of dirty stairs $ \le 3000$. Petya can reach stair number $n$ if the first and the last stairs are not dirty and there are not three or more dirty stairs in a row. So let sort the array of dirty stairs and go through it, checking for three or more consecutive dirty stairs. Also one need...
[ "implementation", "sortings" ]
1,100
null
362
C
Insertion Sort
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array $a$ of size $n$ in the non-d...
The number of times swap is called equals the number of inversions in the input permutation. It's easy to see that it is reasonable to swap only such elements $a_{i}$, $a_{j}$ that $i < j$ and $a_{i} > a_{j}$ (otherwise the number of inversions will increase). Let $d_{i, j}$ be the number of permutation of elements wit...
[ "data structures", "dp", "implementation", "math" ]
1,900
null
362
D
Fools and Foolproof Roads
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of $n$ cities, some pairs of cities are connected by bidirectional roads, each road is described by its length $l_{i}$. The...
If the given graph contains less than $q$ connectivity components, then there's no solution. Otherwise it's optimal at first add edges that connect different components and afterwards all remaining edges (they will be connect edges from one component). For the first phase you can use greedy algorithm: each time you sel...
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
2,100
null
362
E
Petya and Pipes
A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in. The Berland capital has $n$ water ...
Construct the following flow network. Water tank $1$ is the source, water tank $n$ is the sink. Every pipe from water tank $u$ to water tank $v$ is presented as two arcs - the first one with capacity $c_{uv}$ and cost $0$ and the second one with infinite capacity and cost $1$. Thus, the answer is the maximum flow with ...
[ "flows", "graphs", "shortest paths" ]
2,300
null
363
A
Soroban
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about ...
Not so much to say about this problem. You need to extract the digits of the given number (read it as string or repeteadly divide by 10 and take the remainders). Then carefully do the mapping of digits to its' representation.
[ "implementation" ]
800
null
363
B
Fence
There is a fence in front of Polycarpus's home. The fence consists of $n$ planks of the same width which go one after another from left to right. The height of the $i$-th plank is $h_{i}$ meters, distinct planks can have distinct heights. \begin{center} {\small Fence for $n = 7$ and $h = [1, 2, 6, 1, 1, 7, 1]$} \end{c...
Another easy problem. We need to calculate the sum of every consequtive segment of $k$ planks. One way to do this is to calculate partial prefix sums: $s_{i}=\sum_{j\leq i}h_{j}$. Then the sum of heights of the planks $i, i + 1, ..., i + k - 1$ is $s_{i + k - 1} - s_{i - 1}$. The other approach is to calculate the sum ...
[ "brute force", "dp" ]
1,100
null
363
C
Fixing Typos
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ...
The general idea of the solution is the following: while there are three consequtive equal characters, remove any one of them. After that we can only have typos of the second type. So, if we have one couple of equal characters immediately after another couple of equal characters ($xxyy$), we need to decide which charac...
[ "greedy", "implementation" ]
1,400
null
363
D
Renting Bikes
A group of $n$ schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them. The renting site offered them $m$ bikes. The renting price is different for different bikes, renting the $j$-th bike costs $p_{j}$ rubles. In total, the boys' shared budget is $a$ rubles. Besides, each of them h...
Let's do a binary search over the number of boys that can rent a bike. So let's say that we want to check whether it possible for $k$ boys to rent bikes. If some $k$ boys can rent a bike, then the $k$ "richest" boys (with the most amount of personal money) also can do that. It is easy to see that if they can rent bikes...
[ "binary search", "greedy" ]
1,800
null
364
A
Matrix
You have a string of decimal digits $s$. Let's define $b_{ij} = s_{i}·s_{j}$. Find in matrix $b$ the number of such rectangles that the sum $b_{ij}$ for all cells $(i, j)$ that are the elements of the rectangle equals $a$ in each rectangle. A rectangle in a matrix is a group of four integers $(x, y, z, t)$ \textbf{$(x...
Let's notice that sum in the rectangle $(x1, y1, x2, y2)$ is $sum(x1, x2) \cdot sum(y1, y2)$. Where $sum(l, r) = s_{l} + s_{l + 1} + ... + s_{r}$. Then, we have to calc $sum(l, r)$ for every pair $(l, r)$ and count how many segments give us sum $x$ for any possible x ($0 \le x \le 9 \cdot |s|$). In the end we shoul...
[ "combinatorics", "data structures", "implementation" ]
1,600
null
364
B
Free Market
John Doe has recently found a "Free Market" in his city — that is the place where you can exchange some of your possessions for other things for free. John knows that his city has $n$ items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that ea...
We may assume that John may exchange any subset of his items $x$ to any other subset $y$, such as $s(x) + d \ge s(y)$ (it does not matter if $x$ intersects $y$). We can find all possible sums in subset of elements of the given set of items using standard dp (knapsack problem). John should always exchange all his curr...
[ "dp", "greedy" ]
2,200
null
364
C
Beautiful Set
We'll call a set of positive integers $a$ beautiful if the following condition fulfills: for any prime $p$, if $\exists x\in a,x\equiv0\;\;\mathrm{mod}\;p$, then $|\{y\in a|y\equiv0\mathrm{\boldmath~\mod~}p\}|\geq\textstyle{\frac{\vert a|}{2}}$. In other words, if one number from the set is divisible by prime $p$, then...
We expected many unproved, but tested solutions. I think that careful prove of my solution with pen and paper is very difficult. So I will use some statistic-based facts. Consider the set of divisors of number $k$. One can check that it's beautiful set. If factorisation of $k$ has the form $\textstyle{\prod_{i=0}^{*}p_...
[ "brute force", "number theory" ]
2,300
null
364
D
Ghd
John Doe offered his sister Jane Doe find the gcd of some set of numbers $a$. Gcd is a positive integer $g$, such that all number from the set are evenly divisible by $g$ and there isn't such $g'$ $(g' > g)$, that all numbers of the set are evenly divisible by $g'$. Unfortunately Jane couldn't cope with the task and ...
Consider random element $a_{r}$ of $a$. With probabillity $\textstyle{\frac{1}{2}}$ $a\equiv0\mod g$ where $g$ is ghd of $a$. Let $x_{i} = gcd(a_{i}, a_{r})$. There are no more than $d$ distinct $x_{i}$ where $d$ is number of divisors of $a_{r}$. We can find number of $a_{i}$ such as $a_{i}\equiv0\mathrm{\boldmath~\mod...
[ "brute force", "math", "probabilities" ]
2,900
null
364
E
Empty Rectangles
You've got an $n × m$ table ($n$ rows and $m$ columns), each cell of the table contains a "0" or a "1". Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly $k$ times in the rectangle.
Let's find number of rectangles whick consist $k$ ones and intersect $y={\frac{m}{2}}$ in cartesian coordinate system. It's possible to do it in $n^{2} \cdot k$. We need to find closest $k$ ones on the top and on the bottom of the $y={\frac{m}{2}}$ and enumareate all segments $[l, r]$ such as $1 \le l \le r \le n...
[ "divide and conquer", "two pointers" ]
3,000
null
365
A
Good Number
Let's call a number $k$-good if it contains all digits not exceeding $k$ ($0, ..., k$). You've got a number $k$ and an array $a$ containing $n$ numbers. Find out how many $k$-good numbers are in $a$ (count each number every time it occurs in array $a$).
Task was to find the least digit, that is not contained in the given number and compare with given $k$.
[ "implementation" ]
1,100
null
365
B
The Fibonacci Segment
You have array $a_{1}, a_{2}, ..., a_{n}$. Segment $[l, r]$ ($1 ≤ l ≤ r ≤ n$) is good if $a_{i} = a_{i - 1} + a_{i - 2}$, for all $i$ $(l + 2 ≤ i ≤ r)$. Let's define $len([l, r]) = r - l + 1$, $len([l, r])$ is the length of the segment $[l, r]$. Segment $[l_{1}, r_{1}]$, is longer than segment $[l_{2}, r_{2}]$, if $le...
Good sequence may contain only zeroes or contain some positive number. In the second case such a sequence is not longer than sequence ${0, 1, 1, 2, 3, 5, 8, ..., x, y}$ where $y > 10^{9}$ and $x \le 10^{9}$. That's possible to find it using dummy algorithm. In the first case you may use binary search of two pointers.
[ "implementation" ]
1,100
null
366
A
Dima and Guards
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can b...
The solution doesn't exist only if the mimimal way to bribe is grater than $n$. Otherwise we can increase the gift price to make $price1$ + $price2$ = $n$. Let's find the miminal way to bribe. We should buy that gift for old lady which costs less. It means, if we have 2 guards with params $a$ $b$ $c$ $d$, then minimum ...
[ "implementation" ]
1,100
null
366
B
Dima and To-do List
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong. Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ...
Dima can make $k-1$ tasks, so Inna always tells him off for each $k$-th taks, beginning from the chosen place. So for the numbers with same modulo by k the answer will be the same. We should find the answer with minimal first task number so it is eniugh to calculate the sums of "tellings of" for tasks $0, 1... k-1$. We...
[ "brute force", "implementation" ]
1,200
null
366
C
Dima and Salad
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have $n$ fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit sal...
Let's calculate dinamic: $d[num][balance]$ where $num$ - last looked fruit, balance - difference between sum of colories and sum of tastes. Let's multiply each $b$ by $k$. The answer will be $d[n][0]$. $d[num][balance]$ = maximal possible sum of tastes under conditions. Step: from $d[num][balance]$ we can relax answers...
[ "dp" ]
1,900
null
366
D
Dima and Trap Graph
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate inter...
The answer for some path is a range under which we can go all the way, and this range is the intersection of all the ranges on the path. We can conclude it because the number is valid for path if it is valid for all ranges in the path. We will iterate all ribs. Let the left board of range on a rib is the left board of ...
[ "binary search", "data structures", "dfs and similar", "dsu", "shortest paths", "two pointers" ]
2,000
null
366
E
Dima and Magic Guitar
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with $n$ strings and $m$ frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the $i$-th string holding it on the $j$...
There are many solutions for this task. I will describe my, you can deal with other by looking participants code. To find the answer we should calculate $maxDis[k][k]$, where $maxDis[i][j]$ - maximal complexity from note $i$ to note $j$. Now we should only iterate the song updating answer for each pair of adjacent note...
[ "brute force", "implementation", "math" ]
2,200
null
367
A
Sereja and Algorithm
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as $q = q_{1}q_{2}... q_{k}$. The algorithm consists of two steps: - Find any continuous subsequence (substring) of three characters of string $q$, ...
If you look at what is written in the statment, it becomes clear that the algorithm finishes its work, if we can get a string like: $xx$, $yy$, $zz$, $zyxzyxzyx...$ and all its cyclic shuffles. To check you just need to know the number of letters $x$, $y$ and $z$ separately. Quantities can be counted using partial sums...
[ "data structures", "implementation" ]
1,500
null
367
B
Sereja ans Anagrams
Sereja has two sequences $a$ and $b$ and number $p$. Sequence $a$ consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Similarly, sequence $b$ consists of $m$ integers $b_{1}, b_{2}, ..., b_{m}$. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions $q$ $(q + (m - 1)·p ≤ n; q ≥ 1...
We will divide the sequence on $min(n, p)$ sequences. $1$-st, $(1 + p)$-th, $(1 + 2 \cdot p)$-th, ... element will go to the first sequence, $2$-nd, $(2 + p)$-th, $(2 + 2 \cdot p)$-th... will go to the second sequence and so on. Now you need to find an answer for each of them, considering that $p = 1$. This can be solv...
[ "binary search", "data structures" ]
1,900
null
367
C
Sereja and the Arrangement of Numbers
Let's call an array consisting of $n$ integer numbers $a_{1}$, $a_{2}$, $...$, $a_{n}$, beautiful if it has the following property: - consider all pairs of numbers $x, y$ $(x ≠ y)$, such that number $x$ occurs in the array $a$ and number $y$ occurs in the array $a$; - for each pair $x, y$ must exist some position $j$ ...
Clear that we need to collect as many of the most expensive properties that would have been possible to build the array. Note that having $n$ numbers, we have $m$ = $n \cdot (n - 1) / 2$ binding ties. See that this is a graph in which to do Euler path, adding as little as possible edges. For $n%2 = 1$ - everything is c...
[ "graphs", "greedy", "sortings" ]
2,000
null
367
D
Sereja and Sets
Sereja has $m$ non-empty sets of integers $A_{1}, A_{2}, ..., A_{m}$. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to $n$. In other words, for any integer $v$ $(1 ≤ v ≤ n)$ there is exactly one set $A_{t}$ such that $v\in A_{t}$. Also Sereja has integer $d$. Sereja decided...
Replace out sets by array, where the element - the number set to which its index belongs. Now take all the consequitive sub-arrays with lengths of $d$ and find a set of elements that were not found in that sub array. Clearly, if we as a response to select a subset of such set, it does not fit us. Remember all those "ba...
[ "bitmasks", "dfs and similar" ]
2,400
null
367
E
Sereja and Intervals
Sereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers $[l, r]$ $(1 ≤ l ≤ r ≤ m)$. Interval $[l_{1}, r_{1}]$ belongs to interval $[l_{2}, r_{2}]$ if the following condition is met: $l_{2} ≤ l_{1} ≤ r_{1} ≤ r_{2}$. Sereja wants to...
We assume that the intervals are sorted, and in the end we will multiply the answer by $n!$, We can do so, as all segments are different. Consider two cases $n > m$ and $n \le m$. It would seem that you need to write different dynamics for them, but not difficult to show that in the first case the answer is always $0...
[ "combinatorics", "dp" ]
2,700
null
368
A
Sereja and Coat Rack
Sereja owns a restaurant for $n$ people. The restaurant hall has a coat rack with $n$ hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the $i$-th hook costs $a_{i}$ rubles. Only one person can hang clothes on one hook. Tonight Sereja expects $m$ guests in the restaurant. Naturally, each g...
Each time we will go through the array and look for the minimal element which is not yet marked. If we find an item, we add it to the answer and mark it, otherwise we will subtract the penlty from answer.
[ "implementation" ]
1,000
null
368
B
Sereja and Suffixes
Sereja has an array $a$, consisting of $n$ integers $a_{1}$, $a_{2}$, $...$, $a_{n}$. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out $m$ integers $l_{1}, l_{2}, ..., l_{m}$ $(1 ≤ l_{i} ≤ n)$. For each number $l_{i}$ he wants to know how many distinct numbers ...
We will count value $ans_{i}$ - number of different elements on the suffix from $i$. For calculation will walk from the end of the array, and we count $ans_{i} = ans_{i + 1} + new_{ai}$, $new_{ai}$ equals to $1$, if element $a_{i}$ has not yet met and $0$ otherwise.
[ "data structures", "dp" ]
1,100
null
369
A
Valera and Plates
Valera is a lazy student. He has $m$ clean bowls and $k$ clean plates. Valera has made an eating plan for the next $n$ days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can ...
We will use greedy algorithm. Let's now $i$-th day, and current dish is a dish of first type. Then if we have the bowl, let's use it. Otherwise we will increase the answer. If the current dish is a dish of the second type, we first try to get the plate, and then the bowl. If there are no plates/bowls at all, then we wi...
[ "greedy", "implementation" ]
900
#include <iostream> using namespace std; int main() { int n, m, k, type; int ans = 0; cin >> n >> m >> k; for(int i = 0; i < n; i++) { cin >> type; if (type == 1) { if (m == 0) ans++; else m--; } else { if (k != 0) { k--; continue; } if (m != 0) { ...
369
B
Valera and Contest
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of $n$ students (including Valera). This contest was an individual competition, so each student in the team solved problems individually. After the contest was over, Valer...
In this task you are to determine such array $a_{1}, a_{2}, ..., a_{n}$, that following conditions are met: $r \ge a_1 \ge a_2 \ge \dots \ge a_n \ge l$; $s_k = \sum_{i = 1}^k a_i$; $s_{all} = \sum_{i = 1}^n a_i$; It's clear to understand, that value $s_{k}$ should be distributed evenly between the first $k$ elements. F...
[ "constructive algorithms", "implementation", "math" ]
1,400
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, k, l, r, s, sk; cin >> n >> k >> l >> r >> s >> sk; int tsk = s - sk; vector < int > ans(n); for(int i = 0; i < k; i++) { ans[i] = sk / k; if (sk % k != 0) ans[i]++, sk--; } if (k != n) { for(int ...
369
C
Valera and Elections
The city Valera lives in is going to hold elections to the city Parliament. The city has $n$ districts and $n - 1$ bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from $1$ to $n$, inclusive. Furthermore, fo...
Consider all the roads that we need to repair. Mark the ends of $u, v$ white. After that, we will consider a simple dynamic programming $d[v]$ ($v$ is the vertex) on the tree that for each vertex in the tree determines the number of white vertexes in the subtree. It is easy to calculate this by using a recursive functi...
[ "dfs and similar", "graphs", "trees" ]
1,600
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <list> #include <bitset> #include <utility> #include <functional> #include <string> #include <algorithm> #include <cstring> #include <cstdio> #includ...
369
D
Valera and Fools
One fine morning, $n$ fools lined up in a row. After that, they numbered each other with numbers from $1$ to $n$, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun. Every fool has exactly $k$ bullets and a pistol. In addition, the fool number $i$ has prob...
Let's $p[A]$ is the $p_{A}$ from the statement. It's clear to understand that you can discribe the state by using pair of integers ($A, B$), where $A$ is a number of the fool with smallest index, $B$ - the second fool from the left. It is clear to understand that fool with indexes $j \ge B$ will be living. After that...
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
2,200
#include <iostream> #include <queue> #include <cstring> #include <cstdio> using namespace std; #define pb push_back #define mp make_pair #define ft first #define sc second typedef pair<int,int> pt; const int N = 3000 + 50; int n, k, p[N], d[N][N], sufP[N], sufO[N]; int main() { #ifdef gridnevvvit freopen...
369
E
Valera and Queries
Valera loves segments. He has recently come up with one interesting problem. The $Ox$ axis of coordinates has $n$ segments, the $i$-th segment starts in position $l_{i}$ and ends in position $r_{i}$ (we will mark it as $[l_{i}, r_{i}]$). Your task is to process $m$ queries, each consists of number $cnt_{i}$ and a set ...
Let's calculate sets $xs[y]$ - all segments, whose right borders are exactly equal to $y$. Now we reduce our task to another. For each query we will count the number of segments that doesn't belong to any one point. Let's it will be the value $v$. Then the answer to the query is $n - v$. We add to our request the point...
[ "binary search", "data structures" ]
2,200
#define _CRT_SECURE_NO_DEPRECATE #define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include <iomanip> #include <utility> #include <complex> #include <vector> #include <bitset> #include <string> #include <stack> #include <queue> #include <set> #include <list> #include <map> #include <algorithm> #inclu...
370
A
Rook, Bishop and King
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an $8 × 8$ table. A field is represented by a pair of integers $(r, c)$ — the number of the row and the number of th...
There are two approaches to this task. The first is use BFS to find the shortest path three times. The second is to notice that: A rook can reach the destination in one or two moves. If the starting and the destination fields are in the same row or column, one move is enough. A bishop can reach only fields that are col...
[ "graphs", "math", "shortest paths" ]
1,100
null
370
B
Berland Bingo
Lately, a national version of a bingo game has become very popular in Berland. There are $n$ players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the $i$-th player contains $m_{i}$ numbers. During the game the host ...
It is good idea to think about cards as set of numbers. It is easy to see that card $a$ can't be finished before $b$ if $b$ is subset of $a$. So all you need is to find such cards (sets) which do not have other card (other set) as subset. Since there are at most 1000 cards, you may iterate through all pairs and check t...
[ "implementation" ]
1,300
null
370
C
Mittens
A Christmas party in city S. had $n$ children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to $m$, and the children are numbered from 1 to $n$. Then th...
Let's show that if the most frequent color appears not more than $\lfloor{\frac{n}{2}}\rfloor$ times, than all children can get mittens of distinct colors. One way to construct such solution is to sort all left mittens in the order of decreasing frequency of their colors: for the input 1 2 1 2 3 1 3 3 1 we get 1 1 1 1 ...
[ "constructive algorithms", "greedy", "sortings" ]
1,800
null
370
D
Broken Monitor
Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus. Innocentius is touch-typing a program that pain...
There are a lot of correct approaches to solve the problem. But there are much more incorrect :) One way to solve the problem is following. It is easy to see that in possible answer there are two opposite sides each containing w. In opposite case frame can be shrinked. So the size of frame is $dx$ or $dy$, where $dx = ...
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
2,100
null
370
E
Summer Reading
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer. As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the ...
For each book number that is in the sequence, find the leftmost and the rightmost position of this number. In other words, for each such book number we find a segment of positions that should consist of this number. If for some pair of numbers there segments intersect, it is impossible to construct the answer. The same...
[ "dp", "greedy" ]
2,500
null
371
A
K-Periodic Array
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2. Array $a$ is $k$-period if its length is divisible by $k$ and there is such array $b$ of length $k$, that $a$ is represented by array $b$ written exactly $\scriptstyle{\frac{n}{k}}$ times consecutively. In other words, array...
For array to be periodic, elements $1, 1 + k, 1 + 2 * k, \dots $ must be equal. Also, elements $2, 2 + k, 2 + 2 * k, \dots $ must be equal. And so on up to $k$. So each element of the array is a part of exactly one group. And there are $k$ groups total. Each such group is independent. Let's consider some group of ele...
[ "greedy", "implementation", "math" ]
1,000
null
371
B
Fox Dividing Cheese
Two little greedy bears have found two pieces of cheese in the forest of weight $a$ and $b$ grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it...
It is easy to see that the fox can do three type of operations: divide by 2, divide by 3 and divide by 5. Let's write both given numbers in form $a = x \cdot 2^{a2} \cdot 3^{a3} \cdot 5^{a5}$, $b = y \cdot 2^{b2} \cdot 3^{b3} \cdot 5^{b5}$, where $x$ and $y$ are not dibisible by 2, 3 and 5. If $x \neq y$ the fox can'...
[ "math", "number theory" ]
1,300
null
371
C
Hamburgers
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
Let's use binary search approach. For given number of hamburgers (say, $x$) let's find the minimal number of money needed to cook them. Say, for one hamburger Polycarpus needs $c_{b}$ bread pieces, $c_{s}$ sausages pieces, $c_{c}$ cheese pieces. So for $x$ hamburgers he needs: $c_{b} \cdot x$, $c_{s} \cdot x$ and $c_{c...
[ "binary search", "brute force" ]
1,600
null
371
D
Vessels
There is a system of $n$ vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to $n$, in the order from the highest to the lowest, the volume of the $i$-th vessel is $a_{i}$ liters. Initially, all the vessels are empty. In some vessels water is poured. All the ...
The naive solution for this problem will work like this. Let us store an amount of water in each vessel in some array $v$. If we need to know how much water is in some vessel, we just take the number from the array. If we need to pour $x$ units of water into vessel number $i$, we must follow the simple procedure: 1. If...
[ "data structures", "dsu", "implementation", "trees" ]
1,800
null
371
E
Subway Innovation
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter! The President of Berland was forced to leave only $k$ of the currently existing $n$ subway stations. The subway stations are located on a straight...
It is easy to see that you need to minimize the sum of pairwise distances between $k$ stations. The main idea to do it is to sort them and the required stations will form a continuous segment. It is easy to prove by contradiction. Huge constraints do not allow to use straight-forward method to find required segment. Le...
[ "greedy", "math", "two pointers" ]
2,000
null
372
A
Counting Kangaroos is Fun
There are $n$ kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who i...
Because of the number of holding-held relations is at most $\textstyle{\frac{N}{2}}$, We can assume that first half of kangaroos do not hold any kangaroos, and last half of kangaroos are not held by any kangaroos. So we can split kangaroos in two set, such that first set contains the kangaroos whose size is in smaller ...
[ "binary search", "greedy", "sortings", "two pointers" ]
1,600
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; int main() { int num; scanf("%d",&num); vector<int>vec; for(int i=0;i<num;i++) { int zan; scanf("%d",&zan); vec.push_back(zan); } sort(vec.begin(),vec.end()); int pt=num/2; int ans=num; for(int i=0;i<num/2;i++) { for(;;) { ...
372
B
Counting Rectangles is Fun
There is an $n × m$ rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the $i$-th row and the $j$-th column as $(i, j)$. Let's define a "rectangle" as four integers $a, b, c, d$ $(1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m)$. Rectangle denotes a set of cells of the grid ${(x, y) :...
We can precalculate all rectangles, in O(N^2M^2) with using consecutive sums for 2D. And then we use 4D consecutive sums, we can answer the queries. The time conplexity is O(N^2M^2+Q).
[ "brute force", "divide and conquer", "dp" ]
1,900
#include<stdio.h> int map[50][50]; int rui[51][51]; int dat[50][50][50][50]; int ans[51][51][51][51]; int main() { int mx,my,query; scanf("%d%d%d",&mx,&my,&query); for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { char zan; scanf(" %c",&zan); map[i][j]=zan-'0'; } } for(int i=0;i<mx;i++) { for(int ...
372
C
Watching Fireworks is Fun
A festival will be held in a town's main street. There are $n$ sections in the main street. The sections are numbered $1$ through $n$ from left to right. The distance between each adjacent sections is $1$. In the festival $m$ fireworks will be launched. The $i$-th ($1 ≤ i ≤ m$) launching is on time $t_{i}$ at section ...
I think most of the participants came up with simple DP algorithm : dp[i][j] := the maximum happiness value that you can gain when you're on poisition j at i th launching. Each value in table can be calculated by this formula : $dp[i][j] = max[k = - t * d..t * d](dp[i - 1][j + k] + b[i] - |a[i] - j|)$ where $t = t[i] -...
[ "data structures", "dp", "math" ]
2,100
#include <cstdio> #include <climits> #include <deque> #include <algorithm> using namespace std; typedef long long lint; int main() { int N, M, D; int a[1000], b[1000], t[1000]; lint dp[2][300001]; scanf("%d %d %d", &N, &M, &D); for (int i = 0; i < M; i++){ scanf("%d %d %d", a + ...
372
D
Choosing Subtree is Fun
There is a tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$. Let's define the length of an interval $[l, r]$ as the value $r - l + 1$. The score of a subtree of this tree is the maximum length of such an interval $[l, r]$ that, the vertices with numbers $l, l + 1, ..., r$ belong to the subtre...
We can use two pointers, which treat the interval of the consecutive numbers of node on tree. All we have to do is answer the query which requires the minimal number of size of subtree which contains all the vertices in the set, after the "add vertices to the set" and "delete verticesto the set" operations. We can calc...
[ "binary search", "data structures", "dfs and similar", "trees", "two pointers" ]
2,600
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; #define SIZE 131072 vector<int>pat[100000]; vector<int>ko[100000]; int par[19][100000]; int depth[100000]; bool flag[100000]; int heavy[100000]; int toseg[100000]; int pattop[100000]; void dfs(int node,int d) { if(flag[node]) { return; } ...
372
E
Drawing Circles is Fun
There are a set of points $S$ on the plane. This set doesn't contain the origin $O(0, 0)$, and for each two distinct points in the set $A$ and $B$, the triangle $OAB$ has strictly positive area. Consider a set of pairs of points $(P_{1}, P_{2}), (P_{3}, P_{4}), ..., (P_{2k - 1}, P_{2k})$. We'll call the set good if an...
All circles we must consider pass through O, so we can consider the operation inversion. At this operation, the point $(x, y)$ will be $\left({\frac{x}{x^{2}+y^{2}}},\,{\frac{y}{x^{2}+y^{2}}}\right)$. From now, we think the plane as the plane after inversed. "The circumcircles of triangles $OAB$ and $OCD$ have a single...
[ "combinatorics", "geometry" ]
3,000
#include<stdio.h> #include<vector> #include<algorithm> #include<stdlib.h> #include<math.h> using namespace std; typedef long long ll; typedef pair<ll,ll>pii; typedef pair<pii,pii>pi4; typedef pair<pi4,pii>pi6; ll mod=1000000007; ll gcd(ll a,ll b) { for(;;) { if(a<b) { swap(a,b); } a%=b; if(a==0) { r...
373
A
Collecting Beats is Fun
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has $16$ panels for playing arranged in $4 × 4$ table. When a panel lights up, he has to press that panel. Each panel has a \textbf{timing} to press (the preffered time when a player should press it), and Cucumber boy is able to press at most $k$ panels in ...
First, you need to count the occurence of each number (1 through 9). If none of them are greater than 2 * k, Cucumber boy is able to press the panels in perfect timing. Complexity is O(1).
[ "implementation" ]
900
#include <cstdio> using namespace std; int main() { int k; int cnt[10] = {0}; char mp[4][5]; scanf("%d", &k); for (int i = 0; i < 4; i++){ scanf("%s", mp[i]); for (int j = 0; j < 4; j++){ if (mp[i][j] == '.') continue; else cnt[mp[i][j] - '0']++; ...
373
B
Making Sequences is Fun
We'll define $S(n)$ for positive integer $n$ as follows: the number of the $n$'s digits in the decimal base. For example, $S(893) = 3$, $S(114514) = 6$. You want to make a consecutive integer sequence starting from number $m$ ($m, m + 1, ...$). But you need to pay $S(n)·k$ to add the number $n$ to the sequence. You c...
Naive simulation (subtracting S(i) * k from w while w >= 0) won't finish in 2 seconds. At first, these two facts will make it easier to solve the problem : 1. k doesn't matter for solving this problem, so you can simply divide w with k at the first point. 2. S(10^x) + S(10^x + 1) + ... + S(10^(x+1) - 1) = 9 * x * 10^x ...
[ "binary search", "implementation", "math" ]
1,600
#include<stdio.h> typedef long long ll; ll get(ll a) { ll ret=0; ll now=1; ll t=1; for(;;) { if(now*10>a) { ret+=(a-now+1)*t; break; } ret+=now*9*t; now*=10; t++; } return ret; } int main() { ll gen,st,tim; scanf...
374
A
Inna and Pink Pony
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an $n × m$ chessboard, a very tasty candy and two numbers $a$ and $b$. Dima put the chessboard in front of Inna and placed the candy in position $(i, j)$ on the board. The bo...
Lets find a solution for shifting a candy from the position $(x_{1}, y_{1})$ into position $(x_{2}, y_{2})$. On each step we shift (increase or decrease) $x_{1}$ by $a$ and $y_{1}$ by $b$. It is not difficult to understand that if $|x_{2} - x_{1}|$ is not divisible by $a$ and $|y_{2} - y_{1}|$ is divisible by $b$ answe...
[ "greedy", "implementation" ]
2,000
null
374
B
Inna and Nine
Inna loves digit $9$ very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number $a$, consisting of digits from $1$ to $9$. Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digi...
We can divide the task into subtasks because if two adjacent digits have sum none-9 the number transformation doesn't depends on other side relatively to the position between this two digits. It means we should divide our task into subtasks of kind: $x$ or $xyxyxyx...xyxy$ where $x + y = 9$. We should multiply all such...
[ "combinatorics", "greedy" ]
1,500
null
374
C
Inna and Dima
Inna and Dima bought a table of size $n × m$ in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A". Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: - initially, Inna chooses some cell of the table...
Our task is tranformed to the task of finding cycle or maximal way, but lets solve it without any graphs. Lets run dfs from each digit $D$, memorizing all already calculated tasks. If we come into the cell we have already been (in one of the previous $D$) than we should simply add the maximal way length to our current ...
[ "dfs and similar", "dp", "graphs", "implementation" ]
1,900
null
374
D
Inna and Sequence
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence $w$. Now they want to fill sequence $w$ with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses $m$ integers $a_{1}, a_{2}, ..., a_{m}$ $(1 ≤ a_{1} < a_{2} < ... < a_{m})$...
Lets note that not more than $n$ numbers, thus it will be not more than $n$ dropings. We will run this process using data structure Segment Tree (you can use another structures). Lets calculate the number of numbers in current segment. When the number is added we should simply go down from the root to the leaf and incr...
[ "binary search", "data structures", "dp", "trees" ]
2,000
null
374
E
Inna and Babies
Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing $n$ blue babies and $m$ red ones. Each baby is a segment that grows in time. At time moment $t$ the blue baby $(x, y)$ is a blue segment ...
We will make the binary search to find the answer. For each time let's generate our segments and rotate them to transform them into horizontal and verticle. We can use transformation $(x, y)$ to $(x + y, x - y)$. Don't forget to make the union of all segments which were at the one diagonal and have an intersection. You...
[ "binary search", "data structures", "dsu", "geometry", "implementation" ]
2,600
null
375
A
Divisible by Seven
You have number $a$, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7. Number $a$ doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resu...
O(n): Because permutation of 1, 6, 8, 9 can form integers that mod 7 equals 0, 1, 2, 3, 4, 5, 6. So you can construct answer like this: nonzero digits + a permutation of 1, 6, 8, 9 + zeros.
[ "math", "number theory" ]
1,600
null
375
B
Maximum Submatrix 2
You are given a matrix consisting of digits zero and one, its size is $n × m$. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix $a$ are numbered from 1 t...
O(n*m): #We can get right[i][j] by O(n*m) dp. Let right[i][j] = how many continuous 1s is on cell (j, i)'s right. Let answer = 0 For all column i Sort right[i] #You can use O(n) sorting algorithm For j in [1..n] If right[i][j]*(n-j+1) > answer then answer = right[i][j]*(n-j+1)
[ "data structures", "dp", "implementation", "sortings" ]
1,600
null
375
C
Circling Round Treasures
You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you. You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, e...
#T = number of treasures, B = number of booms O(n*m*2^(T+B)): #State(i, j, ts, bs) means: # 1. You are at cell (i, j) # 2. If the i-th bit of ts is 0 i-th treasure cross even edges of current path, otherwise odd edges. # 3. If the i-th bit of bs is 0 i-th boom cross even edges of current path, otherwise odd edges. Let ...
[ "bitmasks", "shortest paths" ]
2,600
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Div1C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); char[][] g = new char[n][]; for (int i = 0; i < n; i++) g[i] = in.next().toCharArray(); ...
375
D
Tree and Queries
You have a rooted tree consisting of $n$ vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to $n$. Then we represent the color of vertex $v$ as $c_{v}$. The tree root is a vertex with number 1. In this problem you need to answer to $m$ queries. Each...
O(nlogn) or O(nlog^2n): Use binary search tree and merge them by rank. Use binary search tree that supports O(n) merging to get O(nlogn) solution. O(n*sqrt(n)): Dfs the tree to transform the problem to: Given a[i], query [l,r] k. To solve this problem: Build sqrt(n) bucket, put query [l,r] into (l/sqrt(n)+1)-th bucket ...
[ "data structures", "dfs and similar", "trees" ]
2,400
null
375
E
Red and Black Tree
You have a weighted tree, consisting of $n$ vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most $x$. The distance between two nodes is the shortest path between them. You have a red and black tr...
This problem can be solved by integer programming: min sum{c[i]*x[i]} subject to sum{A[i][j]*x[j]} >= 1 for all i sum{x[i]} = R x[i] = 0 or 1 for all i where c[i] = 1 if node i is black, 0 otherwise A[i][j] = 1 if distance between i and j is no greater than X, 0 otherwise R = number of red nodes. As it is known, intege...
[ "dp", "implementation", "math" ]
3,000
#include <vector> #include <algorithm> #include <cstdio> using namespace std; #define lp for(;;) #define repf(i,a,b) #define ft(i,a,b) for (int i=(a);i<=(b);++i) #define rep(i,n) for (int i=0;i<(n);++i) #define rtn return #define pb push_back #define mp make_pair #define sz(x) (int((x).size())) typedef double db; type...
376
A
Lever
You have a description of a lever as string $s$. We'll represent the string length as record $|s|$, then the lever looks as a horizontal bar with weights of length $|s| - 1$ with exactly one pivot. We will assume that the bar is a segment on the $Ox$ axis between points $0$ and $|s| - 1$. The decoding of the lever des...
O(n): Let mid = position of ^ Let value(x) = x if x is a digit , 0 otherwise. Let sum = value(i-th char)*(i-mid) If sum = 0 then answer = balance Else if sum<0 then answer = left Else answer = right
[ "implementation", "math" ]
900
null
376
B
I.O.U.
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
O(n^4): Let f[i][j] = how many money i owes j #It can be proved we only need to loop n times. Loop n times do: For i,j,k in [1..n] If f[i][j]>0 and f[j][k]>0 then Let delta = min (f[i][j], f[j][k]) Decrease f[i][j] and f[j][k] by delta Increase f[i][k] by deltaAnswer will be sum{f[i][j]} O(m+n): Let owe[i] = 0 for all...
[ "implementation" ]
1,300
null
377
A
Maze
Pavel loves grid mazes. A grid maze is an $n × m$ rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any o...
Start BFS or DFS from any free cell. As the maze is connected, this search will visit all $s$ free cells. But we can stop the search when it visits $s - k$ free cells. It's obvious that these $s - k$ cells are connected to each other. Remaining $k$ cells can be transformed into the walls. Solutions which every move tra...
[ "dfs and similar" ]
1,600
null
377
B
Preparing for the Contest
Soon there will be held the world's largest programming contest, but the testing system still has $m$ bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has $n$ students able to perform such work. The students realize that they are ...
It's obvious that the time needed to fix all bugs is the monotonic function: if we can do it for some time, we can do it for greater time. So we can use binary search in these problem. We should learn how to check if some time $t$ is enough. At first sort all bugs by their complexity and all students by their skills. L...
[ "binary search", "data structures", "greedy", "sortings" ]
1,900
null
377
C
Captains Mode
Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analys...
There are some observations that do the problem very simple. The first one is that we always should pick the strongest hero. But we cannot say something similar about the bans - in different situations different bans are the best. But the most important observation is that we should consider only $m$ strongest heroes. ...
[ "bitmasks", "dp", "games" ]
2,200
null
377
D
Developing Game
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired $n$ workers of staff. Now he wants to pick $n$ workers from the staff who will be directly responsible for developing a game. Each worker has a certain skill level $v_{i}$. Besid...
Let's note that every answer is characterized with two numbers $L$ and $R$ so that $max{l_{i}} \le L$, $R \le min{r_{i}}$, and $L \le v_{i} \le R$. If we know $L$ and $R$, we can check every person and choose those who satisfies the conditions above. Let's imagine a plane with the coordinate axes: one of the ax...
[ "data structures" ]
2,400
null
377
E
Cookie Clicker
Kostya is playing the computer game Cookie Clicker. The goal of this game is to gather cookies. You can get cookies using different buildings: you can just click a special field on the screen and get the cookies for the clicks, you can buy a cookie factory, an alchemy lab, a time machine and it all will bring lots and ...
First of all, throw away the buildings which cannot be used in any optimal answer: for each $v_{i}$ remain only one building that has speed equal to $v_{i}$ and minimal $c_{i}$. Also throw away all buildings whose speed is less than the speed of the fastest building which has $c_{i} = 0$. It's fairly obvious that at an...
[ "dp", "geometry" ]
2,800
null
378
A
Playing with Dice
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number $a$, the second player wrote number $b$. How many w...
Make three counters: for wins of both players and for a draw. Iterate over all six ways how they can throw a dice. For each way determine who wins or there is a draw and increment the corresponding counter.
[ "brute force" ]
800
null
378
B
Semifinals
Two semifinals have just been in the running tournament. Each semifinal had $n$ participants. There are $n$ participants advancing to the finals, they are chosen as follows: from each semifinal, we choose $k$ people ($0 ≤ 2k ≤ n$) who showed the best result in their semifinals and all other places in the finals go to t...
You can think a bit and understand that you should consider only corner cases: $k = 0$ and $k={\frac{n}{2}}$. All other cases will be something between them. If $k = 0$, we should choose $n$ biggest elements from two sorted lists, one of the ways is to use two pointers method. And if $k={\frac{n}{2}}$, we just mark fir...
[ "implementation", "sortings" ]
1,300
null
379
A
New Year Candles
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has $a$ candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make $b$ went out candles into a new candle. As a result, this new candle can be used ...
Let $cur_{a}$ amount of new candles, $cur_{b}$ - amount of burnt out. Initially $cur_{a} = a$, $cur_{b} = 0$, after burning all $cur_{a}$ new candles, amount of hours incremented by $cur_{a}$ and $cur_{b} + = cur_{a}$, lets make all burnt out candles into new $cur_{a} = cur_{b} / b$ $c u r_{b}=c u r_{b}\;\;\mathrm{mod}...
[ "implementation" ]
1,000
null
379
C
New Year Ratings Change
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors. There are $n$ users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user $i$ wants to get at least $a_{...
We can to sort ratings in nondecrease order, then iterate by them we can keep minimal rating not used before. If $a_{i} > cur$, $i$'s user recieve $a_{i}$ of rating and $cur = a_{i} + 1$, else $a_{i} \le cur$ then $i$'s user recieve $cur$ of rating and $cur$ increased by one.
[ "greedy", "sortings" ]
1,400
null
379
D
New Year Letter
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). ...
We can't fairly calculate $s_{k}$ because of length of this string which can be very large. But note that whole string not need, we just need number of $AC$ substrings, first and last letter. That help us to easy calculate number $AC$ substrings for any $s_{k}$ for some $s_{1}$, $s_{2}$. Let's iterate through $s_{1}$, ...
[ "bitmasks", "brute force", "dp" ]
2,000
null
379
E
New Year Tree Decorations
Due to atheistic Soviet past, Christmas wasn't officially celebrated in Russia for most of the twentieth century. As a result, the Russian traditions for Christmas and New Year mixed into one event celebrated on the New Year but including the tree, a Santa-like 'Grandfather Frost', presents and huge family reunions and...
Let's keep union of first $i$ pieces, $S(i)$ denote the area of union for the first $i$ pieces. Then to know visible part of $i$'s piece we need to calculate $S(i) - S(i - 1)$, ( Unable to parse markup [type=CF_TEX]
[ "geometry", "schedules", "sortings" ]
2,500
null
379
G
New Year Cactus
Jack and Jill are tired of the New Year tree, now they've got a New Year cactus at home! A cactus is a connected undirected graph where any two simple cycles have at most one common vertex. In other words, this graph doesn't have any edges that lie on more than one simple cycle. On the 31st of December they are going ...
This problem can be solved for tree by using of dynamic programming $d[v][c][a]$, where $v$ - vertex, $c$ - type of vertex(whose toys are hanged or nothing are hanged there), $a$ - number of toys hanged by Jack for this subtree, $d[v][c][a]$ denote of maximum number of toys which can be hanged by Jill. Value $d[v][c][a...
[ "dp" ]
3,100
null
380
A
Sereja and Prefixes
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in $m$ stages. Each time he either adds a new number to the end of the sequence or takes $l$ first elements of the current...
Generate the first number 100000. Will in turn handle the requests, if the request gets to the point of adding one number, just print it. Otherwise see what element will meet our and just print it from precalculated array.
[ "binary search", "brute force" ]
1,600
null
380
B
Sereja and Tree
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees. His new tree consists of $n$ levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level $1$, its index is $(1, 1)$. Here is a pseudo code o...
Lets generate a tree as described in the statment. For each request to add items we just add a segment for a certain level. At the request of the number of items we just go through all the lower levels, considering the leftmost and the rightmost vertex in the subtree. To each level will take all intervals that it owns ...
[ "graphs", "implementation" ]
2,400
null