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 ⌀ |
|---|---|---|---|---|---|---|---|
283 | C | Coin Troubles | In the Isle of Guernsey there are $n$ different types of coins. For each $i$ $(1 ≤ i ≤ n)$, coin of type $i$ is worth $a_{i}$ cents. It is possible that $a_{i} = a_{j}$ for some $i$ and $j$ $(i ≠ j)$.
Bessie has some set of these coins totaling $t$ cents. She tells Jessie $q$ pairs of integers. For each $i$ $(1 ≤ i ≤ ... | Imagine the problem as a graph where coins are the nodes and Bessie's statements are directed edges between coins. Because of the problem conditions, the graph must be a set of cycles and directed paths. If there are any cycles in the graph, the answer is clearly 0. Then, suppose we have a path $p_{1}, p_{2}, \dots p_... | [
"dp"
] | 2,100 | null |
283 | D | Cows and Cool Sequences | Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!
A pair $(x, y)$ of positive integers is "cool" if $x$ can be expressed as the sum of $y$ consecutive integers (not necessarily positive). A sequence $... | Let $v_{2}(n)$ denote the exponent of the largest power of $2$ that divides $n.$ For example $v_{2}(5) = 0, v_{2}(96) = 5.$ Let $f(n)$ denote the largest odd factor of $n.$ We can show that for fixed $a_{i}, a_{j}(i < j),$ we can construct a cool sequence $a_{i} = b_{i}, b_{i + 1}, ... b_{j - 1}, b_{j} = a_{j}$ if and ... | [
"dp",
"math",
"number theory"
] | 2,400 | null |
283 | E | Cow Tennis Tournament | Farmer John is hosting a tennis tournament with his $n$ cows. Each cow has a skill level $s_{i}$, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own.
However, Farmer John thinks the tournament wil... | This will go over the basic outline for solution. We can show that the answer is $\textstyle{\binom{n}{3}}-\sum_{i}{\binom{n_{i}}{2}}$ where $w_{i}$ is the number of wins cow $i$ appears to have. Proof here Now sort the skill levels of the cows (the order of the $s_{i}$ doesn't actually matter). $s_{1}$ is lowest skill... | [
"combinatorics",
"data structures",
"math"
] | 2,800 | null |
284 | A | Cows and Primitive Roots | The cows have just learned what a primitive root is! Given a prime $p$, a primitive root $\mathrm{mod}\,p$ is an integer $x$ $(1 ≤ x < p)$ such that none of integers $x - 1, x^{2} - 1, ..., x^{p - 2} - 1$ are divisible by $p$, but $x^{p - 1} - 1$ is.
Unfortunately, computing primitive roots can be time consuming, so t... | We didn't expect this problem to be so hard :(. This problem can be solved by brute forcing. For any $x,$ you can compute $x^{1},x^{2},\ldots,x^{p-1}\mod p$ in $O(p)$ time (iteratively multiply cur = (cur * i) % p, not use pow in math library!), so overall brute force will be $O(p^{2})$ time. Note: there is actually $O... | [
"implementation",
"math",
"number theory"
] | 1,400 | null |
284 | B | Cows and Poker Game | There are $n$ cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any be... | We first note that players who have folded do not affect our desired answer. Then, we can do casework on the number of players who are currently "IN". If no cows are "IN", then all the players who are "ALLIN" can show their hands. If exactly one cow is "IN", she is the only one who can show, so the answer is 1. If two ... | [
"brute force",
"implementation"
] | 1,000 | null |
285 | A | Slightly Decreasing Permutations | {\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}
The ... | As the answer you can print such permutation: $n, n - 1, ..., n - k + 1, 1, 2, ..., n - k$. For example, if $n = 5$, $k = 2$, then the answer is: $5, 4, 1, 2, 3$. If $k = 0$, you should print $1, 2, ..., n$. Such solution can be written in two loops. | [
"greedy",
"implementation"
] | 1,100 | null |
285 | B | Find Marble | Petya and Vasya are playing a game. Petya's got $n$ non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from $1$ to $n$ from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position $s$. Then he performs s... | It is known that a permutation can be considered as set of cycles. The integer $i$ moves to $p[i]$ for all $i$ $(1 \le i \le n)$. You can start moving from integer $s$ along the cycle. If you find integer $t$, then print the length of the path. If you return to $s$, then print $- 1$. | [
"implementation"
] | 1,200 | null |
285 | C | Building Permutation | {\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}
You ... | The solution of the problem is rather simple. Sort all integers $a$ and then make from integer $a[1]$ integer $1$, from integer $a[2]$ integer $2$ and so on. So, integer $a[i]$ adds to the answer the value $|a[i] - i|$. The answer should be count in 64-bit type. You can simply guess why such solution is correct. | [
"greedy",
"implementation",
"sortings"
] | 1,200 | null |
285 | D | Permutation Sum | {\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}
Pety... | For a start, describe bruteforce solution. Firstly, we will always assume, that $a$ is identity permutation, that is $a[i] = i$. In this case, the answer should be multiplied by $n!$. Or in other way your bruteforce will not be counted. Secondly, using our bruteforce we can see, that for even $n$ the answer is $0$. Wha... | [
"bitmasks",
"combinatorics",
"dp",
"implementation",
"meet-in-the-middle"
] | 1,900 | null |
285 | E | Positions in Permutations | {\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}
We'l... | A common approach for this kind of problem is DP. What we do here is to choose numbers for the good positions first, then fill the others later on. Let f(i, j, k) is the number of ways to choose j good positions in the first i-th position and k is a 2-bit number that represents whether number i and number i + 1 is alre... | [
"combinatorics",
"dp",
"math"
] | 2,600 | #include <iostream>
#include <algorithm>
using namespace std;
const int BASE = int(1e9) + 7;
long long f[1010][1010][4], F[1010], c[1010][1010];
void addMod(long long &x, long long y)
{
x += y;
if (x >= BASE) x -= BASE;
}
int main()
{
int n, k;
cin >> n >> k;
for (int i = 0; i <= n; i++)
for (int j = 0; j ... |
288 | A | Polo the Penguin and Strings | Little penguin Polo adores strings. But most of all he adores strings of length $n$.
One day he wanted to find a string that meets the following conditions:
- The string consists of $n$ lowercase English letters (that is, the string's length equals $n$), exactly $k$ of these letters are distinct.
- No two neighbourin... | To solve this problem we need to find out some contruction of resulting string. But first of all, we need find out when there is no result. Obviously, if $k > n$, there is not result - you cannot build string of length $n$ with more than $n$ characters. Another one case is when $k = 1$ and $n > 1$ - there is no answer ... | [
"greedy"
] | 1,300 | null |
288 | B | Polo the Penguin and Houses | Little penguin Polo loves his home village. The village has $n$ houses, indexed by integers from 1 to $n$. Each house has a plaque containing an integer, the $i$-th house has a plaque containing integer $p_{i}$ ($1 ≤ p_{i} ≤ n$).
Little penguin Polo loves walking around this village. The walk looks like that. First he... | Since $k \le 8$ you can solve this problem using brute force. This means that you can recursively construct all possible $k^{k}$ possibilities of first $k$ assignments. (For $k = 8$ this is equal to $16 777 216$.) For each of that assignments you need to check whether it is correct or not (by problem statement). Ths ... | [
"combinatorics"
] | 1,500 | null |
288 | C | Polo the Penguin and XOR operation | Little penguin Polo likes permutations. But most of all he likes permutations of integers from $0$ to $n$, inclusive.
For permutation $p = p_{0}, p_{1}, ..., p_{n}$, Polo has defined its beauty — number $(0\oplus p_{0})+(1\oplus p_{1})+\cdot\cdot\cdot+(n\oplus p_{n})$.
Expression $x\oplus y$ means applying the operat... | Since we need to maximize the result, we need to find such permutation, for which the least number of bit disappear. (We consider bit disappeared if it was 1 both in $i$ and $p_{i}$, so in $i\oplus p_{i}$ it is 0). It turns out that for each $n$ there is such permutation that no bit disappear. How to build it? We will ... | [
"implementation",
"math"
] | 1,700 | null |
288 | D | Polo the Penguin and Trees | Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing $n$ nodes and $n - 1$ edges. We will consider the tree nodes numbered by integers from 1 to $n$.
Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of... | As always in such problems, root our tree at some vertex, for example vertex with number 1. We need to find out, what will happen when we have already chosen one path. Obviously, after deleting all vertices and their edges from that path, tree will disintegrate in some set of trees. Denote their sizes by $c_{1}, c_{2},... | [
"combinatorics",
"dfs and similar",
"trees"
] | 2,400 | null |
288 | E | Polo the Penguin and Lucky Numbers | \underline{Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.}
Polo the Penguin have two positive integers $l$ and $r$ $(l < r)$, both of them are lucky numbers. Moreover, the... | In this problem there are a lot of different formulas, most of them are for optimizing solution and making it lenear. Editorial shows just a general idea because it's pretty hard to explain all of them and good for you to derive it by yourself. If you have any questions - write them all in comments. Denote by $a_{1}, a... | [
"dp",
"implementation",
"math"
] | 2,800 | null |
289 | A | Polo the Penguin and Segments | Little penguin Polo adores integer segments, that is, pairs of integers $[l; r]$ $(l ≤ r)$.
He has a set that consists of $n$ integer segments: $[l_{1}; r_{1}], [l_{2}; r_{2}], ..., [l_{n}; r_{n}]$. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to t... | First of all, we need to count, how many integers are inside given segments at the beginning. Since they don't intersect and even touch, no integer point can belong to more than one segment at the same time. This mans that starting value of segments is $p\ {\stackrel{\mathrm{def}}{=}}\left(r_{1}-l_{1}+1\right)+\left(r_... | [
"brute force",
"implementation"
] | 1,100 | null |
289 | B | Polo the Penguin and Matrix | Little penguin Polo has an $n × m$ matrix, consisting of integers. Let's index the matrix rows from 1 to $n$ from top to bottom and let's index the columns from 1 to $m$ from left to right. Let's represent the matrix element on the intersection of row $i$ and column $j$ as $a_{ij}$.
In one move the penguin can add or ... | First of all, we need to know when the answer is -1. For that you should notice that after any operation on number $z$, value $z\ {\mathrm{mod}}\ d$ doesn't change. Indeed, $z_{\textrm{m o d}}d=(z+d)\;\;\mathrm{mod}\;=(z-d)\;\;\mathrm{mod}\;d$. This means that there is not answer if there are two different points for w... | [
"brute force",
"dp",
"implementation",
"sortings",
"ternary search"
] | 1,400 | null |
293 | A | Weird Game | Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of $2·n$ binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fi... | The first observation - we don't care about the actual strings, all information we need - number of pairs {0,0}, {0,1}, {1,0}, {1,1}. Count that and then just follow the greedy algorithm, for the first player: try to get a index with {1,1} if there are some, than {1,0}, than {0,1} and than {0,0}. For the second player ... | [
"games",
"greedy"
] | 1,500 | null |
293 | B | Distinct Paths | You have a rectangular $n × m$-cell board. Some cells are already painted some of $k$ colors. You need to paint each uncolored cell one of the $k$ colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and... | Every path from the topleft cell to the bottomright cell contain exactly $n + m - 1$ cells. And all of the should be of different color. So $n + m - 1 \le k$. Due to the small constraints for k we may assume that bruteforce might work. The only optimization to get the correct solution is some canonization of the colo... | [
"brute force",
"combinatorics"
] | 2,700 | null |
293 | C | Cube Problem | Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours!
Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an $a × a × a$ cube, Andrey made a $b × b × b$ cube and Roman made a $c × c × c$ cube. After that the ... | After reading the problem statement one can understand that all we need is to calculate the number of positive integer solutions of equation: $(a + b + c)^{3} - a^{3} - b^{3} - c^{3} = n$. The key observation is: $3(a + b)(a + c)(b + c) = (a + b + c)^{3} - a^{3} - b^{3} - c^{3}$, after that simply calculate all divisor... | [
"brute force",
"math",
"number theory"
] | 2,400 | null |
293 | D | Ksusha and Square | Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles.
Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the p... | We can see that we asked to calculate $\sum2((x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2})$ for all integer points inside the polygon or on its border. We can see that we can process Xs and Ys independently. For each $x$ determine $y_{left}$, $y_{right}$, such that all points $(x, y)$ where $y_{left} \le y \le y_{right}$ ar... | [
"geometry",
"math",
"probabilities",
"two pointers"
] | 2,700 | null |
293 | E | Close Vertices | You've got a weighted tree, consisting of $n$ vertices. Each edge has a non-negative weight. The length of the path between any two vertices of the tree is the number of edges in the path. The weight of the path is the total weight of all edges it contains.
Two vertices are close if there exists a path of length at mo... | Let's assume that we have a data structure which can perform such operations as: - add point (x,y) to the structure; shift all points in the structure by vector (dx,dy); answer how many point (x,y) are in the structure where $x \le x_{bound}$, $y \le y_{bound}$; get all elements which are now in the structure; For ... | [
"data structures",
"divide and conquer",
"trees"
] | 2,700 | null |
294 | A | Shaass and Oskols | Shaass has decided to hunt some birds. There are $n$ horizontal electricity wires aligned parallel to each other. Wires are numbered $1$ to $n$ from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are $a_{... | In this problem you just have to now how many birds are there on each wire after each shot. A good trick for the first and the last wire would be to define wires $0$ and $n + 1$. In this way the birds that fly away sit on these wires and you don't need to worry about accessing some element outside the range of your arr... | [
"implementation",
"math"
] | 800 | null |
294 | B | Shaass and Bookshelf | Shaass has $n$ books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the $i$-th book is $t_{i}$ and its pages' width is equal to $w_{i}$. The thickness of each book is either $1$ or $2$. All books have the same page heights.
Shaass puts ... | As said in the statement, the thickness of each book is either 1 or 2. Think about when we want to arrange $v_{1}$ books of thickness 1 and $v_{2}$ books of thickness $2$ vertically and arrange all other $n - v_{1} - v_{2}$ books horizontally above them to achieve a configuration with total thickness of vertical books ... | [
"dp",
"greedy"
] | 1,700 | null |
294 | C | Shaass and Lights | There are $n$ lights aligned in a row. These lights are numbered $1$ to $n$ from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is... | I just want to solve the third sample of this problem for you and you can figure out the rest by yourself. :) The third sample is ...#...#... where # is a switched on lamp and . is a switched off lamp. As you can see we have three different types of lights. The first three lights (Type A), the 5th to 8th lights (Type B... | [
"combinatorics",
"number theory"
] | 1,900 | null |
296 | A | Yaroslav and Permutations | Yaroslav has an array that consists of $n$ integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav. | Note that after applying the operations of the exchange, we can get any permutation of numbers. Not difficult to understand that the answer is "YES", if you can place a single number that it would not stand in the neighboring cells. Thus, if a some number is meeted C times, it must fulfill the condition C <= (n+1) / 2. | [
"greedy",
"math"
] | 1,100 | null |
297 | A | Parity Game | You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") $a$ and $b$. Then you try to turn $a$ into $b$ using two types of operations:
- Write $p... | Obv 1: If $a$ has odd parity, we can apply operation 1 to increase its number of 1s by $1$. Obv 2: If $a$ has even parity, its number of 1s cannot increase anymore. Claim: If the number of 1s in $a$ is not fewer than those in $b$, we can always turn $a$ to $b$ The idea is to make a copy of $b$ at the right of $a$. Lets... | [
"constructive algorithms"
] | 1,700 | null |
297 | B | Fish Weight | It is known that there are $k$ fish species in the polar ocean, numbered from $1$ to $k$. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the $i$-th type of fish be $w_{i}$, then $0 < w_{1} ≤ w_{2} ≤ ... ≤ w_{k}$ holds.
Polar bears Alice and Bob each have caught s... | First we sort $a$ and $b$ in non-increasing order. We claim that the answer is YES if and only if exists $a$ is lexicographically larger than $b$. $(\leftarrow)$ If $a$ is not lexicographcally larger than $b$, that means for every $i$, $a_{i} \le b_{i}$. That implies for every fish Alice has, there is a corresponding... | [
"constructive algorithms",
"greedy"
] | 1,600 | null |
297 | C | Splitting the Uniqueness | Polar bears like unique arrays — that is, arrays without repeated elements.
You have got a unique array $s$ with length $n$ containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays $a$ and $b$ that are also of len... | An equivalent definition for almost unique, is an array with at least $ \lfloor 2n / 3 \rfloor $ different elements. The idea is to split $s$ into three parts: In the first part, we give uniqueness to $a$. In the second part, we give uniqueness to $b$. In the third part, we give uniqueness to both. Lets assume $s$ is ... | [
"constructive algorithms"
] | 2,400 | null |
297 | D | Color the Carpet | Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height $h$ and width $w$. Then the grid is divided into $h × w$ squares. Alice is going to assign one of $k$ different colors to each square. The colors are numbered from 1 ... | For $k = 1$ there is only one coloring so we just need to check the number of $=$ constraints. When $k \ge 2$, it turns out that using only $2$ colors is always sufficient to satisfy at least $3 / 4$ of the constraints. Lets assume $w \ge h$ (rotate if not). We will call the constraints that involves cells in diffe... | [
"constructive algorithms"
] | 2,500 | null |
297 | E | Mystic Carvings | The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are $n$ lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered $1, 2, ..., 2n$ counter-clockwise along the circumferenc... | For any three lines, they can intersect in one of the following 5 ways: The problem is asking for the number of Type 2 or Type 5. Some of these configs are easy to count (e.g. Type 1), some are not. To count the number of Type 1, we can exhaust the middle line with index $i$, and count the number of lines on the right ... | [
"data structures"
] | 3,000 | null |
298 | A | Snow Footprints | There is a straight snowy road, divided into $n$ blocks. The blocks are numbered from 1 to $n$ from left to right. If one moves from the $i$-th block to the $(i + 1)$-th block, he will leave a right footprint on the $i$-th block. Similarly, if one moves from the $i$-th block to the $(i - 1)$-th block, he will leave a l... | The starting position can be anywhere with a footprint. The footprints can be categorized into 3 types. only $L$ s only $R$ s $R$ s followed by $L$ s In case 1, we end in the left of all footprints. In case 2, we end in the right of all footprints. In case 3, we either end in the rightmost $R$ or the leftmost $L$ | [
"greedy",
"implementation"
] | 1,300 | null |
298 | B | Sail | The polar bears are going fishing. They plan to sail from $(s_{x}, s_{y})$ to $(e_{x}, e_{y})$. However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at $(x, y)$.
- If the wind blows to the east, the boat will move t... | We can simply move by greedy method - only moves when it takes the boat closer to the destination. | [
"brute force",
"greedy",
"implementation"
] | 1,200 | null |
299 | A | Ksusha and Array | Ksusha is a beginner coder. Today she starts studying arrays. She has array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers.
Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number! | If $a_{i}$ divide $a_{j}$ than $a_{i} \le a_{j}$. So the number which will divide every other number should be less than or equal to every other number, so the only possible candidate - it's the minimum in the array. So just check whether all elements are divisible by the minimal one | [
"brute force",
"number theory",
"sortings"
] | 1,000 | null |
299 | B | Ksusha the Squirrel | Ksusha the Squirrel is standing at the beginning of a straight road, divided into $n$ sectors. The sectors are numbered 1 to $n$, from left to right. Initially, Ksusha stands in sector 1.
Ksusha wants to walk to the end of the road, that is, get to sector $n$. Unfortunately, there are some rocks on the road. We know t... | Easy to see, that Ksusha is unable to complete her journey if there is a sequence of consecutive # with length more than k. | [
"brute force",
"implementation"
] | 900 | null |
300 | A | Array | Vitaly has an array of $n$ distinct integers. Vitaly wants to divide this array into three \textbf{non-empty} sets so as the following conditions hold:
- The product of all numbers in the first set is less than zero $( < 0)$.
- The product of all numbers in the second set is greater than zero $( > 0)$.
- The product o... | In this problem you just need to implement following algorithm. Split input data into 3 vectors: first will contain negative numbers, second positive numbers, third zeroes. If size of first vector is even move one number from it to the third vector. If second vector is empty, then move two numbers from first vector to ... | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,100 | #include <cstdio>
#include <vector>
using namespace std;
vector <int> first, second, third;
int main () {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
int a;
scanf("%d", &a);
if (a == 0)
third.push_back(a);
if (a > 0)
second.push_back(a);
... |
300 | B | Coach | A programming coach has $n$ students to teach. We know that $n$ is divisible by $3$. Let's assume that all students are numbered from $1$ to $n$, inclusive.
Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be... | Input data represents a graph. If there is a connected component with at least $4$ vertexes, then answer is $- 1$. Every connected component with $3$ vertexes is a complete team. Other teams are made from $1$ or $2$-vertex components. If amount of $2$-vertex components is greater than $1$-vertex answer is $- 1$. Otherw... | [
"brute force",
"dfs and similar",
"graphs"
] | 1,500 | #define _CRT_SECURE_NO_DEPRECATE
#define _SECURE_SCL 0
#pragma comment(linker, "/STACK:300000000")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <complex>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <fs... |
300 | C | Beautiful Numbers | Vitaly is a very weird man. He's got two favorite digits $a$ and $b$. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits $a$ and $b$. Vitaly calls a good number excellent, if the sum of its digits is a good number.
For example, let's say that Vitaly's favourite dig... | Let's $MOD = 1000000007$. Let's precalc factorial values modulo $MOD$. $fact[i] = i!%MOD$, $\forall i\leq100000$. Let $i$ be an amount of digits equal to $a$ in current excellent number. In this case we can find sum of digits in this number: $sum = ai + b(n - i)$. If $sum$ is good, then add $C[n][i]$ to answer. In this... | [
"brute force",
"combinatorics"
] | 1,800 | #define _CRT_SECURE_NO_DEPRECATE
#define _SECURE_SCL 0
#pragma comment(linker, "/STACK:200000000")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <complex>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <fs... |
300 | D | Painting Square | Vasily the bear has got a large square white table of $n$ rows and $n$ columns. The table has got a black border around this table.
\begin{center}
{\scriptsize The example of the initial table at $n$ = 5.}
\end{center}
Vasily the bear wants to paint his square table in exactly $k$ moves. Each move is sequence of acti... | This picture is helpful for understanding. Let's consider problem $D$ in graph terms: We have matrix $n \times n$, which represents a graph: It is tree. Every vertex, except leaves, has 4 children. There are $4^{k}$ distinct vertexes, with distance $k$ from root. We need to color $k$ vertexes of this graph. By that w... | [
"dp",
"fft"
] | 2,300 | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <deque>
#include <functional>
#include <fstream>
#include <iostream>
#include <map>
#include <memory.h>
#include <numeric>
#include <queue>
#in... |
300 | E | Empire Strikes Back | In a far away galaxy there is war again. The treacherous Republic made $k$ precision strikes of power $a_{i}$ on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces.
To successfully complete the conflict, the confrontation balance after th... | Let's $v a l=\sum_{i=1}^{k}a_{i}$. $val$ is upper bound for answer. $val!$ is divisible by $d e n=\prod_{i=1}^{k}a_{i}!$, you can easily prove it using facts about prime powers in factorial and following inequality $\left|{\frac{\eta}{i}}\right|+\left|{\frac{\eta}{i}}\right|\leq\left|{\frac{(\mu+\mu)}{i}}\right|$. By t... | [
"binary search",
"math",
"number theory"
] | 2,300 | #include <cstdio>
const int N = (int)1e7 + 100;
int lp[N], simples[N], simsz;
long long cnt[N];
bool ok(long long mid) {
bool can = true;
for(int i = 0; i < simsz && can; i++) {
long long tmp = mid, f = 0;
while(tmp) {
tmp /= simples[i];
f += tmp;
}
if (f < cnt[i])
can = false;
}
return can;
} ... |
301 | A | Yaroslav and Sequence | Yaroslav has an array, consisting of $(2·n - 1)$ integers. In a single operation Yaroslav can change the sign of exactly $n$ elements in the array. In other words, in one operation Yaroslav can select exactly $n$ array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elem... | Using dfs we will find number of numbers that we can set as positive. Note that we can either set all of the numbers as positive or leave one number(any) as negative. If we can obtain all numbers as positive, we just return sum of modules of the numbers, but if we cannot we will count the same sum and will subtract min... | [
"constructive algorithms"
] | 1,800 | null |
301 | B | Yaroslav and Time | Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has $n$ clock stations, station number $i$ is at point $(x_{i}, y_{i})$ of the plane. As the player visits station number $i$, he i... | We will use binary search to find the answer. Further we will use Ford-Bellman algorithm. On each step we will have an array of maximum values on timer, when we stand in some point. On in transfer we will check: will our player stay alive after travelling beetwen points. If we can make transfer, we will update value of... | [
"binary search",
"graphs",
"shortest paths"
] | 2,100 | null |
301 | C | Yaroslav and Algorithm | Yaroslav likes algorithms. We'll describe one of his favorite algorithms.
- The algorithm receives a string as the input. We denote this input string as $a$.
- The algorithm consists of some number of command. Сommand number $i$ looks either as $s_{i}$ >> $w_{i}$, or as $s_{i}$ <> $w_{i}$, where $s_{i}$ and $w_{i}$ ar... | We will use ? as iterator. In the begin we will set ? before the number. Then we will move it to the end of the string. Then we will change ? to ?? and we will move it to the begin, while we have 9 before ??. If we have another digit, we just increase it, and finish the algorithm. If we have ?? at the begin, we change ... | [
"constructive algorithms"
] | 2,500 | null |
301 | D | Yaroslav and Divisors | Yaroslav has an array $p = p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$, consisting of $n$ distinct integers. Also, he has $m$ queries:
- Query number $i$ is represented as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$.
- The answer to the query $l_{i}, r_{i}$ is the number of pairs of integers $q$, $w$... | Lets add all pair: (x,y) ((d[x]%d[y]==0) || (d[y]%d[x]==0)) to some lest. We can count such pairs using Eretosphen algorithm. Here will be O(n*log(n)) sych pairs using fact, that we have permutation. We will sort all this paairs using counting-sort. Also we will sort given in input intervals. For each given interval we... | [
"data structures"
] | 2,200 | null |
301 | E | Yaroslav and Arrangements | Yaroslav calls an array of $r$ integers $a_{1}, a_{2}, ..., a_{r}$ good, if it meets the following conditions: $|a_{1} - a_{2}| = 1, |a_{2} - a_{3}| = 1, ..., |a_{r - 1} - a_{r}| = 1, |a_{r} - a_{1}| = 1$, at that $a_{1}=\operatorname*{min}_{i=1}a_{i}$.
An array of integers $b_{1}, b_{2}, ..., b_{r}$ is called great, ... | We will build the needed arrays sequentially adding numbers. Let's look at what states we need. First, it is obvious that you need to keep the number of ways to build an array of already added numbers, secondly you need to know the total amount of added numbers. Now let's look at what happens when we add a new number (... | [
"dp"
] | 2,800 | null |
302 | A | Eugeny and Array | Eugeny has array $a = a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ integers. Each integer $a_{i}$ equals to -1, or to 1. Also, he has $m$ queries:
- Query number $i$ is given as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$.
- The response to the query will be integer $1$, if the elements of array $a$ ... | If the length of the given segment is even and count of 1 in input is not lower then half of the length of the segment and count of -1 in the input is not lower then half of the length of the segment so we have answer 1, otherwise 0. | [
"implementation"
] | 800 | null |
302 | B | Eugeny and Play List | Eugeny loves listening to music. He has $n$ songs in his play list. We know that song number $i$ has the duration of $t_{i}$ minutes. Eugeny listens to each song, perhaps more than once. He listens to song number $i$ $c_{i}$ times. Eugeny's play list is organized as follows: first song number $1$ plays $c_{1}$ times, t... | For each song we will count moment of time, when it will be over (some sums on the prefixes, for example). Further, we will use binary search of two itaratos method to solve the problem. | [
"binary search",
"implementation",
"two pointers"
] | 1,200 | null |
303 | A | Lucky Permutation Triple | Bike is interested in permutations. A permutation of length $n$ is an integer sequence such that each integer from 0 to $(n - 1)$ appears exactly once in it. For example, $[0, 2, 1]$ is a permutation of length 3 while both $[0, 2, 2]$ and $[1, 2, 3]$ is not.
A permutation triple of permutations of length $n$ $(a, b, c... | when n is odd, A[i] = B[i] = i when n is even, there is no solution. So why? Because: S = \Sum_{i=0}^{n-1} i = n/2 (mod n) but 2*S = 0 (mod n) | [
"constructive algorithms",
"implementation",
"math"
] | 1,300 | null |
303 | B | Rectangle Puzzle II | You are given a rectangle grid. That grid's size is $n × m$. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers $(x, y)$ $(0 ≤ x ≤ n, 0 ≤ y ≤ m)$.
Your task is to find a maximum sub-rectangle on the grid $(x_{1}, y_{1}, x_{2}, y_{2})$ so that it contai... | Give you $n$, $m$, $x$, $y$, $a$, $b$. Find a maximum sub-rectangle within (0, 0) - ($n$, $m$), so that it contains the given point($x$, $y$) and its length-width radio is exactly ($a$, $b$). If there are multiple solutions, find the rectangle which is closest to ($x$, $y$). If there are still multiple solutions, find ... | [
"implementation",
"math"
] | 1,700 | null |
303 | C | Minimum Modular | You have been given $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$. You can remove at most $k$ of them. Find the minimum modular $m$ $(m > 0)$, so that for every pair of the remaining integers $(a_{i}, a_{j})$, the following unequality holds: $a_{i}\neq a_{j}\;\;\mathrm{mod}\;m$. | It is hard to solve this problem at once, so at first, let us consider on k = 0, this easier case can be solved by enumerate on the $ans$. Let us define a bool array diff[], which diff[x] is weather there are two number, $a_{i}$, $a_{j}$, such that $abs(a_{i} - a_{j}) = x$. So $ans$ is legal <=> diff[ans], diff[2*ans] ... | [
"brute force",
"graphs",
"math",
"number theory"
] | 2,400 | null |
304 | A | Pythagorean Theorem II | In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:
\underline{In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the area... | This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math. | [
"brute force",
"math"
] | 1,200 | null |
304 | B | Calendar | Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:
\underline{Every year that is exactly divisible by four is ... | This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math. | [
"brute force",
"implementation"
] | 1,300 | null |
305 | A | Strange Addition | Unfortunately, Vasya can only sum pairs of integers ($a$, $b$), such that for any decimal place at least one number has digit $0$ in this place. For example, Vasya can sum numbers $505$ and $50$, but he cannot sum $1$ and $4$.
Vasya has a set of $k$ distinct non-negative integers $d_{1}, d_{2}, ..., d_{k}$.
Vasya wan... | All you have to do is implement following algorithm: If we have numbers $0$ or $100$, we take them to needed subset. If we got number greater than $0$ and less than 10, we take it. If we got number $x\in[10;100)$ divisible by 10 we take it. In case we have no numbers of second and third type, we take a number $x\in[10;... | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,600 | #include <cstdio>
#include <vector>
int n, cnt[5], a;
using namespace std;
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", &a);
if (a == 0) {
cnt[0] = 1;
continue;
}
if (a == 100) {
cnt[1] = 1;
continue;... |
305 | B | Continued Fractions | A continued fraction of height $n$ is a fraction of form $a_{1}+{\frac{1}{a_{2}+{\frac{1}{\ldots+{\frac{1}{a_{m}}}}}}}$. You are given two rational numbers, one is represented as $\overset{p}{q}$ and the other one is represented as a finite fraction of height $n$. Check if they are equal. | There are at most two ways to represent rational fraction as continued. Using Euclid algorithm you can do that for $\overset{p}{q}$ and then check equality of corresponding $a_{i}$. | [
"brute force",
"implementation",
"math"
] | 1,700 | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <complex>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <map>
#include <memory.h>
#include <numeric>
#... |
305 | C | Ivan and Powers of Two | Ivan has got an array of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. Ivan knows that the array is sorted in the non-decreasing order.
Ivan wrote out integers $2^{a1}, 2^{a2}, ..., 2^{an}$ on a piece of paper. Now he wonders, what minimum number of integers of form $2^{b}$ $(b ≥ 0)$ need to be added to the pi... | First of all, let's carry over all powers of two in the following way: if we have $a_{i} = a_{j}$, $i \neq j$, carry 1 to $a_{i} + 1$. Now as all of $a_{i}$ are distinct, the answer is $max(a_{i})$ - $cnt(a_{i})$ + 1, where $max(a_{i})$ - maximal value of $a_{i}$,$cnt(a_{i})$ - size of $a$ | [
"greedy",
"implementation"
] | 1,600 | #include <cstdio>
const int NMAX = 100005;
int a[NMAX], n, tmax, tcnt;
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &a[n - i - 1]);
while (n > 0) {
int j = n - 1, cnt;
while (j > 0 && a[n - 1] == a[j - 1]) --j;
cnt = n - j;
if (cnt % 2 == 1) {
... |
305 | D | Olya and Graph | Olya has got a directed non-weighted graph, consisting of $n$ vertexes and $m$ edges. We will consider that the graph vertexes are indexed from 1 to $n$ in some manner. Then for any graph edge that goes from vertex $v$ to vertex $u$ the following inequation holds: $v < u$.
Now Olya wonders, how many ways there are to ... | First of all let's consider a graph on a number line. It's neccesary to have edges $i - > i + 1$(first type). Also you can edges like $i - > i + k + 1$ (second type). Other edges are forbidden. This allows us to understand whether the answer is 0 or not. Also answer is 0 when all edges of second type doesn't intersect,... | [
"combinatorics",
"math"
] | 2,200 | #include <cstdio>
#include <algorithm>
#include <utility>
#include <cassert>
#include <vector>
using namespace std;
const int MOD = 1000000007, N = 1000005;
int n, m, k, ans, degs[N];
#define forn(i,n) for(int i = 0; i < (int) n; i++)
inline int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a;}
... |
305 | E | Playing with String | Two people play the following string game. Initially the players have got some string $s$. The players move in turns, the player who cannot make a move loses.
Before the game began, the string is written on a piece of paper, one letter per cell.
\begin{center}
{\scriptsize An example of the initial situation at $s$ =... | Let's consider substring of $s$ $s[i... j]$, that all characters from $i$ to $j$ are palindrome centers, and $i - 1, j + 1$ are not. Every such substring can be treated independently from the others, and as we don't need to know it'sstructure let's consider only it length $len$. Let's calculate $grundy[len]$ - Grundy f... | [
"games"
] | 2,300 | #include <cstdio>
#include <memory.h>
#include <cstring>
inline int max(int a, int b) { if (a >= b) return a; return b; }
const int N = 5005;
char s[N];
int grundy[N], mex[N], n, totalXor;
int main(){
gets(s);
for(int i = 1; i < N; i++) {
memset(mex, 0, sizeof mex);
for(int j = 0; j < i; j... |
309 | A | Morning run | People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium.
The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can... | We were asked to find the expected value of meetings between the runners. How to do that? As the first step, expected value is lineal, so we can split the initial problems into the different ones: find the expected value of meetings between the fixed pair of runners. We will solve these problems. To do that we need to ... | [
"binary search",
"math",
"two pointers"
] | 2,000 | null |
309 | B | Context Advertising | Advertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better!
In this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly $n$ words. A standard advertising banner has exactly $r$ lines,... | We were asked to find the maximal number of words we can fit into the block of size $r \times c$. Let's first solve such problem: what is the maximal number of consecutive words which can fit in a row of lenth $c$, if the first word has index $i$. We can solve it using binary search or moving the pointer. Now let us ... | [
"dp",
"two pointers"
] | 2,100 | null |
309 | C | Memory for Arrays | You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.
We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some... | We were asked to find the maximal number of arrays we can fit into the memory. A small observation first, let the answer be $k$, then one of the optimal solutions fits the $k$ smallest arrays into the memory. We can assume that we have arrays of size 1 and we want to arrange the memory for the maximal arrays as possibl... | [
"binary search",
"bitmasks",
"greedy"
] | 1,900 | null |
309 | D | Tennis Rackets | Professional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new co... | We were asked to find the number of obtuse triangles which satisfy the problem statement. Author's solution has complexity $O(n^{2})$, but it has some optimizations, so it easily works under the TL. Every triangle has only one obtuse angle. Due to symmetry reasons we can fix one of the sides and assume that obtuse angl... | [
"brute force",
"geometry"
] | 2,700 | null |
309 | E | Sheep | Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming!
A large farm has a meadow with grazing sheep. Overall there are $n$ sheep and each of them contains a unique number from 1 to $n$ — because t... | Author's supposed greedy algorithm as a solution for this problem. Let us follow this algorithm. Let us create to label for every interval $Position_{v}$ and $MaximalPosition_{v}$. $Position_{v}$ - stands for position of $v$ in the required permutation. $MaximalPosition_{v}$ - stands for maximal possible position of $v... | [
"binary search",
"greedy"
] | 2,900 | null |
311 | A | The Closest Pair | Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.
The problem is the follows. Given $n$ points in the plane, find a pair of points betwe... | We read the pseudo code carefully. If we ignore "break", $tot$ will be up to $\textstyle{\frac{n(n-1)}{2}}$. Consider whether we can make such inequality $d \le p[j].x - p[i].x$ is always false. The obvious way is to make all points' x coordinates the same. And we can just choose $n$ distinct numbers to be all points... | [
"constructive algorithms",
"implementation"
] | 1,300 | null |
311 | B | Cats Transport | Zxr960115 is owner of a large farm. He feeds $m$ cute cats and employs $p$ feeders. There's a straight road across the farm and $n$ hills along the road, numbered from 1 to $n$ from left to right. The distance between hill $i$ and $(i - 1)$ is $d_{i}$ meters. The feeders live in hill 1.
One day, the cats went out to p... | Let a[i] be the distance from hill 1 to hill i, s[i]=a[1]+a[2]+ \dots +a[i]. Firstly, we sort the cats by (Ti-a[i]). Then we can divide the cats into P consecutive parts, and plan a feeder for each part. Dynamic Programming can solve this problem. Let f[i,j] indicates the minimum sum of waiting time with i feeders and ... | [
"data structures",
"dp"
] | 2,400 | null |
311 | C | Fetch the Treasure | Rainbow built $h$ cells in a row that are numbered from 1 to $h$ from left to right. There are $n$ cells with treasure. We call each of these $n$ cells "Treasure Cell". The $i$-th "Treasure Cell" is the $a_{i}$-th cell and the value of treasure in it is $c_{i}$ dollars.
Then, Freda went in the first cell. For now, she... | Firstly, we solve such a problem: if we can go exactly k,k1,k2 \dots \dots or kp cells forward each step, what cells can we reach? We divide the H cells into k groups: Group 0,1 \dots \dots k-1. The i-th cell should be in Group (i mod k). If we reach Cell x in Group (x mod k), we can also reach Cell (x+kj , 1<=j<=p) ... | [
"brute force",
"data structures",
"graphs",
"shortest paths"
] | 2,500 | null |
311 | D | Interval Cubing | While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem:
Given an integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run $q$ queries of two types:
- Given two integers $l$ and ... | Consider a number $x$. If we apply an assignment $x = x^{3}$, $x$ becomes $x^{3}$. If we apply such assignment once more, we will get $(x^{3})^{3} = x^{32}$. If we apply such assignment $k$ times, we will get $x^{3k}$. Thus, we can get such a sequence $a_{0} = x, a_{1} = x^{3}, a_{2} = x^{32}, ..., a_{k} = x^{3k}, ...$... | [
"data structures",
"math"
] | 2,600 | null |
311 | E | Biologist | SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa.
She is going to demonstrate this technique. Now SmallR has $n$ dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to $n$. The c... | Obviously, It is about min-cut, which can be solved by max-flow. So, this problem can regarded as the minimum of losing money if we assume SmallR can get all the money and get a total money(sum of wi)at first. Define that, in the min-cut result, the dogs which are connected directly or indirectly to S are 0-gender.othe... | [
"flows"
] | 2,300 | null |
312 | A | Whose sentence is it? | One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ... | We only need to find out if "miao." is a prefix of the sentence, and if "lala." is a suffix of the sentence. Pay attention to the situation when both conditions are satisfied. | [
"implementation",
"strings"
] | 1,100 | null |
312 | B | Archer | SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is $\overset{\stackrel{\alpha}{b}}$ for SmallR while $\frac{\epsilon}{d}$ for Zanoes. The one who shoots in the target first should be ... | let p=a/b,q=(1-c/d)*(1-a/b). The answer of this problem can be showed as:p*q^0+p*q^1+p*q^2+ \dots \dots \dots \dots That is the sum of a geometric progression which is infinite but 0<q<1.We can get the limit by the formula:p/(1-q) | [
"math",
"probabilities"
] | 1,300 | null |
313 | A | Ilya and Bank Account | Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | Ilya and Bank Account This problem is the easiest one. You need to use only div and mod functions. If $n$>0, then answer is $n$, else you need to delete one of two digits. | [
"implementation",
"number theory"
] | 900 | #include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))
#define abs(a) (((a) > 0) ? (a) :... |
313 | B | Ilya and Queries | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string $s = s_{1}s_{2}... s_{n}$ ($n$ is the length of the string), consisting only of characters "." and "#" and $m$ queries. Each query is described by a pair of integers $l_{i}, r... | Precalculate some array $A_{i}$, that $A_{i} = 1$, if $s_{i} = s_{i + 1}$, else $A_{i} = 0$. Now for any query $(l, r)$, you need to find sum of $A_{i}$, that $(l \le i < r)$. It is standart problem. For solving this problem you can precalcutate some another array Sum, where $Sum_{i} = A_{1} + A_{2} + ... + A_{i}$. T... | [
"dp",
"implementation"
] | 1,100 | Var a,l,r:array[1..1000000] of longint;
s:string;
i,m,k:longint;
begin
Readln(s);
for i:=2 to length(s) do
begin
if s[i]=s[i-1] then inc(k);
a[i]:=k;
end;
Readln(m);
for i:=1 to m do
Readln(l[i],r[i]);
for i:=1 to m do
Writeln(a[r[i]]-a[l[i]]);
end. |
313 | C | Ilya and Matrix | Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.
He's got a square $2^{n} × 2^{n}$-sized matrix and $4^{n}$ integers. You need to arrange all these numbers in the matrix (put each number in a sin... | At the start sort array. Let $C_{i}$ - number of times of entering the number in $A_{i}$ optimal placement. Answer is sum of $A_{i} * C_{i}$ for all $i$ $(1 \le i \le 4^{n})$. If we look at the array $C$, we can see that for maximal element $C = n + 1$ (for array with size $4^{n}$), then for second, third and fourt... | [
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 1,400 | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
long long s;
vector<int> a;
scanf("%d", &n);
a.resize(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
sort(a.rbegin(), a.rend());
s = 0;
for (int m = 1; m <= n; m *= 4) {
s += ac... |
313 | D | Ilya and Roads | Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as $n$ holes in a row. We will consider the holes numbered from 1 to $n$, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least $k$ holes (perharps he can fix more) on a sing... | To solve this problem you need to use dynamic programming. Let $Full_{i, j}$ - minimal cost of covering interval $(i, j)$. Fix left border and move right. You can solve this subtask with complexity $O(nm)$ or $O(nmlogn)$. Now we need to solve the standart problem of dynamic programming. Cover $K$ points with intervals ... | [
"dp"
] | 2,100 | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long llint;
const int MAXN = 320;
const llint INF = 0x0123456789ABCDEFLL;
llint d[MAXN][MAXN], dp[MAXN][MAXN];
int main() {
int n, m, k, a, b, c;
llint ans;
scanf("%d%d%d", &n, &m, &k);
fill(d[0], d[n + 1]... |
313 | E | Ilya and Two Numbers | Ilya has recently taken up archaeology. He's recently found two numbers, written in the $m$-based notation. Each of the found numbers consisted of exactly $n$ digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decyphe... | 1) Get the number of our sequences in sorted by frequencies. Thus from the first sequence (hereinafter - the first type) - in a direct order from the second - to the contrary. 2) These numbers are put on the stack, where if, recording onto the stack of the second type, we find the number at the top of the first type, t... | [
"constructive algorithms",
"data structures",
"dsu",
"greedy"
] | 2,300 | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <string>
#include <cmath>
#define Mod (1000000007LL)
#define eps (1e-8)
#define Pi (acos(-1.0))
using namespace std;
int n,m;
int f1[100100],f2[100100];
int f[200200],tot;
int ans[100... |
314 | A | Sereja and Contest | During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that $n$ people took part in the contest. Let's assume that the participant who got the first place has rating $a_{1}$, the second place participant has rating $a_{2}... | Note that if we remove some of the participants, we never remove the participants with lower numbers as theirs amount will only increase. So just consider the sequence of all the participants, and if the participant does not fit we delete him. | [
"implementation"
] | 1,600 | null |
314 | B | Sereja and Periods | Let's introduce the designation $[x,n]=x+x+\cdot\cdot\cdot+x=\sum_{i=1}^{n}x$, where $x$ is a string, $n$ is a positive integer and operation "$ + $" is the string concatenation operation. For example, $[abc, 2] = abcabc$.
We'll say that string $s$ can be obtained from string $t$, if we can remove some characters from... | It is clear that we can use greedy algorithm to look for the number of occurrences of the 2nd string in the first string, but it works too slow. To speed up the process, you can look at the first line of the string that specifies the second period. And the answer is divided into how many string you need to set the seco... | [
"binary search",
"dfs and similar",
"strings"
] | 2,000 | null |
314 | C | Sereja and Subsequences | Sereja has a sequence that consists of $n$ positive integers, $a_{1}, a_{2}, ..., a_{n}$.
First Sereja took a piece of squared paper and wrote all \textbf{distinct} non-empty non-decreasing subsequences of sequence $a$. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all seq... | It is clear that we need to calculate the sum of the products of elements of all the different non-decreasing subsequences of given sequence. Let's go through the sequence from left to right and maintain the array q[i]: what means the sum of all relevant sub-sequences, such that their last element is equal to i. Clearl... | [
"data structures",
"dp"
] | 2,000 | null |
314 | D | Sereja and Straight Lines | Sereja placed $n$ points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the $Ox$ axis at an angle of $45$ degrees and the maximum distance from the points to the straight lines were minimum.
In this problem we consider t... | Roll all at 45 degrees using the transformation: (x, y) -> (x ', y'): x '= x + y, y' = x-y. Next you need to place two lines parallel to the coordinate axes. Sort the points by the first coordinate. Next, we use a binary search for the answer. May we have fixed a number, you now need to check whether it is enough or no... | [
"binary search",
"data structures",
"geometry",
"sortings",
"two pointers"
] | 2,500 | null |
315 | A | Sereja and Bottles | Sereja and his friends went to a picnic. The guys had $n$ soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.
Sereja knows that the $i$-th bottle is from brand $a_{i}$, besides, you can use it to open \textbf{other} bottles of brand $b_{i}$. ... | Just check for each bottle, can I open it with another. In this task can pass absolutely any solutions. | [
"brute force"
] | 1,400 | null |
315 | B | Sereja and Array | Sereja has got an array, consisting of $n$ integers, $a_{1}, a_{2}, ..., a_{n}$. Sereja is an active boy, so he is now going to complete $m$ operations. Each operation will have one of the three forms:
- Make $v_{i}$-th array element equal to $x_{i}$. In other words, perform the assignment $a_{vi} = x_{i}$.
- Increase... | We will support all of the elements in the array, but also we will supprt additionally variable add: how much to add to all the elements. Then to add some value to every element we simply increase the add. In the derivation we deduce the value of the array element + add. When you update the item we put to a value, valu... | [
"implementation"
] | 1,200 | null |
317 | A | Perfect Pair | Let us call a pair of integer numbers $m$-perfect, if at least one number in the pair is greater than or equal to $m$. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers $x$, $y$ are written on the blackboard. It is allowed to erase one of them and replace it with the sum of th... | This problem were more about accuracy then about ideas or coding. It is important to not forget any cases here. On each step we replace one of the numbers $x$, $y$ by their sum $x + y$ until the pair becomes $m$-perfect (id est one of them becomes not lesser than $m$). It is clear that one sould replace lesser number f... | [
"brute force"
] | 1,600 | null |
317 | B | Ants | It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction ($x$, $y$) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions ($x + 1$, $... | One may reformulate the problem ass follows. Non-negative integers $A(x, y)$ are placed in the vertices of two-dimensional lattice $\mathbb{Z}^{2}$ We may imagine this construction as a function $A\colon\mathbb{Z}^{2}\to\mathbb{N}_{0}$. On each step for each vertex $P = (x, y)$ with $A(x, y) \ge 4$ we perform operati... | [
"brute force",
"implementation"
] | 2,000 | null |
317 | C | Balance | A system of $n$ vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of t... | In this problem we need to find $2n^{2}$ transfusions from initial configuration to the desired one. First of all we propose the following: if in each connected component overall volume of the water in initial configuration is the same as in desired one, then answer exist. We call the vessel ready, if current volume of... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"trees"
] | 2,500 | null |
317 | D | Game with Powers | Vasya and Petya wrote down all integers from $1$ to $n$ to play the "powers" game ($n$ can be quite large; however, Vasya and Petya are not confused by this fact).
Players choose numbers in turn (Vasya chooses first). If some number $x$ is chosen at the current turn, it is forbidden to choose $x$ or all of its other p... | For each numner $x$ denote sequence of its powers within $[1..n]$ as $Pow(x)$: $P o w(x)=\{x,x^{2},x^{3},x^{4},\cdot\cdot\cdot\}\cap[1..n].$ Game proceeds as follows: on each step one player takes still available number $x$ from $1$ to $n$ and prohibits whole set $Pow(x)$. Who can't make his turn loses. This game may b... | [
"dp",
"games"
] | 2,300 | null |
317 | E | Princess and Her Shadow | Princess Vlada enjoys springing in the meadows and walking in the forest. One day — wonderful, sunny day — during her walk Princess found out with astonishment that her shadow was missing! "Blimey!", — she thought and started her search of the shadow in the forest.
Normally the Shadow is too lazy and simply sleeps und... | In this problem princess Vlada should simply catch the Shadow. Here is the idea of a solution. If there is only one tree, then using it as a barrier to the shadow it is not hard to catch the shadow. Similar technique works if Vlada and Shadow are far from the square where all the trees grow. But what can she do in the ... | [
"constructive algorithms",
"shortest paths"
] | 3,100 | null |
318 | A | Even Odds | Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first $n$. He writes down the follow... | In this problem we need to understand how exactly numbers from $1$ to $n$ rearrange when we write firstly all odd numbers and after them all even numbers. To find out which number stands at position $k$ one needs to find the position where even numbers start and output either the position of the odd number from the fir... | [
"math"
] | 900 | null |
318 | B | Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of cons... | In the heavy metal problem one needs to find the number of the substrings in the string S with a given prefix A and given suffix B. If we mark black all the starting positions of the entries of the string A in S, and white all the starting positions of the entries of the string B, then we come to the following problem:... | [
"implementation",
"strings",
"two pointers"
] | 1,300 | null |
319 | A | Malek Dance Club | As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has $2^{n}$ members and coincidentally Natalia Fan Club also has $2^{n}$ members. Each member of MDC is assigned a unique id $i$ from $0$ to $2^{n} - 1$. The same hold... | Solving this problem was easy when you modeled the assignment with two sets of points numbered from $0$ to $2^{n} - 1$ (inclusive) paired with $2^{n}$ line segments. Each line segment corresponds to a dance pair. And each pair of intersecting lines increase the complexity by one. Imagine you now the solution for binary... | [
"combinatorics",
"math"
] | 1,600 | null |
319 | C | Kalila and Dimna in the Logging Industry | Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money.
The manager of logging factory wants them to go to the jungle and cut $n$ trees with heights $a_{1}, a_{2}, ..., a_{n}$. They bought a chain saw from a shop. Each time they use the chain saw... | This problem is equal to finding the minimum cost to cut the last tree completely. Because any cutting operation can be done with no cost afterward. Let $dp_{i}$ be the minimum cost to cut the $i$-th tree completely. It's easy to figure out that we can calculate $dp_{i}$ if we know the index of the last tree which has ... | [
"dp",
"geometry"
] | 2,100 | null |
320 | A | Magic Numbers | A magic number is a number formed by concatenation of numbers $1$, $14$ and $144$. We can use each of these numbers any number of times. Therefore $14144$, $141414$ and $1411$ are magic numbers but $1444$, $514$ and $414$ are not.
You're given a number. Determine if it is a magic number or not. | Although the input number is very small, solving the problem for arbitrary length numbers using strings is easier. It's easy to prove that a number meeting the following conditions is magical: The number should only consist of digits $1$ and $4$. The number should begin with digit $1$. The number should not contain thr... | [
"brute force",
"greedy"
] | 900 | #include <iostream>
#include <string>
using namespace std;
bool is_magical(string number) {
for (int i = 0; i < (int)number.size(); i++)
if (number[i] != '1' && number[i] != '4')
return false;
if (number[0] == '4')
return false;
if (number.find("444") != number.npos)
return false;
return true;
}
int ... |
320 | B | Ping-Pong (Easy Version) | In this problem at each moment you have a set of intervals. You can move from interval $(a, b)$ from our set to interval $(c, d)$ from our set if and only if $c < a < d$ \textbf{or} $c < b < d$. Also there is a path from interval $I_{1}$ from our set to interval $I_{2}$ from our set if there is a sequence of successive... | Imagine the intervals as nodes of a graph and draw directed edges between them as defined in the statement. Now answering the second query would be trivial if you are familiar with graph traversal algorithms like DFS or BFS or even Floyd-Warshall! | [
"dfs and similar",
"graphs"
] | 1,500 | #include<iostream>
#include<string.h>
using namespace std;
int a[111],b[111];
bool f[111];
int n = 0;
void dfs(int i)
{
f[i] = true;
for(int k = 1; k <= n;k++)
{
if(f[k])
continue;
if(a[i]>a[k] && a[i] < b[k])
dfs(k);
else if(b[i] > a[k] && b[i] < b[k])
... |
321 | A | Ciel and Robot | Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string $s$. Each character of $s$ is one move operation. There are four move operations at all:
- 'U': go up, (x, y) $ → $ (x, y+1);
- 'D': go down, (x, y) $ → $ (x, y-1);
- 'L': go left... | Note that after Ciel execute string s, it will moves (dx, dy). And for each repeat, it will alway moves (dx, dy). So the total movement will be k * (dx, dy) + (dx[p], dy[p]) which (dx[p], dy[p]) denotes the movement after execute first p characters. We can enumerate p since (0 <= p < |s| <= 100), and check if there are... | [
"binary search",
"implementation",
"math"
] | 1,700 | null |
321 | B | Ciel and Duel | Fox Ciel is playing a card game with her friend Jiro.
Jiro has $n$ cards, each one has two attributes: $position$ (Attack or Defense) and $strength$. Fox Ciel has $m$ cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.
Now is Ciel's battle phase, Ciel can do the follo... | We have 3 solutions to this problem: = 1. greedy = There are 2 cases: we killed all Jiro's cards, or not. If we are not killed all of Jiro's cards, then: We never attack his DEF cards, it's meaningless. Suppose we make k attacks, then it must be: use Ciel's k cards with highest strength to attack Jiro's k cards with lo... | [
"dp",
"flows",
"greedy"
] | 1,900 | null |
321 | C | Ciel the Commander | Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has $n$ cities connected by $n - 1$ undirected roads, and for any two cities there always exists a path between them.
Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 d... | This is a problem with construction on trees. And for these kind of problems, we usually use two method: up-down or down-up. So we have 1 solution for each method: = 1. up-down construction = Suppose we assign an officer with rank A at node x. Then for two distinct subtree rooted by x, says T1 and T2: There can't be an... | [
"constructive algorithms",
"dfs and similar",
"divide and conquer",
"greedy",
"trees"
] | 2,100 | null |
321 | D | Ciel and Flipboard | Fox Ciel has a board with $n$ rows and $n$ columns, there is one integer in each cell.
It's known that $n$ is an odd number, so let's introduce $x={\frac{n+1}{2}}$. Fox Ciel can do the following operation many times: she choose a sub-board with size $x$ rows and $x$ columns, then all numbers in it will be multiplied b... | For this problem we need a big "observation": what setup of "flips" are valid? What means set up of "flips", well, for example, after the 1st step operation of example 1, we get: 1 1 0 1 1 0 0 0 0It means the left top 2x2 cells are negatived. Given a 0-1 matrix of a set up of "flips", how can you determine if we can ge... | [
"dp",
"greedy",
"math"
] | 2,900 | null |
321 | E | Ciel and Gondolas | Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are $n$ people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and $n$-th people to refer the last one in the queue.
There will be $k$ gondolas, and the way we allocate go... | This problem may jog your memory of OI times (if you have been an OIer and now grows up, like me). Maybe some Chinese contestants might think this problem doesn't worth 2500, but DP optimization is an advanced topic in programming contest for many regions. It's quite easy to find an O(N^2 K) DP: dp[i][j] = max{ k | dp[... | [
"data structures",
"divide and conquer",
"dp"
] | 2,600 | null |
322 | A | Ciel and Dancing | Fox Ciel and her friends are in a dancing room. There are $n$ boys and $m$ girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
- either the boy in the dancing pair must dance for the first time (... | Let's define remainNew = # of people haven't danced before. So at beginning remainNew = n+m, and we have: During the 1st song, remainNew must decreased by at least 2. (Because the boy and girl must haven't danced before.) During the k-th (k>1) song, remainNew must decreased by at least 1. (Because one of the boy or gir... | [
"greedy"
] | 1,000 | null |
322 | B | Ciel and Flowers | Fox Ciel has some flowers: $r$ red flowers, $g$ green flowers and $b$ blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:
- To make a "red bouquet", it needs 3 red flowers.
- To make a "green bouquet", it needs 3 green flowers.
- To make a "blue bouquet", it needs 3 bl... | If there are no "mixing bouquet" then the answer will be r/3 + g/3 + b/3. One important observation is that: There always exist an optimal solution with less than 3 mixing bouquet. The proof is here: Once we get 3 mixing bouquet, we can change it to (1 red bouquet + 1 green bouquet + 1 blue bouquet) So we can try 0, 1,... | [
"combinatorics",
"math"
] | 1,600 | null |
325 | A | Square and Rectangles | You are given $n$ rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the $Ox$ and $Oy$ axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to determine if the r... | What happens if the rectangles form an $N \times N$ square? Then these two conditions are necessary. 1) The area must be exactly $N \times N$. 2) The length of its sides must be $N$. That means, the difference between the right side of the rightmost rectangle - the left side of the leftmost rectangle is $N$. Same f... | [
"implementation"
] | 1,500 | null |
325 | B | Stadium and Games | Daniel is organizing a football tournament. He has come up with the following tournament format:
- In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages ar... | Suppose the "divide-by-two" stage happens exactly $D$ times, and the round robin happens with $M$ people. Then, the number of games held is: ${\frac{M(M-1)}{2}}+M\times(2^{D}-1)$ We would like that ${\frac{M(M-1)}{2}}+M\times(2^{D}-1)=N$ This is an equation with two variables -- to solve it, we can enumerate the value ... | [
"binary search",
"math"
] | 1,800 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.