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 ⌀ |
|---|---|---|---|---|---|---|---|
255 | A | Greg's Workout | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was $n$ integers $a_{1}, a_{2}, ..., a_{n}$. These numbers mean that Greg needs to do exactly $n$ exercises today. Besides, Greg should repeat the $i$-th in order exercise $a_{i}$ times.
Greg now only does three types of exercis... | It is not hard problem. We must calculate sums of numbers for each group and print group with maximum count. | [
"implementation"
] | 800 | null |
255 | B | Code Parsing | Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string $s$, consisting of characters "x" and "y", and uses two following operations at runtime:
- Find two consecutive characters in the string, such that the first of them equals "y", and the se... | Not hard to see that after few operations of first type string will become: x..xy..y. After fer operations of second type, there will be only letters of one type, count of this letters will be: |count(x) - count(y)| | [
"implementation"
] | 1,200 | null |
255 | D | Mr. Bender and Square | Mr. Bender has a digital table of size $n × n$, each cell can be switched on or off. He wants the field to have at least $c$ switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to $n$, and the columns — numbered from left to r... | Solution - binary search for answer. Next we have to calculate the area of a truncated square set at 45 degrees. This can be done as follows: Calculate its total area. Subtract area that cuts off the top line. Similarly, for the lower, left and right line. Add parts that are cutted by corners. You can write a function ... | [
"binary search",
"implementation",
"math"
] | 1,800 | null |
255 | E | Furlo and Rublo and Game | Furlo and Rublo play a game. The table has $n$ piles of coins lying on it, the $i$-th pile has $a_{i}$ coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to:
- choose some pile, let's denote the current number of coins in it as $x$;
- choose some integer $y$ $(0 ≤ y < x; x^{1 / 4} ≤ y... | Note that after the first move any pile turns into a pile no larger than 1000000. We assume Grundy function for numbers less than 1 million. Grundy function is very small, you can start on the partial sums for each type of function that would quickly tell what function is in the interval, and which are not present. Kno... | [
"games",
"implementation",
"math"
] | 2,200 | null |
256 | D | Liars and Serge | There are $n$ people, sitting in a line at the table. For each person we know that he always tells either the truth or lies.
Little Serge asked them: how many of you always tell the truth? Each of the people at the table knows everything (who is an honest person and who is a liar) about all the people at the table. Th... | If person say number x, and at all x was said by x persons, then we cannot tell anything about fixed person. Now we understand which sequence are good for us. We will calculate their count wuth dynamic programming dp[n][m][k], n - which persons answers we set to the sequence right now, m - how mant persons gived theis ... | [
"dp"
] | 2,700 | null |
256 | E | Lucky Arrays | Little Maxim loves interesting problems. He decided to share one such problem with you.
Initially there is an array $a$, consisting of $n$ zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array $a$. Each query is characterized by two integers $v_{i}, t_{i}$. In the answer t... | Solution is - interval tree. We will save dynamic programming f[i,j] in each vertex, this dp means: in how many ways we can change all 0 to some numbers on interval, such that it will be valid and first element will be i and last will be j. With normal implementation its easy to pass system tests. | [
"data structures"
] | 2,400 | null |
258 | A | Little Elephant and Bits | The Little Elephant has an integer $a$, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number $a$ fits on the piece of paper, the Little Elephant \textbf{ought} to delete exactly one any digit from number $a$ in the binary record. At that a new number appears. ... | It's pretty easy to notice that you need to delete the first (from the left) 0-digit. The only catchy case is 111...111 - here you need to delete any of 1-digits. | [
"greedy",
"math"
] | 1,100 | null |
258 | B | Little Elephant and Elections | There have recently been elections in the zoo. Overall there were $7$ main political parties: one of them is the Little Elephant Political Party, $6$ other parties have less catchy names.
Political parties find their number in the ballot highly important. Overall there are $m$ possible numbers: $1, 2, ..., m$. Each of... | First of all, lets think about the problem of finding array $c_{i}$ - the number of integers from 1 to $m$ such, that the number of lucky digits is equal to $i$. It's pretty standart dynamic programminc problem, which can be solved with state [position][less][count]. It can be solved directly using DP, but to simplify ... | [
"brute force",
"combinatorics",
"dp"
] | 1,900 | null |
258 | C | Little Elephant and LCM | The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of $k$ positive integers $x_{1}, x_{2}, ..., x_{k}$ is the minimum positive integer that is divisible by each of numbers $x_{i}$.
Let's assume that there is a sequence of integer... | The complexity of the possible solution is $O(n * sqrt(n) * log(n))$. You can see that statement $lcm(b_{1}, b_{2}, ..., b_{n}) = max(b_{1}, b_{2}, ..., b_{n})$ is equal to statement "All the numbers $b_{1}, b_{2}, ..., b_{n}$ must divide $max(b_{1}, b_{2}, ..., b_{n})$". You can iterate that $max(b_{1}, b_{2}, ..., b_... | [
"binary search",
"combinatorics",
"dp",
"math"
] | 2,000 | null |
258 | E | Little Elephant and Tree | The Little Elephant loves trees very much, he especially loves root trees.
He's got a tree consisting of $n$ nodes (the nodes are numbered from 1 to $n$), with root at node number $1$. Each node of the tree contains some list of numbers which initially is empty.
The Little Elephant wants to apply $m$ operations. On t... | Very useful thing in this problem is ordering all vertices in DFS order (preorped). After that any subtree can be represented as a some sequence of continuous vertices. Consider that we have some fixed vertex $v$. Which vertices should be included in $c_{v}$? Obviously, if in the path from the root to $v$ is some non-e... | [
"data structures",
"dfs and similar",
"trees"
] | 2,400 | null |
259 | A | Little Elephant and Chess | The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an $8 × 8$ checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard do... | Obviously, the only correct rows are rows WBWBWBWB and BWBWBWBW. Only thing you need to do is to check whether each string is one of these. If yes then print YES, else print NO. | [
"brute force",
"strings"
] | 1,000 | null |
259 | B | Little Elephant and Magic Square | Little Elephant loves magic squares very much.
A magic square is a $3 × 3$ table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals ... | Since each number is less than or equal to $10^{5}$, you can loop all possible $a_{1, 1}$ values, the rest of cells can be calculated from this. | [
"brute force",
"implementation"
] | 1,100 | null |
260 | A | Adding Digits | Vasya has got two number: $a$ and $b$. However, Vasya finds number $a$ too short. So he decided to repeat the operation of lengthening number $a$ $n$ times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di... | At first try to add to the right one digit from $0$ to $9$. If it is impossible write -1. In other case, the remaining $n-1$ digits can be $0$ because divisibility doesn't change. | [
"implementation",
"math"
] | 1,400 | null |
260 | B | Ancient Prophesy | A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha... | In this problem you have to consider every date from $2013$ to $2015$ year (there is no leap years in this interval), count occurrences of this date and find maximum. In one year there is $365$ days, so the complexity of the solution $(3 \cdot 365 \cdot N)$. | [
"brute force",
"implementation",
"strings"
] | 1,600 | null |
260 | C | Balls and Boxes | Little Vasya had $n$ boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to $n$ from left to right.
Once Vasya chose one of the boxes, let's assume that its number is $i$, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began pu... | Firstly describe simple solution. We will get by one ball from boxes (we begin from box $x$) from right to left (action back). At some moment there will be $0$ balls in current box. This box is the first box in our initial problem (from which we took all balls and begun to put). In this box we put all balls, which we g... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,700 | null |
260 | D | Black and White Tree | The board has got a painted tree graph, consisting of $n$ nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.
Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each ed... | The problem can be solved constructively maintaining the following invariant (rule) - the sum of the white vertices equals to the sum of the black vertices. The tree is a bipartite graph, so we build bipartite graph with no cycles, which will satisfy the conditions of the problem. Parts of graph will be black and white... | [
"constructive algorithms",
"dsu",
"graphs",
"greedy",
"trees"
] | 2,100 | null |
260 | E | Dividing Kingdom | A country called Flatland is an infinite two-dimensional plane. Flatland has $n$ cities, each of them is a point on the plane.
Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four \textbf{distinct} straight lines, such th... | Consider $9!$ variants of location of integers $a[i]$ on $9$ areas. When we consider some location (some grid), we can easily find amount of cities to the left of the left vertical line, to the right of the right vertical line, below the lower horizontal line and above the upper horizontal line. All these numbers is su... | [
"binary search",
"brute force",
"data structures"
] | 2,500 | null |
261 | A | Maxim and Discounts | Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are $m$ types of discounts. We assume that the discounts are indexed from 1 to $m$. To use the discount number $i$, the customer takes a special basket, where he puts exactly $q_{i}$ items he buys. Und... | Ofcourse the most optimal way is to use discount with minimal q_i. We will sort our numbers and will go from the end to begin of the array. We will by use our discount as soon as it will be possible. It's not hard to see that we will buy all the items with numbers I (zero-numeration from the end of the sorted array) su... | [
"greedy",
"sortings"
] | 1,400 | null |
261 | B | Maxim and Restaurant | Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is $p$ meters.
Maxim has got a dinner party tonight, $n$ guests will come to him. Let's index the guests of Maxim's restaurant from 1 to $n$. Maxim knows the sizes of all guests that are going to come to him. The $i$-th guest'... | If all people can come, we will return answer as n. If it is impossible, there will be finded some person that will be the last to come. We will brtueforce this value. Then we will detrminate dp[i,j,s] in how many ways j persons from the first i with total length s can be in the resturant. It is easy to calculate. Then... | [
"dp",
"math",
"probabilities"
] | 1,900 | null |
261 | C | Maxim and Matrix | Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size $(m + 1) × (m + 1)$:
Maxim asks you to count, how many numbers $m$ $(1 ≤ m ≤ n)$ are there, such that the sum of values in the cells in the row number $m + 1$ of the resulting matrix equals $t$.
Expression ($x$ $x... | For fixed m, the sum in the last row will be 2^(bit_count(m+1)-1). So now if T is not power of 2, answer is 0. Else we can find number of bits that we need. And know we have stndart problem. How many numbers form 2 to n+1 have exactly P bits in binary presentation of the number. It is well known problem can be done usi... | [
"constructive algorithms",
"dp",
"math"
] | 2,000 | null |
261 | D | Maxim and Increasing Subsequence | Maxim loves sequences, especially those that strictly increase. He is wondering, what is the length of the longest increasing subsequence of the given sequence $a$?
Sequence $a$ is given as follows:
- the length of the sequence equals $n × t$;
- $a_{i}=b_{((i-1)}\;\;\mathrm{mod}\;n)+1$ $(1 ≤ i ≤ n × t)$, where operat... | This problem can be done using dp[i,j] where we can end our increasing sequence with length i and last number j. Its not hard to understand that number of states will be n*b. To make a tranfer we need to know array first[j] - first position of the number j in the sequence b, next[i][j] - first position of the number j ... | [
"dp"
] | 2,600 | null |
262 | A | Roma and Lucky Numbers | Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.
Roma's got $n$ ... | This problem just need to simulate everithing that was given in statment. | [
"implementation"
] | 800 | null |
262 | B | Roma and Changing Signs | Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of $n$ integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly $k$ changes of signs of s... | We will "reverse" numbers from the begining to the end while numebrers are negative and we did't spend all k operations. In the end there can leave some operetions, and we will "reverse" only one numeber, with minimal value k(that remains) times. | [
"greedy"
] | 1,200 | null |
263 | A | Beautiful Matrix | You've got a $5 × 5$ matrix, consisting of $24$ zeroes and a single number one. Let's index the matrix rows by numbers from $1$ to $5$ from top to bottom, let's index the matrix columns by numbers from $1$ to $5$ from left to right. In one move, you are allowed to apply one of the two following transformations to the m... | If the single $1$ is located on the intersection of the $r$-th row and the $c$-th column (1-based numeration), then the answer is $|3 - r| + |3 - c|$. | [
"implementation"
] | 800 | null |
263 | B | Squares | Vasya has found a piece of paper with a coordinate system written on it. There are $n$ distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to $n$. It turned out that points with coordinates $(0, 0)$ and $(a_{i}, a_{i})$ are the opposite corners of the $i$-th square.
Vasya wa... | If $k > n$, then the answer doesn't exist. Otherwise let's sort the squares by descending of their sizes. Now you can print any point that belongs to the $k$-th square and doesn't belong to the $k + 1$-th square. One of the possible answers is $(a_{k}, 0)$. | [
"greedy",
"implementation",
"sortings"
] | 900 | null |
263 | C | Circle of Numbers | One day Vasya came up to the blackboard and wrote out $n$ distinct integers from $1$ to $n$ in some order in a circle. Then he drew arcs to join the pairs of integers $(a, b)$ $(a ≠ b)$, that are either each other's immediate neighbors in the circle, or there is number $c$, such that $a$ and $с$ are immediate neighbors... | First of all, we have to check that each number occurs in the input exactly 4 times. If it's not true, then the answer definitely doesn't exist. Otherwise, let's try to restore the circle. As cyclic shift of circle doesn't matter, let $1$ to be the first number. As the second and the third number must be connected to e... | [
"brute force",
"dfs and similar",
"implementation"
] | 2,000 | null |
263 | D | Cycle in Graph | You've got a undirected graph $G$, consisting of $n$ nodes. We will consider the nodes of the graph indexed by integers from 1 to $n$. We know that each node of graph $G$ is connected by edges with at least $k$ other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least $k + ... | Consider any simple path $v_{1}, v_{2}, ..., v_{r}$ which cannot be increased immediately (by adding a node to it's end, $v_{r}$). In other words, all the neighbours of $v_{r}$ are already included in the path. Let's find the first node of the path (say, $v_{l}$), which is connected to $v_{r}$. It is clear that $v_{l},... | [
"dfs and similar",
"graphs"
] | 1,800 | null |
263 | E | Rhombus | You've got a table of size $n × m$. On the intersection of the $i$-th row ($1 ≤ i ≤ n$) and the $j$-th column ($1 ≤ j ≤ m$) there is a non-negative integer $a_{i, j}$. Besides, you've got a non-negative integer $k$.
Your task is to find such pair of integers $(a, b)$ that meets these conditions:
- $k ≤ a ≤ n - k + 1$... | Divide the rhombus of size $k$ into 4 right-angled triangles as shown on a picture below. One of them has size $k$, two - size $k - 1$, and another one - size $k - 2$. Let's solve the problem separately for each triangle. The most convenient way to do that is to rotate the input 4 times and run the same solving functio... | [
"brute force",
"data structures",
"dp"
] | 2,500 | null |
264 | A | Escape from Stones | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval $[0, 1]$. Next, $n$ stones will fall and Liss will escape from the stones. The stones are numbered from 1 to $n$ in order.
The stones always fall to the center of Liss's... | In this problem, there are many simple algorithms which works in $O(n)$. One of them (which I intended) is following: You should prepare 2 vectors. If $s[i] = 'l'$, you should push i to the first vector, and if $s[i] = 'r'$, you should push i to the second vector. Finally, you should print the integers in the second ve... | [
"constructive algorithms",
"data structures",
"implementation",
"two pointers"
] | 1,200 | null |
264 | B | Good Sequences | Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks $n$ integers $a_{1}, a_{2}, ..., a_{n}$ are good.
Now she is interested in good sequences. A sequence $x_{1}, x_{2}, ..., x_{k}$ is called good if it satisfies the following three conditions:
- The sequence is strictly increasi... | The main idea is DP. Let's define $dp[x]$ as the maximal value of the length of the good sequence whose last element is $x$, and define $d[i]$ as the (maximal value of $dp[x]$ where $x$ is divisible by $i$). You should calculate $dp[x]$ in the increasing order of x. The value of $dp[x]$ is (maximal value of $d[i]$ wher... | [
"dp",
"number theory"
] | 1,500 | null |
264 | C | Choosing Balls | There are $n$ balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the $i$-th ball is $c_{i}$ and the value of the $i$-th ball is $v_{i}$.
Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She ... | There are many $O(Q * N * logN)$ solutions using segment trees or other data structures, but probably they will get time limit exceeded. We can solve each query independently. First, let's consider the following DP algorithm. $dp[c]$ := the maximal value of a sequence whose last ball's color is $c$ For each ball $i$, w... | [
"dp"
] | 2,000 | null |
264 | D | Colorful Stones | There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings $s$ and $t$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone of the first sequence. Similarly, the $i$-th (1-based) character of $t$ represents the color of the $i$... | First, let's consider a simpler version of the problem: You are given a start state and a goal state. Check whether the goal state is reachable from the start state. Define $A$, $B$, $C$, and $D$ as in the picture below, and let $I$ be the string of your instructions. $A$ and $B$ are substrings of $s$, and $C$ and $D$ ... | [
"dp",
"two pointers"
] | 2,500 | null |
264 | E | Roadside Trees | Squirrel Liss loves nuts. Liss asks you to plant some nut trees.
There are $n$ positions (numbered 1 to $n$ from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types:
- Plant a tree of height ... | When you want to plant a tree with height h at time t, you should plant a tree with height h-t instead. Then you can ignore the growth of the trees. And plot trees on a x-y plane: x-coordinate is the position and y-coordinate is the modified height (h-t). like this picture then..... LIS is the longest sequence of point... | [
"data structures",
"dp"
] | 3,000 | null |
265 | A | Colorful Stones (Simplified Edition) | There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string $s$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.
Ini... | In this problem you just need to implement what is written in the statement. Make a variable that holds the position of Liss, and simulate the instructions one by one. | [
"implementation"
] | 800 | null |
265 | B | Roadside Trees (Simplified Edition) | Squirrel Liss loves nuts. There are $n$ trees (numbered $1$ to $n$ from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree $i$ is $h_{i}$. Liss wants to eat all nuts.
Now Liss is on the root of the tree with the number $1$. In one second Liss can perform one of th... | The optimal path of Liss is as follows: First she starts from the root of tree 1. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{1}, h_{2})$. Jump to the tree 2. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{2}, h_{3})$, $...$ and so on. | [
"greedy",
"implementation"
] | 1,000 | null |
266 | A | Stones on the Table | There are $n$ stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. | In this problem you should count number of consecutive pairs of equal letters. It can be done using one cycle and $O(N)$ time. | [
"implementation"
] | 800 | null |
266 | B | Queue at the School | During the break the schoolchildren, boys and girls, formed a queue of $n$ people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward ea... | In this you should realize the given process. You should $t$ times swap elements $i$ and $i + 1$ if on the place $i$ was a girl and on the place $i + 1$ was a boy. You should not push some girl to the left multiple times at once. The solution can be written using $O(N \cdot T)$ time. | [
"constructive algorithms",
"graph matchings",
"implementation",
"shortest paths"
] | 800 | null |
266 | C | Below the Diagonal | You are given a square matrix consisting of $n$ rows and $n$ columns. We assume that the rows are numbered from $1$ to $n$ from top to bottom and the columns are numbered from $1$ to $n$ from left to right. Some cells ($n - 1$ cells in total) of the the matrix are filled with ones, the remaining cells are filled with z... | This problem can be solved using constructive algorithm. We will use inductive approach. At first, we have matrix of size $n$ and $n - 1$ ones in it. Therefore, there is a column with no ones in it. So, we put this column to $n$-th place. In this case, the lower right element will be $0$. Then find any row with at leas... | [
"constructive algorithms",
"greedy",
"math"
] | 2,100 | null |
266 | D | BerDonalds | BerDonalds, a well-known fast food restaurant, is going to open a cafe in Bertown. The important thing is to choose the new restaurant's location so that it would be easy to get there. The Bertown road system is represented by $n$ junctions, connected by $m$ bidirectional roads. For each road we know its length. We als... | I'll tell a few ideas how to solve this problem. Firstly, describe the solution with time $O(N^{4})$. Consider every edge $(u, v)$ of length $len$ where could be the answer point. Let this point lie at a distance $x$ from vertex $u$. So, the distance from this point to vertex $i$ would be $min(x + d[u][i], len-x + d[v]... | [
"graphs",
"math",
"shortest paths"
] | 2,400 | null |
266 | E | More Queries to Array... | You've got an array, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to quickly run the queries of two types:
- Assign value $x$ to all elements from $l$ to $r$ inclusive. After such query the values of the elements of array $a_{l}, a_{l + 1}, ..., a_{r}$ become equal to $x$.
- Calculate and print... | This problem can be solved using data structure. We would use segment tree, we will support $k$ segment trees for every power. At every vertex we will calculate weighted sum of the appropriate power, also we will save some number that indicates the color of the whole segment, if any. User Egor in comments to the post a... | [
"data structures",
"math"
] | 2,500 | null |
268 | A | Games | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | With only 30 teams, the simplest solution is simulating all the matches: An O(N + M) solution is also possible, where M is the length of colors' range (i.e. 100 under the given constraints). First, you need to count for each color i the number of teams cntH[i] which have the home uniform of color i and the number of te... | [
"brute force"
] | 800 | null |
268 | B | Buttons | Manao is trying to open a rather challenging lock. The lock has $n$ buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the seque... | Let us first detect the worst case scenario. It is more or less apparent that when Manao tries to guess the i-th (1 <= i <= n) button in order, he will make n-i mistakes in the worst case. After that the correct button is evident. Now let's count the total number of presses Manao might need before he guesses the whole ... | [
"implementation",
"math"
] | 1,000 | null |
268 | C | Beautiful Sets of Points | Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:
- The coordinates of each point in the set are integers.
- For any two points from the set, the distance between them is a non-integer.
Consider all points $(x, y... | Obviously, if a set contains a point (x', y'), it can not contain any other point with x=x' or y=y', because these two points would be an integer distance apart. There are only n+1 distinct x-coordinates and m+1 distinct y-coordinates. Therefore, the size of the set sought can not exceed min(n, m) + 1. If the constrain... | [
"constructive algorithms",
"implementation"
] | 1,500 | null |
268 | D | Wall Bars | Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money.
After reviewing the formal specifications for the wall bars, Manao discovered a number of controv... | Those who are well experienced at dynamic programming can scroll down to "Overall solution" right away. Those who have some experience in DPs can read my attempt to explain how you can come up with that solution. Those with no experience probably shouldn't read this at all :) Imagine a solution which considers all poss... | [
"dp"
] | 2,300 | #include <cstdio>
#include <cstring>
#include <algorithm>
#define FOR(i,s,e) for (int i=(s); i<(e); i++)
#define FOE(i,s,e) for (int i=(s); i<=(e); i++)
#define FOD(i,s,e) for (int i=(s)-1; i>=(e); i--)
#define CLR(a,x) memset(a, x, sizeof(a))
#define EXP(i,l) for (int i=(l); i; i=qn[i])
#define LLD long long
using nam... |
268 | E | Playlist | Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.
Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure... | Let us first find the answer for a fixed sequence of songs. Consider any two songs which are at positions i and j (i < j) in the playlist. If Manao liked song i and disliked song j, then song i will be listened to again. Therefore, with probability p[i]*(1-p[j]) the process length will increase by L[i]. The sum of L[i]... | [
"math",
"probabilities",
"sortings"
] | 2,100 | null |
269 | A | Magical Boxes | Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.
From the top view each magical box looks like a square with side length equal to $2^{k}$ ($k$ is an integer, $k ≥ 0$) units. A magical box $v$ can be p... | Suppose we can put all the squares inside a square with side length $2^{p}$. Then we can insert each $k_{i}$ type squares independently along the grid as shown in the picture. No two squares will overlap, since $2^{x}$ divides $2^{y}$, if $x < y$. That means that we can find the smallest square that can hold all the gi... | [
"greedy",
"math"
] | 1,600 | #include<cstdio>
#include<algorithm>
using namespace std;
int main() {
int n; scanf("%d", &n);
int p = 0, maxk = 0;
for(int i = 0; i < n; i++) {
int k, a; scanf("%d %d", &k, &a);
maxk = max(k, maxk);
int m = 0, s = 1;
while(s < a) {
s *= 4;
m++;
}
p = max(p, k+m);
}
if(p == maxk) {
p++;
}
... |
269 | B | Greenhouse Effect | Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.
Over the years Emuskald has cultivated $n$ plants in his greenhouse, of $m$ different plant species numbered from 1 to $m$. His greenhouse is very narrow and can be viewed as an infinite line, with each p... | First, observe that the coordinates don't matter: only the order of the points is important. Let there be some number of points we can replace to achieve the good arrangement. Then all the other points remain in their positions, so their values must be in increasing order from left to right. Then we must find the maxim... | [
"dp"
] | 1,700 | #include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
#define MAXN 5005
int n, m, type[MAXN], dp[MAXN];
int main() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++) {
double x;
scanf("%d %lf", type+i, &x);
}
for(int i = 1; i <= n; i++) {
int j = type[i];
for(int k = j; k... |
269 | C | Flawed Flow | Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of $n$ vertices and $m$ edges. Vertices are numbered from 1 to $n$. Vertices $1$ and $n$ being the source and the sink respectively.
Ho... | The key element to solving the task is the following observation: if we know all the incoming edges of a vertex, all the remaining edges must be outgoing. The source has no incoming edges, so we already know that all its edges are outgoing. For all other vertices except the sink the amount of incoming and outcoming flo... | [
"constructive algorithms",
"flows",
"graphs",
"greedy"
] | 2,100 | #include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
#define MAXN 200005
#define pb push_back
struct edge {
int v, c, i, d;
edge(int v, int c, int i, int d) : v(v), c(c), i(i), d(d) {}
};
typedef vector<vector<edge> > graph;
int n, m, d[MAXN], f[MAXN... |
269 | D | Maximum Waterfall | Emuskald was hired to design an artificial waterfall according to the latest trends in landscape architecture. A modern artificial waterfall consists of multiple horizontal panels affixed to a wide flat wall. The water flows down the top of the wall from panel to panel until it reaches the bottom of the wall.
The wall... | We will use a sweepline algorithm to solve this task. This horizontal sweepline runs from bottom to top, and holds the parts of the segments that are visible from the line this sweepline is currently at. Each part also holds the reference to its original segment. The sweepline itself is implemented with a binary search... | [
"data structures",
"dp",
"graphs",
"sortings"
] | 2,600 | #include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
#define MAXN 100005
int inf = 2000000000;
struct segment {
int h, l, r;
segment(){}
segment(int h, int l, int r) : h(h), l(l), r(r) {}
bool operator < (const segment &s) const {
return h < s.h;
... |
269 | E | String Theory | Emuskald is an innovative musician and always tries to push the boundaries of music production. Now he has come up with an idea for a revolutionary musical instrument — a rectangular harp.
A rectangular harp is a rectangle $n × m$ consisting of $n$ rows and $m$ columns. The rows are numbered 1 to $n$ from top to botto... | There are overall 6 types of segments that connect the sides: left-top; top-right; right-bottom; bottom-left; left-right; top-bottom; If there are both left-right and top-bottom segments, there is no solution. Otherwise there remain only 5 types of segments. Without loss of generality suppose there are no left-right se... | [
"geometry",
"math",
"strings"
] | 3,100 | #include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef pair<int,int> pii;
#define MAXN 1000005
int n, m, cnt[4][4], id[128], GS[4][MAXN], GC[4][MAXN], IS[4][MAXN], IC[4][MAXN], colp[MAXN], row... |
270 | A | Fancy Fence | Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle $a$.
Will the robot be able to build the fence Emuska... | Consider all supplementary angles of the regular $n$-polygon with angle $a$, which are equal to $180^\circ - a$. Their sum is equal to $360^{\circ}$, because the polygon is convex. Then the following equality holds: $n \cdot (180 - a) = 360$, which means that there is an answer if and only if $360{\mathrm{~~mod~}}(180-... | [
"geometry",
"implementation",
"math"
] | 1,100 | #include<iostream>
#include<cstdio>
using namespace std;
int main() {
int t; cin >> t;
for(int i = 0; i < t; i++) {
int a; cin >> a;
cout << (360 % (180-a) == 0 ? "YES" : "NO") << endl;
}
} |
270 | B | Multithreading | Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.
Recent actions shows a list of $n$ different threads ordered by the time of the latest message in the threa... | If some $a_{i}$ is greater than $a_{i + 1}$, it is clear that $a_{i}$ definitely contains a new message because the order of these two elements has changed. Let the last such element be $a_{k}$. Then all of the elements $a_{k + 1}$, $a_{k + 2}$, $...$, $a_{n}$ can contain no new messages, since their order has not chan... | [
"data structures",
"greedy",
"implementation"
] | 1,400 | #include<iostream>
using namespace std;
int a[100005];
int main() {
int n; cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
int i = n-1;
while(i > 0 && a[i-1] < a[i]) {
i--;
}
cout << i << endl;
} |
271 | A | Beautiful Year | It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | This is a very straight forward problem. Just add 1 to a year number while it still has equal digits. | [
"brute force"
] | 800 | null |
271 | B | Prime Matrix | You've got an $n × m$ matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by $1$. Each element can be increased an arbitrary number of times.
You are really curious about prime numbers. Let us remind you th... | Precalculate the next prime for every integer from $1$ to $10^{5}$. You can do that in any way. The main thing is to test all the divisors up to square root when you are checking if a number is prime. Now for each $a_{ij}$ (element of the given matrix) we can easily calculate $add_{ij}$ - how many do we have to add in ... | [
"binary search",
"brute force",
"math",
"number theory"
] | 1,300 | null |
271 | C | Secret | The Greatest Secret Ever consists of $n$ words, indexed by positive integers from $1$ to $n$. The secret needs dividing between $k$ Keepers (let's index them by positive integers from $1$ to $k$), the $i$-th Keeper gets a \textbf{non-empty} set of words with numbers from the set $U_{i} = (u_{i, 1}, u_{i, 2}, ..., u_{i,... | If $3k > n$ there is no solution (because each of the $k$ sets must have at least 3 elements). Otherwise we can divide first $3k$ words in the following way: 1 1 2 2 3 3 ... k k 1 2 3 ... k For each of the $k$ sets, the difference between the first and the second elements will be $1$. And the difference between the sec... | [
"constructive algorithms",
"implementation"
] | 1,500 | null |
271 | D | Good Substrings | You've got string $s$, consisting of small English letters. Some of the English letters are good, the rest are bad.
A substring $s[l...r]$ ($1 ≤ l ≤ r ≤ |s|$) of string $s = s_{1}s_{2}...s_{|s|}$ (where $|s|$ is the length of string $s$) is string $ s_{l}s_{l + 1}...s_{r}$.
The substring $s[l...r]$ is good, if among ... | At first, build a trie containing all suffixes of given string (this structure is also called explicit suffix tree). Let's iterate over all substrings in order of indexes' increasing, i. e. first $[1...1],$ then $[1...2], [1...3], ..., [1...n], [2...2], [2...3], ..., [2...n], ...$ Note, that moving from a substring to ... | [
"data structures",
"strings"
] | 1,800 | null |
271 | E | Three Horses | There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with $a$ on the top ... | It could be proved, that a card $(x, y)$ $(x < y)$ can be transformed to any card $(1, 1 + k \cdot d)$, where $d$ is the maximal odd divisor of $y - x$, and $k$ is just any positive integer. So every $(a_{i} - 1)$ must be divisible by $d$, i. e. $d$ is a divisor of $gcd(a_{1} - 1, ..., a_{n} - 1)$, and we can just iter... | [
"constructive algorithms",
"math",
"number theory"
] | 2,200 | null |
272 | A | Dima and Friends | Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t... | We will bruteforce number of fingers that will be show Dima, then if total sum of fingers = 1 modulo (n+1), Dima will clean the room. So we should increase answer if the remaining part after division by (n+1) is not 1. | [
"implementation",
"math"
] | 1,000 | null |
272 | B | Dima and Sequence | Dima got into number sequences. Now he's got sequence $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Also, Dima has got a function $f(x)$, which can be defined with the following recurrence:
- $f(0) = 0$;
- $f(2·x) = f(x)$;
- $f(2·x + 1) = f(x) + 1$.
Dima wonders, how many pairs of indexes $(i, j)$ ... | First of all - f(i) is number of ones in binary presentation of number. We will repair all numbers to functions of them. Now we have to find number of pairs of equal numbers. Lets Q[i] - number of numbers with i bits, the answer will be sum of values Q[i]*(Q[i]-1)/2 for all i. | [
"implementation",
"math"
] | 1,400 | null |
272 | C | Dima and Staircase | Dima's got a staircase that consists of $n$ stairs. The first stair is at height $a_{1}$, the second one is at $a_{2}$, the last one is at $a_{n}$ ($1 ≤ a_{1} ≤ a_{2} ≤ ... ≤ a_{n}$).
Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The $i$-th box has width $w_{... | Lets L will be the answer after last block, last block was (w1, h1), next block is (w2, h2). Next answer will be max(L+h1, A[w2]), where A - given array. At the beggining we can suppose that L = 0, w1 = 0, h1 = 0. | [
"data structures",
"implementation"
] | 1,500 | null |
272 | D | Dima and Two Sequences | Little Dima has two sequences of points with integer coordinates: sequence $(a_{1}, 1), (a_{2}, 2), ..., (a_{n}, n)$ and sequence $(b_{1}, 1), (b_{2}, 2), ..., (b_{n}, n)$.
Now Dima wants to count the number of distinct sequences of points of length $2·n$ that can be assembled from these sequences, such that the $x$-c... | Not hard to understand that answer will be (number of numbers with first coordinate = 1)! * (number of numbers with first coordinate = 2)! * ... * (number of numbers with first coordinate = 10^9)!/(2^(number of such i = 1..n, that Ai=Bi)). The only problem was to divide number with non prime modulo, it can be easely do... | [
"combinatorics",
"math",
"sortings"
] | 1,600 | null |
272 | E | Dima and Horses | Dima came to the horse land. There are $n$ horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.
Right now the horse land is going through an election campaign. So the hor... | Not hard to understand that we have undirected graph. Lets color all vetexes in one color. Then we will find some vertex that is incorrect. We will change color of this vertex, and repeat our search, while it is possible. After every move number of bad edges will be decrease by 1 or 2, so our cycle will end in not more... | [
"combinatorics",
"constructive algorithms",
"graphs"
] | 2,200 | null |
273 | D | Dima and Figure | Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures.
A piece of squared paper of size $n × m$ is represented by a table, consisting of $n$ rows and $m$ columns. All squares are white on blank squared paper. Dima defines a pictur... | Good picture is connected figure that saticfy next condition: most left coordinates in every row of figure vere we have some cells will be almost-ternary, we have the same situation with right side, but here we have another sign. So it is not hard to write dp[i][j1][j2][m1][m2] numbr of figures printed of field size i*... | [
"dp"
] | 2,400 | null |
274 | A | k-Multiple Free Set | A $k$-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by $k$. That is, there are no two integers $x$ and $y$ $(x < y)$ from the set, such that $y = x·k$.
You're given a set of $n$ distinct positive integers. Your task is to find the size of it'... | Consider an integer $x$ which is divisible by $k$. At most one of the integers $x$ and $x / k$ can appear in the maximum $k$-multiple free subset. Also for any integer $y$ at most one of the numbers $y$ and $yk$ appears in the answer. If you look like this you can see the input as chains of numbers so that for each cha... | [
"binary search",
"greedy",
"sortings"
] | 1,500 | null |
274 | B | Zero Tree | A tree is a graph with $n$ vertices and exactly $n - 1$ edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree $T$ is a tree with both vertices and edges as subsets of vertices and edges of $T$.
You're gi... | In the problem statement vertex $1$ is not mentioned as root of the tree. But it seems if we make it the root of the tree we can figure out the solution easier. For the leaves of the tree we can see the least number of steps needed to make each of them equal to zero. Consider a vertex which all its children are leaves.... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,800 | null |
274 | C | The Last Hole! | Luyi has $n$ circles on the plane. The $i$-th circle is centered at $(x_{i}, y_{i})$. At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time $t (t > 0)$ is equal to $t$. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consist... | In the solution we will try to find the position of all points which are the last moments in holes. Here we claim that each minimal potential hole is one of these two forms: For each three centers that form an acute triangle it's obvious that they form a potential hole. The last point in this hole would be the in trian... | [
"brute force",
"geometry"
] | 2,600 | null |
274 | D | Lovely Matrix | Lenny had an $n × m$ matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.
One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased som... | The naive solution for this problem would be to make a graph were each vertex represents a column of the grid. Then for each two not erased integers $x$ and $y$ in the same row where $x < y$ we can add an edge from the column of $x$ to the column of $y$ in our graph. Then topological sorting on the built graph would gi... | [
"dfs and similar",
"graphs",
"greedy",
"sortings"
] | 2,200 | null |
274 | E | Mirror Room | Imagine an $n × m$ grid with some blocked cells. The top left cell in the grid has coordinates $(1, 1)$ and the bottom right cell has coordinates $(n, m)$. There are $k$ blocked cells in the grid and others are empty. You flash a laser beam from the center of an empty cell $(x_{s}, y_{s})$ in one of the diagonal direct... | The blocked cells can make lots of complicated patterns. So it's obvious that the solution in includes simulating the path the laser beam goes. But the dimensions of the gird are large and the beam might travel a long path before entering a loop. So naive simulation will surely time out (See note!). It's kind of obviou... | [
"data structures",
"implementation"
] | 3,000 | null |
275 | A | Lights Out | Lenny is playing a game on a $3 × 3$ grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be sw... | For each light you should count the number of times it's been toggled. Consider a light is toggled $k$ times. If $k$ is even then the final state of the light is 'on' otherwise it's 'off'. The implementation would be easy. You may look at the accepted solutions as reference. | [
"implementation"
] | 900 | null |
275 | B | Convex Shape | Consider an $n × m$ grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid \underline{convex} if one can walk from \textbf{any} black cell to \textbf{any another} black cell using a path of side-adjacent black cells changing his dire... | Consider a pair of black cells. There exist at most two different valid paths we can take between these two cells. The naive solution would be to check the existence of at least one of these paths for each pair of black cells. There are $O(n^{2}m^{2})$ such pairs and each pair can be checked in $O(n + m)$. So the time ... | [
"constructive algorithms",
"implementation"
] | 1,700 | null |
276 | A | Lunch Rush | Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly $k$ time units for the lunch break.
The Rabbits have a list of $n$ restaurants to lunch in: the $i$-th restaurant is characterized by two integers $f_{i}$ and $t_{i}$. Value $t_{i}$ shows the time the ... | Let's look at all restraunts, where Rabbits can have their lunch. Let's calculate the answer for all restraunts and choose the maximulm value among of them. We need to use formula descrbed in problem statement to calculate the answer for some particular restraunt. Time complexity of this solution is $O(N)$. | [
"implementation"
] | 900 | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <memory.h>
#include <ctime>
using namespace std;
#define AB... |
276 | B | Little Girl and Game | The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string $s$, consisting of lowercase English letters. They play a game that is described by the following rules:
- The players move in turns; In one move the player can remove an arbitrary letter from string $s$.
- If the pla... | Let's calculate the number of letters with odd number of occurrences in $s$. Let this value be equal to $k$. If $k = 0$, then first player can win immediately: he can easily build palindrome, placing equal letters in different sides of resulting string (he always can do it, because total number of all letters is even).... | [
"games",
"greedy"
] | 1,300 | #include <iostream>
#include <string>
#include <string.h>
using namespace std;
string s;
int cnt[30];
int main()
{
cin>>s;
for (int i=0; i<s.size(); ++i)
cnt[s[i]-'a']++;
int odd=0;
for (int i=0; i<26; ++i)
if (cnt[i]&1)
odd++... |
276 | C | Little Girl and Maximum Sum | The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)... | Lets calculate for each cell of the initial array the number of queries that cover this cell. It's claimed, that we should associate the cell with bigger value to the cell with bigger value in initial array. More formally: suppose $b$ is an array, in $i - th$ cell of which is written the number of queries that cover $i... | [
"data structures",
"greedy",
"implementation",
"sortings"
] | 1,500 | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <memory.h>
#include <ctime>
using namespace std;
#define AB... |
276 | D | Little Girl and Maximum XOR | A little girl loves problems on bitwise operations very much. Here's one of them.
You are given two integers $l$ and $r$. Let's consider the values of $a\oplus b$ for all pairs of integers $a$ and $b$ $(l ≤ a ≤ b ≤ r)$. Your task is to find the maximum value among all considered ones.
Expression $x\oplus y$ means app... | To be honest, I am surprised that problem D had so many accepted solution during the contest. The author's solution uses dynamic programming. In this editorial I'll explain this solution. First of all we should convert $L$ and $R$ to the binary numeral system. Now we can solve our problem with dynamic programming, usin... | [
"bitmasks",
"dp",
"greedy",
"implementation",
"math"
] | 1,700 | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <memory.h>
#include <ctime>
using namespace std;
#define AB... |
276 | E | Little Girl and Problem on Trees | A little girl loves problems on trees very much. Here's one of them.
A tree is an undirected connected graph, not containing cycles. The degree of node $x$ in the tree is the number of nodes $y$ of the tree, such that each of them is connected with node $x$ by some edge of the tree.
Let's consider a tree that consist... | One can see, that our tree is a set of chains, each of which starts in the root. First of all we need to decompose our tree in chains using, for example, depth first search. For each vertex we should find out it's depth and number of chain, which contain this vertex. For each chain we'll use some data structure, which ... | [
"data structures",
"graphs",
"trees"
] | 2,100 | #include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <memory.h>
#include <stdio.h>
#include <ctime>
#include <cmath>
using namespace std;
char ch_ch_ch[1<<20];
inline int g... |
277 | A | Learning Languages | The "BerCorp" company has got $n$ employees. These employees can use $m$ approved official languages for the formal correspondence. The languages are numbered with integers from $1$ to $m$. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official ... | Build bipartite graph with $n$ nodes for employees and $m$ nodes for languages. If an employee initially knows a language, than there will be an edge between corresponding nodes. Now the problem is simple: add the minimal number of edges in such a way, that all the $n$ employees will be in the same connected component.... | [
"dfs and similar",
"dsu"
] | 1,400 | null |
277 | B | Set of Points | Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of $n$ points with the convexity of exactly $m$. Your set of points should not contain three points that lie on a straight line. | For $m = 3, n = 5$ and $m = 3, n = 6$ there is no solution. Let's learn how to construct the solution for $n = 2m$, where $m \ge 5$ and is odd. Set up $m$ points on a circle of sufficiently large radius. This will be the inner polygon. The outer polygon will be the inner polygon multiplied by 2. More precisely ($1 \... | [
"constructive algorithms",
"geometry"
] | 2,300 | null |
277 | C | Game | Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid l... | At first, notice that horizontal and vertical cuts are independent. Consider a single horizontal line. It contains $m$ unit segments. And in any game state it's always possible to decrease the number of uncut units as the player wants. Imagine, that she starts growing a segment from a border, increasing it's length by ... | [
"games",
"implementation"
] | 2,400 | null |
277 | D | Google Code Jam | Many of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one wi... | Suppose we have fixed set of inputs that we have to solve. Let's learn how to determine the optimal order. Obviously, Small inputs (and Large inputs with $probFail = 0$) won't fail in any case. It means that our penalty time is no less than submission time of last such ``safe'' inputs. So we will solve such inputs befo... | [
"dp",
"probabilities"
] | 2,800 | null |
277 | E | Binary Tree on Plane | A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.
A root tree is binary if each node has at most two outgoing arcs.
When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from $u$ ... | If there is no "binary" restriction, the solution is simple greedy. Each node of the tree (except the root) must have exactly 1 parent, and each node could be parent for any number of nodes. Let's assign for each node $i$ (except the root) such a node $p_{i}$ as a parent, so that $y_{pi} > y_{i}$ and distance between $... | [
"flows",
"trees"
] | 2,400 | null |
278 | B | New Problem | Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title \underline{original} if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of $n$ last problems — the strings, consisting of lowercase English ... | The total number of different strings of 2 letters is $26^{2} = 676$, but the total length of the input strings is no more than $600$. It means that the length of answer is no more than 2. So just check all the strings of length 1 and 2. | [
"brute force",
"strings"
] | 1,500 | null |
279 | A | Point on Spiral | Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: \textbf{$[(0, 0), (1, 0)]$, $[(1, 0), (1, 1)]$, $[(1, 1), ( - 1, 1)]$, $[( - 1, 1), ( - 1, - 1)]$, $[( - 1, - 1), (2, - 1)]$, $[(2, - 1), (2, 2)]... | Since constraints are small, you can just simulate the whole process, but I'll explain an $O(1)$ solution. Let's look at the path Now it's easy to see that the plane can be divided into four parts And then we can calculate answer for each part separately, just be careful with borders. For example, for the right part th... | [
"brute force",
"geometry",
"implementation"
] | 1,400 | #include "bits/stdc++.h"
using namespace std;
int main() {
int x, y;
cin >> x >> y;
if (x == 0 && y == 0) {
cout << 0 << '\n';
} else if (-x + 1 < y && y <= x) {
cout << 1 + (x - 1) * 4 << '\n';
} else if (-y <= x && x < y) {
cout << 2 + (y - 1) * 4 << '\n';
} else if (... |
279 | B | Books | When Valera has got some free time, he goes to the library to read some books. Today he's got $t$ free minutes to read. That's why Valera took $n$ books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to $n$. Valera needs $a_{i}$ minutes t... | The problem can be written in the following way: for each index $i$ denote $r_i$ as the largest index such that $a_i + \ldots + a_{r_i} \leqslant t$. The problem is to find $max(r_i - i + 1)$. One can see that $r_i$ are nondecreasing, so the problem can be solved with two pointers: iterate over $i$ and keep a pointer t... | [
"binary search",
"brute force",
"implementation",
"two pointers"
] | 1,400 | #include "bits/stdc++.h"
using namespace std;
int main() {
int n, t;
cin >> n >> t;
vector<int> a(n);
for (int& k : a)
cin >> k;
int r = 0;
int sm = 0;
int ans = 0;
for (int i = 0; i < n; ++i) {
while (r < n && sm + a[r] <= t) {
sm += a[r];
++r;... |
279 | C | Ladder | You've got an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Also, you've got $m$ queries, the $i$-th query is described by two integers $l_{i}, r_{i}$. Numbers $l_{i}, r_{i}$ define a subsegment of the original array, that is, the sequence of numbers $a_{li}, a_{li + 1}, a_{li + 2}, ..., a_{ri}$. For ea... | Let's calculate two arrays before answering queries. $tol[i]$ is the smallest index such that $[b_{tol[i]},\, \ldots,\, b_{i}]$ is nonincreasing, and $tor[i]$ is the largest index such that $[b_{i},\, \ldots,\, b_{tor[i]}]$ is nondecreasing. Then for each query we can take $tor[l]$ and $tol[r]$ and compare them. The an... | [
"dp",
"implementation",
"two pointers"
] | 1,700 | #include "bits/stdc++.h"
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int& k : a)
cin >> k;
vector<int> tor(n), tol(n);
iota(tol.begin(), tol.end(), 0);
iota(tor.begin(), tor.end(), 0);
tol[0] = 0;
for (int i = 1; i < n; ++i)
i... |
279 | D | The Minimum Number of Variables | You've got a positive integer sequence $a_{1}, a_{2}, ..., a_{n}$. All numbers in the sequence are distinct. Let's fix the set of variables $b_{1}, b_{2}, ..., b_{m}$. Initially each variable $b_{i}$ $(1 ≤ i ≤ m)$ contains the value of zero. Consider the following sequence, consisting of $n$ operations.
The first oper... | You can notice that when we want to perform some operation, we are only interested in a subset of current values of variables (including zeros). So let's create $dp[i][mask] = bool$, which is $1$ if we can perform first $i$ operations and end up with the values from $mask$. Here $k$-bit in the mask corresponds to the v... | [
"bitmasks",
"dp"
] | 2,200 | #include "bits/stdc++.h"
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int& k : a)
cin >> k;
auto vals = a;
vals.push_back(0);
sort(vals.begin(), vals.end());
vals.erase(unique(vals.begin(), vals.end()), vals.end());
vector<int> pos(n);
for... |
279 | E | Beautiful Decomposition | Valera considers a number beautiful, if it equals $2^{k}$ or -$2^{k}$ for some integer $k$ $(k ≥ 0)$. Recently, the math teacher asked Valera to represent number $n$ as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible.
Help Valera and fi... | First of all it's easy to notice that we will use each power of $2$ at most once. Let's look at the highest bit in the current number, suppose it's $2^k$. Since the sum of all powers of $2$ below $k$ is less than $2^k$, we will have to add at least one power of two $2^x$ with $x \geqslant k$. One can see that adding $2... | [
"dp",
"games",
"greedy",
"number theory"
] | 1,900 | #include "bits/stdc++.h"
using namespace std;
int main() {
string n;
cin >> n;
string m = n;
{
for (char& c : m) {
c ^= '1' ^ '0';
}
int ind = m.size() - 1;
while (ind >= 0 && m[ind] == '1') {
m[ind] = '0';
--ind;
}
if... |
280 | A | Rectangle Puzzle | You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the $Ox$ axis, equals $w$, the length of the side... | It may always be a good idea to try a simplified version before the situation gets into complicated. In this problem, a simplified version you might to be noticed is the square case. So here it is. you can easily see the area can be calculated by $$S - 4 \times T$$ Here S is the area of the large square, and T is the a... | [
"geometry"
] | 2,000 | null |
280 | B | Maximum Xor Secondary | Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers $x_{1}, x_{2}, ..., x_{k}$ $(k > 1)$ is such maximum element $x_{j}$, that the following inequality holds: $x_{j}\not\to\operatorname*{m}_{i\geq k}^{k}x_{i}$.
The lucky number of the sequen... | The intervals meaning can only be reflected on its maximum element and second maximum element, so apparently, there must be a lot of meaningless interval which we needn't check them at all. But how can we skip them? Maintain a monotone-decreasing-stack can help us. While a new element came into the view, pop the top el... | [
"data structures",
"implementation",
"two pointers"
] | 1,800 | null |
280 | C | Game on Tree | Momiji has got a rooted tree, consisting of $n$ nodes. The tree nodes are numbered by integers from $1$ to $n$. The root has number $1$. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by $v$) and removes all ... | The answer is $$\sum_{i=1}^n \frac{1}{Depth[i]}$$ Here we denoted the $Depth[root] = 0$. And why it works? Well, let us observe each vertex independently, when one vertex has been removed, you need either to remove it directly, or remove one of its ancestors. All these choices are equiprobable, so the probability of di... | [
"implementation",
"math",
"probabilities",
"trees"
] | 2,200 | null |
280 | D | k-Maximum Subsequence Sum | Consider integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run queries of two types:
- The query format is "$0$ $i$ $val$". In reply to this query you should make the following assignment: $a_{i} = val$.
- The query format is "$1$ $l$ $r$ $k$". In reply to this query you should print the maximum sum of at most $... | Consider the static problem, Apparently, we can use a dynamic programming to solve it. $f_{0}[i][j]$: the j-MSS in [0, i]. $f_{1}[i][j]$: the quasi-j-MSS in [0, i], which the item ${A_{i}}$ must be selected. The state transition is enumerating whether the $i$th element is selected or not. That's easy for a clever guy s... | [
"data structures",
"flows",
"graphs",
"implementation"
] | 2,800 | /*
Author: elfness@UESTC
*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<vector>
#include<string>
using namespace std;
typedef long long LL;
const int MAX = 105000;
/**
* Segment tree
*/
struct Seg
{
int l, r;
int maxLeftValue, ... |
280 | E | Sequence Transformation | You've got a non-decreasing sequence $x_{1}, x_{2}, ..., x_{n}$ $(1 ≤ x_{1} ≤ x_{2} ≤ ... ≤ x_{n} ≤ q)$. You've also got two integers $a$ and $b$ $(a ≤ b; a·(n - 1) < q)$.
Your task is to transform sequence $x_{1}, x_{2}, ..., x_{n}$ into some sequence $y_{1}, y_{2}, ..., y_{n}$ $(1 ≤ y_{i} ≤ q; a ≤ y_{i + 1} - y_{i} ... | Let $dp[i][j]$=(the minimum transformation price to the moment if $y_{1}... y_{i}$ have been determined and $y_{i} = j$). It's easy to find that: $dp[1][p] = (p - x_{1})^{2}$ $f[i][p] = min(dp[i - 1][q] | p - b \le q \le p - a)$ $dp[i][p] = (p - x_{i})^{2} + f[i][p]$ Solutions using this idea straight can't pass be... | [
"brute force",
"data structures",
"dp",
"implementation",
"math"
] | 3,000 | null |
281 | A | Word Capitalization | Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged. | As the first problem in the problemset, it intended to be simple so that any one could solve it. Just implement what the problem said under your favorite language. | [
"implementation",
"strings"
] | 800 | null |
281 | B | Nearest Fraction | You are given three positive integers $x, y, n$. Your task is to find the nearest fraction to fraction $\scriptstyle{\frac{\pi}{y}}$ whose denominator is no more than $n$.
Formally, you should find such pair of integers $a, b$ $(1 ≤ b ≤ n; 0 ≤ a)$ that the value $\left|{\frac{x}{y}}-{\frac{a}{b}}\right|$ is as minimal... | This problem can be solved by a straight forward method since we are at Div II, simply enumerate all possible denominator, and calculate the nearest fraction for each denominator. As you would expect, we can do better. Actually this is the limit_denominator() method implemented by the Python fractions module. Since it ... | [
"brute force",
"implementation",
"two pointers"
] | 1,700 | null |
282 | A | Bit++ | The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called $x$. Also, there are two operations:
- Operation ++ increases the value of variable $x$ by 1.
- Operation -- decreases the value of variable $x$ by 1... | Just use a simple loop. (Take a look at the Python code) | [
"implementation"
] | 800 | #include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <asser... |
282 | B | Painting Eggs | The Bitlandians are quite weird people. They have very peculiar customs.
As is customary, Uncle J. wants to have $n$ eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.
The kids are excited because just as is customary, they're going to be paid for the job!
Overall uncle J. ... | This one can be solved by a greedy algorithm. Start from the 1st egg and each time give the egg to A if and only if giving it to A doesn't make the difference > 500, otherwise give it to G. To prove the correctness, one can use induction. The base case is trivial. Suppose that we've assigned the first $n - 1$ eggs such... | [
"greedy",
"math"
] | 1,500 | #include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <asser... |
282 | C | XOR and OR | The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.
A Bitlandish string is a string made only of characters "0" and "1".
BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish ... | First of all, check the length of the two strings to be equal. Then with a little try and guess, you can find out that the zero string (00...0) can't be converted to anything else and nothing else can be converted to zero. All other conversions are possible. | [
"constructive algorithms",
"implementation",
"math"
] | 1,500 | #include <iostream>
#include <string>
using namespace std;
int main(){
string a,b;
cin>>a>>b;
bool ans_a = false;
bool ans_b = false;
if(a.size()==b.size()){
for(int i=0;i<a.size();i++){
if(a[i]=='1'){
ans_a=... |
282 | D | Yet Another Number Game | Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!
Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games.
BitLGM and Bi... | For n=1, everything is clear. If $a_{1} = 0$ then BitAryo wins, otherwise BitLGM is the winner. For n=2: define win[i][j] = (Whether i,j is a Winning position). It's easy to calculate win[i][j] for all i and j, using a loop (Checking all possible moves). This leads us to an O($n^{3}$) solution. For n=3: Everything is s... | [
"dp",
"games"
] | 2,100 | //In the name of God
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN=310;
const int MGO=305;
bool wins2[MAXN][MAXN];
void calc2()
{
for(int i=0;i<MGO;++i)
for(int j=max(i,1);j<MGO;++j)
{
for(int I=0;I<i;++I)
if(wins2[I][j]==false)
{wins2[i][j]=true; break;}
for(int J... |
282 | E | Sausage Maximization | The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness i... | Can be solved using a trie in O(n log (max{$a_{i}$})). Start with a prefix of size n, and decrease the size of prefix in each step. For each new prefix calculate the XOR of elements in that prefix and add the XOR of the newly available suffix (which does not coincide with the new prefix) to the trie, then query the tri... | [
"bitmasks",
"data structures",
"trees"
] | 2,200 | //In the name of God
#include <iostream>
#include <deque>
using namespace std;
const int MAXN=1e6+1e3;
#define num long long
num all[MAXN];
struct node
{
node *child[2];
node()
{
child[0]=child[1]=NULL;
}
};
node *root;
deque<short> binary(long long x)
{
deque<short> ans;
while(x)
{
ans.pu... |
283 | A | Cows and Sequence | Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform $n$ operations. Each operation is one of the following:
- Add the integer $x_{i}$ to the first $a_{i}$ elements of the sequence.
- Append an integer $k_{i}$ to the end of t... | Consider the problem with only queries 1 and 2. Then the problem is easy in $O(n)$: keep track of the number of terms and the sum, and you can handle each query in O(1). But with query 3 we need to also be able to find the last term of the sequence at any given time. To do this, we keep track of the sequence $d_{i} = a... | [
"constructive algorithms",
"data structures",
"implementation"
] | 1,600 | null |
283 | B | Cow Program | Farmer John has just given the cows a program to play with! The program contains two integer variables, $x$ and $y$, and performs the following operations on a sequence $a_{1}, a_{2}, ..., a_{n}$ of positive integers:
- Initially, $x = 1$ and $y = 0$. If, after any step, $x ≤ 0$ or $x > n$, the program immediately ter... | First, suppose we only have the sequence $a_{2}, a_{3}, \dots a_{n}.$ We note that the current state is only determined by the location and the direction we are facing, so there are only $2 \cdot (n - 1)$ states total. Then, we can use DFS with memorization to find the distance traveled from each state, or $- 1$ if a ... | [
"dfs and similar",
"dp",
"graphs"
] | 1,700 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.