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 ⌀ |
|---|---|---|---|---|---|---|---|
65 | C | Harry Potter and the Golden Snitch | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at... | Check for each segment in the polyline if Harry can catch the snitch in it. Note that since $v_{p} \ge v_{s}$, if Harry can catch the snitch at some moment of time, he can catch it at any later moment. He can just follow snitch along its trajectory. So use binary search in each segment. About problems with EPS that p... | [
"binary search",
"geometry"
] | 2,100 | null |
65 | D | Harry Potter and the Sorting Hat | As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the nam... | Let $S_{i}$ be a set of all possible assignments of the first $i$ students to the houses, that is a set of tuples $(a_{1}, a_{2}, a_{3}, a_{4})$, where $a_{1}$ is a number of students sent to Gryffindor, $a_{2}$ - to Ravenclaw, etc. It's intuitively clear that these sets will not be large. So you can get $S_{None}$ fro... | [
"brute force",
"dfs and similar",
"hashing"
] | 2,200 | null |
65 | E | Harry Potter and Moving Staircases | Harry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read "The Invisibility Cloaks, and Everything about Them", as well as six volumes of "The Encyclopedia of Quick... | Consider a graph with floors as vertices and staircases as edges. It is clear that Harry can visit the whole connected component in which he is currently located. Every edge can be used to reach a new vertex for not more than two times. If a connected component contains n vertices and m edges, only n - 1 edges are used... | [
"dfs and similar",
"implementation"
] | 2,900 | null |
66 | A | Petya and Java | Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | In this problem you should answer to 4 questions: 1) Can we use type byte to store N? 2) Can we use type short to store N? 3) Can we use type int to store N? 4) Can we use type long to store N? We should check these conditions in the given order. If all these conditions are wrong, the answer is BigInteger. The simplest... | [
"implementation",
"strings"
] | 1,300 | null |
66 | B | Petya and Countryside | Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle $1 × n$ in size, when viewed from above. This rectangle is divided into $n$ equal square sections. The garden is very unusual as each of the square sections possesses its own fix... | Try to check all possibilities for creation artificial rain and calculate how many sections contain water. The maximal answer from all these possibilities is the answer for the problem. To calculate the answer for the given position we should check how many sections are to the left and to the right of the given section... | [
"brute force",
"implementation"
] | 1,100 | null |
66 | D | Petya and His Friends | Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to $n$.
Let us remind you the definition of the greatest common divisor: $GCD(a_{1}, ..., a_{k}) = d$, where $d$ represents such a maximal positive number that each $a_{i}$... | Consider N distinct prime numbers: p1, p2, \dots , pn. Let A=p1*p2* \dots *pn. Then, easy to see, that the numbers A/p1, A/p2, \dots , A/pn can be considered as the answer. The special case is when N=2. In this case there is no answer. We can see that this solution needs long arithmetic. If we choose first n prime nu... | [
"constructive algorithms",
"math",
"number theory"
] | 1,700 | null |
66 | E | Petya and Post | Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then ... | First of all we divide our problem into 2 parts: consider stations from which we can start if we are moving in the clockwise direction and stations from which we can start if we are moving in the counterclockwise direction. Obviously, if we know the solution of one of these problems, we know the solution of another pro... | [
"data structures",
"dp"
] | 2,000 | null |
67 | A | Partial Teacher | A teacher decides to give toffees to his students. He asks $n$ students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.
He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same mar... | Let the student at position 'x' receives 't' toffees Initially t=1 and temp=1 Now move towards RIGHT till you encounter a 'R' or end of string , if in the path 'L' is encountered increment t by 1.Following code performs the same : Now if temp is greater than t ; t is initialised as temp and temp as 1. Now move towards ... | [
"dp",
"graphs",
"greedy",
"implementation"
] | 1,800 | #include<iostream>
using namespace std;
int main()
{
int n,ans[1000],temp,i,j;
fill(ans,ans+1000,0);
char s[1000];
cin>>n;
cin>>s;
for(i=0;i<n;i++)
{
ans[i]=1;
temp=1;
for(j=i;j<n;j++)
{
if(s[j]=='R')
break;
else if(s[j]... |
67 | B | Restoration of the Permutation | Let $A = {a_{1}, a_{2}, ..., a_{n}}$ be any permutation of the first $n$ natural numbers ${1, 2, ..., n}$. You are given a positive integer $k$ and another sequence $B = {b_{1}, b_{2}, ..., b_{n}}$, where $b_{i}$ is the number of elements $a_{j}$ in $A$ to the left of the element $a_{t} = i$ such that $a_{j} ≥ (i + k)$... | For k=1, the given sequence is called Table of Inversions. We notice that if i>j, relative position of i effects the b_j while placing of j does not effect b_i. For this value of k, and sequnce {b_1, b_2, ..., b_n}, we first place n in the permutation. Then we chose (n-1) and check whether n-1 is 0 or 1. If its 0, It l... | [
"greedy"
] | 1,800 | #include <stdio.h>
int main()
{
int n,k,a[1002],b[1002],i,j,temp;
scanf("%d%d",&n;,&k;);
for(i=1;i<=n;i++)
{
scanf("%d",&b;[i]);
}
for(i=k;i>=1;i--)
a[i] = n-i+1;
for(i=n-k;i>=1;i--)
{
temp = b[i];
for(j=n-i;j>=1 && temp>0;j--)
{
if(a[j]>=i+k)
temp--;
... |
67 | C | Sequence of Balls | You are given a sequence of balls $A$ by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, $B$ that suits you better. So, you allow yourself four operations:
- You can insert any ball with any label into the sequence at any p... | This is problem is an extension to the problem of String Edit Distance where you have to find the minimum cost of converting one string to another using only the following operations: 1) insert 2) delete 3) modify This problem has an extra operation of exchanging adjacent characters. It is similar to the Damerau Levens... | [
"dp"
] | 2,600 | #include<stdio.h>
#include<string.h>
#include <iostream>
#define MAX 5010
using namespace std;
int main()
{
char A[MAX],B[MAX];
int length_A,length_B,INF,wd,wi,ws,wc,H[MAX+2][MAX+2],i,j,DA[MAX+10],d,DB,i1,j1,C,min[4],k,testcase;
//scanf("%d%d%d%d",&wi;,&wd;,&wc;,&ws;);
//scanf("%s%s",A,B);
//printf("%s
%s
",A... |
67 | D | Optical Experiment | Professor Phunsuk Wangdu has performed some experiments on rays. The setup for $n$ rays is as follows.
There is a rectangular box having exactly $n$ holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from ... | For a given set of n rays, we can prepare the graph, having exactly n nodes. The n nodes represent the rays, numbered from 1 to n. There is an edge between the ith and jth node, if ith ray intersect the jth ray. A Clique of a graph is a complete subgraph. For this graph, the problem requires to find the Clique number, ... | [
"binary search",
"data structures",
"dp"
] | 1,900 | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
void find_lis(vector<int> &a;, vector<int> &b;)
{
vector<int> p(a.size());
int u, v;
b.push_back(0);
for (int i = 1; i < a.size(); i++)
{
if (a[b.back()] > a[i])
{
p[i] = b.back();
b.push_back(i);
co... |
67 | E | Save the City! | In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away fro... | The problem is to find out the total number of points on the segment AB such that the whole polygon(compound) is watchable from it. It can be observed that a straight line segment XY is fully visible from another straight line segment PQ if the point X is visible from points P and Q, and point Y is also visible from po... | [
"geometry"
] | 2,500 | #include <iostream>
#include <stack>
#include <stdlib.h>
#include <math.h>
using namespace std;
#define EPS 1E-9
struct Point
{
long double x,y;
};
long double Left, Right;
int up;
int RST(Point r,Point s,Point t)
{
long double val = t.x*(r.y-s.y) + t.y*(s.x - r.x) + r.x*s.y - r.y*s.x;
if(val... |
69 | A | Young Physicist | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | In this task all you had to do was to make sure that the sum of all \Sigma xi is 0, the sum of all \Sigma yi is 0 and that the sum of all \Sigma zi - 0 . We have not written that condition evidently in order that participants will have a chance to break a solution. | [
"implementation",
"math"
] | 1,000 | null |
69 | B | Bets | In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.
To begin with friends... | In this problem, in fact, you should find a winner at every section. For each section, you must do a full search of all competitors to find a competitor with a minimum section time, which ran that section. Asymptotic of the solution is O(nm). | [
"greedy",
"implementation"
] | 1,200 | null |
69 | C | Game | In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle... | In this task, you had to update the collection of artifacts, which belong to Kostya's friends, after each purchase . You had to set a matrix c[i][j] - number of the j-th basic artifact that is required in order to collect the i-th component artifact. Further, one can make a matrix of composite artifacts, where a[i][j] ... | [
"implementation"
] | 2,000 | null |
69 | D | Dot | Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules:
- On the checkered paper a... | This game is over, because except for a finite number (2) of reflections about the line y = x,the coordinates are changed to non-negative integer (and at least one coordinate is changed to a positive number). Algorithm for solving this problem is DFS / BFS (states) where the state is a pair of coordinates, and two logi... | [
"dp",
"games"
] | 1,900 | null |
69 | E | Subsegments | Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in $O(\log n)$, which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must fi... | To solve this problem you have to do a "move" subsegment and know : 1. The set B of numbers, meeting once, with the function of extracting the maximum for O (logN) 2.The set of numbers appearing on this subsegments with keeping the number of times,that this number is found on this subsegments, with function of verifyin... | [
"data structures",
"implementation"
] | 1,800 | null |
70 | A | Cookies | Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square $k × k$ in size, divided into blocks $1 × 1$ in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie $k$ in siz... | Let's define a half-filled square of size $k$ as an empty square of size $k$ after adding a cookie of the biggest posible size. Notice, that if we add a cookie of the biggest possible size into the half-filled square of size $2^{n} \times 2^{n}$, it will be divided into three half-filled squares of size $2^{None} \t... | [
"math"
] | 1,300 | null |
70 | B | Text Messaging | Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing $n$ characters (which is the size of one text message). Thus, whole sentences and words get split!
Fangy did not lik... | It's obviously, that sentences should be added into the SMS greedily. Really, if we put the sentence into the new message, when it's possible to add into previous, the number of messages may be increased. The only thing you should pay attention is correct processing whitespaces between the sentences. | [
"expression parsing",
"greedy",
"strings"
] | 1,600 | null |
70 | C | Lucky Tickets | In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by $a$ and the ticket number — by $b$, then a ticket is described by the ordered pair of numbers $(a, b)$.
The walruses believe that ... | Let's learn how to solve more easy problem: it's need to count a number of lucky tickets with $1 \le a \le x$ and $1 \le b \le y$. Rewrite sentence $a * b = rev(a) * rev(b)$ as $a / rev(a) = rev(b) / b$. Brute all $a$ and count a number of irreducible fractions $a / rev(a)$ using, for example, map from STL. Now... | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | 2,200 | null |
70 | D | Professor's task | Once a walrus professor Plato asked his programming students to perform the following practical task.
The students had to implement such a data structure that would support a convex hull on some set of points $S$. The input to the program had $q$ queries of two types:
1. Add a point with coordinates $(x, y)$ into the... | Notice, that any point from the triangle based on first three points will be into the area bounded with the convex hull in the future. Let choose one of these points ad set it as the origin. All points of convex hull will keep in structure like map in C++, where the key is the angle of vector from the origin to a point... | [
"data structures",
"geometry"
] | 2,700 | null |
70 | E | Information Reform | Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.
The... | Notice next facts. If we have the fixed state of some regional centers then for every city will be assigned the nearest regional center. The regional center of some city will be assigned for all cities between this city and it's regional center. It means that tree should be divided into some subtrees. Also define $d[0]... | [
"dp",
"implementation",
"trees"
] | 2,700 | null |
71 | A | Way Too Long Words | Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is \textbf{strictly more} than $10$ characters. All too long words should be replaced with a special abbreviation.
This abbreviation ... | In this problem you can just do what is written in the statement. Let read all words. For each of them compute its length $L$, its the first and the last letter. If $L > 10$, output word without any changes, otherwise output the first letter, next $L - 2$ and finally the last letter. | [
"strings"
] | 800 | null |
71 | B | Progress Bar | A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as $n$ squares, located in line. To add clarity, let's number them with positive integers from $1$ to $n$ ... | At first, compute $z=\sum_{i=1}^{n}a_{i}$. It equals $ \lfloor mnk / 100 \rfloor $, where $ \lfloor x \rfloor $ is rounding down. Next we fill first $ \lfloor z / k \rfloor $ squares with a saturation $k$. $( \lfloor z / k \rfloor + 1)$-th square (if it exists) we fill in a saturation $z - \lfloor z / k \rfloor ... | [
"implementation",
"math"
] | 1,300 | null |
71 | C | Round Table Knights | There are $n$ knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knight... | Define an good polygon as a regular polygon which has a knight in a good mood in every of its vertex. Side of polygon we will measure in arcs which is obtained by dividing border of round table with knights. Freeze the length of the side. Let this length equals $k$. Observe that the regular polygon with such length of ... | [
"dp",
"math",
"number theory"
] | 1,600 | null |
71 | D | Solitaire | Vasya has a pack of $54$ cards ($52$ standard cards and $2$ distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.
Vasya lays out $nm$ cards as a rectangle $n × m$. If there are jokers among them, then Vasya should change them with some of the rest of $54 - nm$ ca... | This problem can be divided into some subproblems. Author's solution means following ones: 1. Check validness of square $3 \times 3$. Square is valid if all cards in it has equal suit or different rank. You may not check equal suit because equal suits imply different ranks. 2. Find 2 valid noninetsect squares $3 \ti... | [
"brute force",
"implementation"
] | 2,200 | null |
71 | E | Nuclear Fusion | There is the following puzzle popular among nuclear physicists.
A reactor contains a set of $n$ atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements.
You are allowed to take any two different atoms and fuse ... | At first, you can use some search engine for find periodic table in some printable form. Next use copy-paste (one or several times) and format it by deleting all excess. It is mechanical work for no more than 5 minutes. Also some parser may be written. Note than author's solution does not mean write 100 symbols by hand... | [
"bitmasks",
"dp"
] | 2,200 | null |
73 | A | The Elder Trolls IV: Oblivon | Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so ... | Let's call the monster dimension sizes as x1, x2, x3. 1. O(min(k, x1 + x2 + x3)) solution We can make at most (x1 - 1) + (x2 - 1) + (x3 - 1) cuttings, so we may assume that k <= x1 + x2 + x3 - 3. For each of the three dimensions we will store an integer ai - number of cuttings performed through the corresponding dimens... | [
"greedy",
"math"
] | 1,600 | null |
73 | B | Need For Brake | Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
$n$ racers take part in the championship, which consists of a number of races. After each race racers are ... | We may assume that we have exactly n awarded places but some of them give 0 points. Let's sort places by amount of points (bi) and racers by amount of currently gained points (ai). First let's find the best place Vasya can reach. In the best case he will get b0 points (where b0 is the greatest number among bi). So, let... | [
"binary search",
"greedy",
"sortings"
] | 2,000 | null |
73 | C | LionAge II | Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string $s$, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided ... | It is easy to see that if we put some symbol c at position p of the string s it will not affect symbols at positions (p+2) and greater. So we have a standard DP problem. State of the dynamic is described by three parameters: p - the number of already processed symbols (or the index of currently processed symbol of the ... | [
"dp"
] | 1,800 | null |
73 | D | FreeDiv | Vasya plays FreeDiv. In this game he manages a huge state, which has $n$ cities and $m$ two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every ci... | First, let's divide graph to connected components (provinces). Next, we consider only new graph on these components - for each province we assign a vertex of the graph. Let the total number of provinces is n. Initially the graph is empty since there are no roads between different provinces. Also for each province we ha... | [
"dfs and similar",
"graphs",
"greedy"
] | 2,200 | null |
73 | E | Morrowindows | Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than $x$ and not less than $2$ items in his inventory. A new patch for the game appeared to view... | When x = 2 then the answer is 0. Further we assume that x > 2. In order to uniquely identify the desired number of items t we must choose a set of numbers ai so that for every y from 2 to x the representation in modes ai is unique, i.e. sets of numbers b (y, i) = y / ai (rounded up) are pairwise distinct among all y. N... | [
"math",
"number theory"
] | 2,400 | null |
73 | F | Plane of Tanks | Vasya plays the Plane of Tanks. The tanks in this game keep trying to finish each other off. But your "Pedalny" is not like that... He just needs to drive in a straight line from point $A$ to point B on the plane. Unfortunately, on the same plane are $n$ enemy tanks. We shall regard all the tanks as points. At the init... | If for some velocity v1 we were able to go from point A to point B and receive no more than k hits, then for any velocity v2 > = v1 we also will be able to go from A to B. So we can use the binary search algorithm to find the answer. Suppose we have fixed speed of the tank v. Now we have to count how many enemy tanks w... | [
"brute force",
"geometry"
] | 2,900 | null |
74 | A | Room Leader | Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly $n$ participants. During the contest the participants are suggested to solve five prob... | You can do exactly what is written in a statement. Only one pitfall in this problem is that room leader may have number of points less than zero. | [
"implementation"
] | 1,000 | null |
74 | B | Train | A stowaway and a controller play the following game.
The train is represented by $n$ wagons which are numbered with positive integers from $1$ to $n$ from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or... | In this problem you may find optimal strategy for a stowaway. Next you may just simulate a game. Optimal strategy for the stowaway is placing from a conrtoller as far as possible. In the moving minute the stowaway should go into wagon that farther to the controller. In the idle minute stowaway should go into wagon in w... | [
"dp",
"games",
"greedy"
] | 1,500 | null |
74 | C | Chessboard Billiard | Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.
More formally, first one of four diagonal directions is chosen and the billiard ball moves ... | Define a trajectory as a line that center of a billiard ball is drawing while it is moving. At begin of moving, the ball chose one from no more than two trajectoties and is moving along of it. Let a number of trajectories is $k$. Define $z$as maximal number of billiard balls that can be placed into chessboard without h... | [
"dfs and similar",
"dsu",
"graphs",
"number theory"
] | 2,100 | null |
74 | D | Hanger | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by $n$ hooks, positioned in a row. The hooks are numbered with positive integers from 1 to $n$ from the left to the right.
The company workers have a very complicated work schedule. At the beginning of a work day ... | You may use some data structire that allows fast insert, search, remove of elements and find a minimum of all elements. There can be used, for example, std::set in C++ or analogicaly container in other languages. In this structure segments of empty hooks can be stored. Minimum element in structure should be a segment i... | [
"data structures"
] | 2,400 | null |
74 | E | Shift It! | There is a square box $6 × 6$ in size. It contains $36$ chips $1 × 1$ in size. Those chips contain 36 different characters — "0"-"9" and "A"-"Z". There is exactly one chip with each character.
You are allowed to make the following operations: you may choose one of $6$ rows or one of $6$ columns and cyclically shift th... | A following sequence of operations swaps two pieces in positions 0 and 1: D1 R1 D1 L1 D1 R1 D1 L1 D1 R1 D1 L1 D1. This sequence can be found on a paper by hands or by usung bidirectional BFS with limitation of allowable moves (it also can be found by ordinary BFS with very limited number of allowable moves). Analogical... | [
"constructive algorithms"
] | 2,800 | null |
75 | A | Life Without Zeros | Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation $a + b = c$, where $a$ and $b$ are positive integers, and $c$ is the ... | In this problem you need to do what is written in the statement. You can do it in the following 3 steps: 1- Calculate C. 2- Remove all zeros from A, B and C. 3- Check if the new values form a correct equation. | [
"implementation"
] | 1,000 | #include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits... |
75 | B | Facetook Priority Wall | Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).
This priority factor will be affected by three types of actions:
- 1. "$X$ posted on $Y$'s wall" ... | This problem is a direct simulation to the rules written in the problem statement. You need to iterate over all actions and parse each one to know the type of the action, and the 2 names X and Y, and if your name is X or Y then update your priority factor with this person with the action corresponding value. And take c... | [
"expression parsing",
"implementation",
"strings"
] | 1,500 | #include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits... |
75 | C | Modified GCD | Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task... | In this problem you will need to generate all common divisors between a and b before answering any query. The first step in this problem is to factorize a and b, you can use the trial division technique which runs in O(sqrt(N)), you can check getFactors function in my solutions. Then using a recursive function you can ... | [
"binary search",
"number theory"
] | 1,600 | #include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits... |
75 | D | Big Maximum Sum | Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the stand... | This problem is my favorite one in this problem set. Maybe it will be easier to solve this problem if you know how to solve the standard one. But because we can't construct the big array, so we can't apply the standard solution for this problem. Let's see first how to solve the standard problem, the following code solv... | [
"data structures",
"dp",
"greedy",
"implementation",
"math",
"trees"
] | 2,000 | #include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits... |
75 | E | Ship's Shortest Path | You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.
And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 po... | The main idea for this problem is not hard, but maybe the hard part is implementing it. First we need to know if the straight line segment between the source and destination points intersect with the island or not. So we will intersect this line segment with all the polygon sides. If there are 2 segments intersect in m... | [
"geometry",
"shortest paths"
] | 2,400 | #include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits... |
76 | A | Gift | The kingdom of Olympia consists of $N$ cities and $M$ bidirectional roads. Each road connects exactly two cities and two cities can be connected with more than one road. Also it possible that some roads connect city with itself making a loop.
All roads are constantly plundered with bandits. After a while bandits becam... | Suppose that the pair $(A, B)$ is an optimal solution, where $A$ is the number of gold coins in a gift and $B$ is a number of silver coins. It is easy to see that there exist two (probably equal) indexes $i$ and $j$ such that $g_{i} = A$ and $s_{j} = B$. It is true, because in the other case we could decrease either $A... | [
"dsu",
"graphs",
"sortings",
"trees"
] | 2,200 | null |
76 | B | Mice | Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and ther... | It is easy to see that the number of closest pieces of cheese for each mouse is not greater than 2. Let's find the closest pieces of cheese for each mouse to the left and to the right from it. From two directions we will choose the one which gives us shorter way to cheese or both of them if their lengths are equal. If ... | [
"greedy",
"two pointers"
] | 2,100 | null |
76 | C | Mutation | Scientists of planet Olympia are conducting an experiment in mutation of primitive organisms. Genome of organism from this planet can be represented as a string of the first $K$ capital English letters. For each pair of types of genes they assigned $a_{i, j}$ — a risk of disease occurence in the organism provided that ... | In the editorial we will replace terms "risk", "genome" and "gene" with "cost", "string" and "character", respectively. Let $S$ be the starting string. Let $M$ be the bitmask of chars which will be removed. Let's iterate over all possible values of $M$. For the fixed $M$ we need to find a cost of the string, which rema... | [
"bitmasks",
"dp",
"math"
] | 2,700 | null |
76 | D | Plus and xor | Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions ... | Let's take a look at some bit in X, which is equal to 1. If the respective bit in Y is equal to 0, then we can swap these two bits, thus reducing X and increasing Y without changing their sum and xor. We can conclude that if some bit in X is equal to 1 then the respective bit in Y is also equal to 1. Thus, $Y = X + B$.... | [
"dp",
"greedy",
"math"
] | 1,700 | null |
76 | E | Points | You are given $N$ points on a plane. Write a program which will find the sum of squares of distances between all pairs of points. | Let's regroup summands and split the sum of squares of distances we are looking for into two sums: ${\textstyle\sum_{i=1}^{N}\sum_{j=1}^{i-1}(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}}$ $\begin{array}{r}{\sum_{i=1}^{N}\sum_{j=1}^{k-1}(x_{i}-x_{j})^{2}+\sum_{i=1}^{N}\sum_{j=1}^{i-1}(y_{i}-y_{j})^{2}}\end{array}$ Now we need to... | [
"implementation",
"math"
] | 1,700 | null |
76 | F | Tourist | Tourist walks along the $X$ axis. He can choose either of two directions and any speed not exceeding $V$. He can also stand without moving anywhere. He knows from newspapers that at time $t_{1}$ in the point with coordinate $x_{1}$ an interesting event will occur, at time $t_{2}$ in the point with coordinate $x_{2}$ — ... | We can get to the event $j$ from the event $i$ if the following statements are true: $t_{i} \le t_{j}$ $|x_{i} - x_{j}| \le |t_{i} - t_{j}| \cdot V$ We can represent all the events as points on a plane with coordinates $(x_{i}, t_{i})$. Now we can reformulate the two statements written above in the following way: ... | [
"binary search",
"data structures",
"dp"
] | 2,300 | null |
77 | A | Heroes | The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us... | It is possble to solve this problem by full search because there are only $k = 7$ heroes and three team. Let's find all dividings - move every hero in every team and drop away incorrect dividings when al least one team is empty. In each correct dividing we should find value of experience between two heroes who will rec... | [
"brute force",
"implementation"
] | 1,400 | null |
77 | B | Falling Anvils | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who ... | In this problem you were to determine the probability if the equation $x^{2}+{\sqrt{p}}\cdot x+q=0$ has at least one real root, assuming that values $p$ and $q$ are independent and equiprobable. It's equivalent to the condition of non-negativity of the discriminant $D = p - 4q$. To solve this problem you might draw a r... | [
"math",
"probabilities"
] | 1,800 | null |
77 | C | Beavermuncher-0xFF | "Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills.
And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with t... | Let's assume that in vertix $v$ it is possible to find pair of values $< x_{i}, y_{i} >$ for every child $v_{i}$ where $x_{i}$ is maximal amount of beavers which can eat beavermuncher if it comes to vertix $v_{i}$ and return back, and $y_{i}$ is amount of beavers which will still alive in vertix $v_{i}$ after beavermun... | [
"dfs and similar",
"dp",
"dsu",
"greedy",
"trees"
] | 2,100 | null |
77 | D | Domino Carpet | ...Mike the TV greets you again!
Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you!
This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other... | Look at squares of Domino Carpet. They are can be only in one of this three states: 1. Here can be any domino chip 2. Here can be only horizontal domino chip 3. Here can be only vertical domino chip No matter what is in squares, only their states are important. Look at the any pair of columns $j$ and $j + 1$ where in s... | [
"dp",
"implementation"
] | 2,300 | null |
77 | E | Martian Food | Have you ever tasted Martian food? Well, you should.
Their signature dish is served on a completely black plate with the radius of $R$, flat as a pancake.
First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of $r$ and is located as close to the edge of the plate as poss... | The problem can be solved using the inversion conversion. Inversion is the conversion transfering a point with the polar coordinates $(r, \phi )$ to a point $\bigl({\frac{1}{\tau}},\varphi\bigr)$. It's stated that the inversion transfers straight lines or circles to straight lines or circles. Straight line can be imag... | [
"geometry"
] | 2,800 | null |
78 | A | Haiku | Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll... | You should count a number of vowels for every of three phrases. Next, you should compare this numbers with numbers 5, 7 and 5. If all is matched, answer is YES, otherwise answer is NO. | [
"implementation",
"strings"
] | 800 | null |
78 | B | Easter Eggs | The Easter Rabbit laid $n$ eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
- Each of the seven colors should be used to paint at least one egg.
- Any four eggs \textbf{ly... | At first, you can $[n / 7]$ times output string "ROYGBIV" ($[]$ is a rounding down). After than you can output "", "G", "GB", "YGB", "YGBI", "OYGBI" or "OYGBIV" according to remainder of division $n$ by 7. A resulting string will satisfy problem's requirements. You can also build answer in other way. | [
"constructive algorithms",
"implementation"
] | 1,200 | null |
78 | C | Beaver Game | Two beavers, Timur and Marsel, play the following game.
There are $n$ logs, each of exactly $m$ meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of \textbf{equal} parts, the length of each one is expressed by an integer and is no less than ... | If $n$ is even, Marsel wins - he just symmetrically repeats moves of Timur. Now consider a case of odd $n$. If Timur cannot move - he is losing automatically. If he can do a move, he always can split one log into few parts that this parts cannot be splitted again. It can be done if we have find minimal $t$ that $k \le... | [
"dp",
"games",
"number theory"
] | 2,000 | null |
78 | D | Archer's Shot | A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.
The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playin... | It should be solved like a classical problem "count the number of square cells 1x1 lying inside the circle". Firstly, lets find the highest hexagon that lies inside the circle. Then we move to the right and up from this hexagon, and then go down until we find hexagon lying inside the circle. Repeat this process until y... | [
"binary search",
"geometry",
"math",
"two pointers"
] | 2,300 | null |
78 | E | Evacuation | They've screwed something up yet again... In one nuclear reactor of a research station an uncontrolled reaction is in progress and explosion which will destroy the whole station will happen soon.
The station is represented by a square $n × n$ divided into $1 × 1$ blocks. Each block is either a reactor or a laboratory.... | Firstly, let's calculate the following value: dp[t][x0][y0][x][y] == true iff scientist from block (x0,y0) can reach block (x,y) in time t, considering toxic coolant. Secondly, let's consider a graph consisting of 4 parts: 1 - source (one vertex) 2 - first fraction (nxn vertices) 3 - second fraction (nxn vertices) 4 - ... | [
"flows",
"graphs",
"shortest paths"
] | 2,300 | null |
79 | A | Bus Game | After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
- Initially, there is a pile that contains $x$ 100-yen coins and $y$ 10-yen c... | Brute force simulation works in this problem. In Ciel's turn, if she has at least 2 100-yen coins and at least 2 10-yen coins, pay those coins. Otherwise, if she has at least 1 100-yen coins and at least 12 10-yen coins, pay those coins. Otherwise, if she has at least 22 10-yen coins, pay those coins. Otherwise, she lo... | [
"greedy"
] | 1,200 | null |
79 | B | Colorful Field | Fox Ciel saw a large field while she was on a bus. The field was a $n × m$ rectangle divided into $1 × 1$ cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in follow... | A solution that uses an array of $N \times M$ will absolutely get (Time|Memory)LimitExceeded, so we cannot simulate it naively. Both the number of queries and the number of waste cells $K$ are not more than 1,000, so it is enough to answer each queries in $O(K)$ runtime. Let $(a, b)$ be a query cell. Whether $(a, b)$... | [
"implementation",
"sortings"
] | 1,400 | null |
79 | C | Beaver | After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string $s$, and she tried to remember the string $s$ correctly.
However, Ciel... | We can regard a substring that is equal to one of boring strings as an interval. The number of such intervals are at most $|s| \cdot n$, and the required time to determine whether each of them is a boring string is $|b_{i}|$, so all intervals can be calculated in $O(|s| \cdot n \cdot |b_{i}|)$ runtime, by naive way.... | [
"data structures",
"dp",
"greedy",
"hashing",
"strings",
"two pointers"
] | 1,800 | null |
79 | D | Password | Finally Fox Ciel arrived in front of her castle!
She have to type a password to enter her castle. An input device attached to her castle is a bit unusual.
The input device is a $1 × n$ rectangle divided into $n$ square panels. They are numbered $1$ to $n$ from left to right. Each panel has a state either ON or OFF. I... | Define an array $b_{0}, b_{1}, ..., b_{n}$ as follows: If the states of $i$-th panel and $(i + 1)$-th panel are same, $b_{i} = 0$. If the states of $i$-th panel and $(i + 1)$-th panel are different, $b_{i} = 1$. (The states of $0$-th panel and $(n + 1)$-th panel are considered to be OFF.) If Ciel flips panels between $... | [
"bitmasks",
"dp",
"shortest paths"
] | 2,800 | null |
79 | E | Security System | Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.
Ciel is at point $(1, 1)$ of the castle now, and wants to move to point $(n, n)$, which is the position of her room. By one step, Ciel can move from point $(x,... | Lemma. The sensors we should consider are only four sensors at the corner. proof: Let's think about sensors at a fixed row $v$. As the definition, when Ciel entered to $(x, y)$, a sensor at $(u, v)$ decreases its count by $|x - u| + |y - v|$. Let this value be $f_{x, y}(u)$. If we fix Ciel's path, the total decrease of... | [
"math"
] | 2,900 | null |
80 | A | Panoramix's Prediction | A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers $2$, $7$, $3$ are prime, and $1$, $6$, $4$ are not.
{The next prime number after $x$ is the \textbf{smallest} prime number greater than $x$. For example, the next prime number after $2$ is $3$, and the next prime n... | In the very beginning of statement you may find some words about what is prime number and what is next prime number. Main point of problem is to check is $m$ next prime after $n$ or not. Problem statement guarantees that $n$ is prime number. We need to check only two cases: 1. Number $m$ is prime, and 2. There is no an... | [
"brute force"
] | 800 | null |
80 | B | Depression | Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!
There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...
Everybody was upset. The beautiful B... | The first I pay your attention is while we are moving first arrow the second one is stay motionless. In fact this means that we can solve next two problems independently: 1. Find the angle to turn the minute hand, and 2. Find the angle to turn the hours hand Next, you may find in statement phrase: "Cogsworth's hour and... | [
"geometry",
"math"
] | 1,200 | null |
82 | A | Double Cola | Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d... | Let's designate characters on the first letter of the name. The queue looks like: SH-L-P-R-G, through 5 cans: SH-SH-L-L-P-P-R-R-G-G, through 10 cans: SH-SH-SH-SH-L-L-L-L-P-P-P-P-R-R-R-R-G-G-G-G. The regularity is clear, and the solution is very simple: we will be iterated on $p$ - we will find such minimum $p$ that $5 ... | [
"implementation",
"math"
] | 1,100 | null |
82 | B | Sets | Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose $n$ non-empty sets in such a way, that no two of them have common elements.
One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possib... | For the solution the following important fact is required to us: we will admit elements $v$ and $u$ are in one set then in any of $n \cdot (n - 1) / 2$ of sequences from the input data where meets $v$ $u$ necessarily meets. And also if $v$ and $u$ are in different sets there is such sequence in which is $v$, but isn't... | [
"constructive algorithms",
"hashing",
"implementation"
] | 1,700 | null |
82 | C | General Mobilization | The Berland Kingdom is a set of $n$ cities connected with each other with $n - 1$ railways. Each road connects exactly two different cities. The capital is located in city $1$. For each city there is a way to get from there to the capital by rail.
In the $i$-th city there is a soldier division number $i$, each divisio... | At first we will estimate from above the maximum time to which all divisions will reach capital - obviously it is required no more $n$ days for this purpose. Therefore restrictions quite allowed model movements of divisions. The key moment of the solution - we will always consider divisions in priority order. Then in e... | [
"data structures",
"dfs and similar",
"sortings"
] | 2,000 | null |
82 | D | Two out of Three | Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.
Let the queue to the cashier contain $n$ people, at that each of them is characterized by a positive integer $a_{i}$ — that is the time needed to work with this customer. What is special abo... | The problem dares the dynamic programming. We will consider a state $(i, j)$ meaning that in the current turn there is a person number $i$ and also all people from $j$ to $n$ inclusive. Any turn achievable of the initial can be presented by corresponding condition. The quantity of conditions is $O(n^{2})$, the quantity... | [
"dp"
] | 2,000 | null |
82 | E | Corridor | Consider a house plan.
Let the house be represented by an infinite horizontal strip defined by the inequality $ - h ≤ y ≤ h$. Strictly outside the house there are two light sources at the points $(0, f)$ and $(0, - f)$. Windows are located in the walls, the windows are represented by segments on the lines $y = h$ and ... | This problem has some solutions based on the various methods of the search of the area of the association of the figures on a plane. One of such methods is the method of vertical decomposition (more in detail you can esteem in various articles) and also it was possible to notice that among figures there are no three ha... | [
"geometry"
] | 2,600 | null |
83 | A | Magical Array | \underline{Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.}
Vale... | We must find out all the intervals that consist of the same integers. For an interval with $P$ integers, the number of reasonable subsequences is $\frac{P(P+1)}{2}$. Thus, we can adopt two pointers to find out all the target intervals, and calculate the answer. | [
"math"
] | 1,300 | null |
83 | B | Doctor | There are $n$ animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number $i$ in the queue will have to visit... | The basic idea is still binary search. We use $a[n]$ to denote the given array. We use binary search to find out the maximum $T$ so that $S=\sum_{0}^{n-1}m i n(a[i],T)\leq K$. Moreover, we compute $K - S$ as the remainder. Then, any $a[i]$ that is not larger than $T$ should be firstly eliminated. Next we enumerate the ... | [
"binary search",
"math",
"sortings"
] | 1,800 | null |
83 | C | Track | You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.
The track's map is represented by a rectangle $n × m$ in size di... | I spent about three hours modifying the algorithm to avoid the time limit....The most impressive modification I used is scaling the constant from $1$ to $\frac{1}{6}$. This is the first time that I realized what an important role that a constant can play. The general idea is to generate all the feasible patterns of map... | [
"graphs",
"greedy",
"shortest paths"
] | 2,400 | null |
84 | A | Toy Army | The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of $n$ men ($n$ is always even). The current player... | The strict proof seems to be a little complicated as far as I consider, however an intuitive understanding suggests that the answer is $n + n / 2$, and it is accpeted... | [
"math",
"number theory"
] | 900 | null |
84 | C | Biathlon | Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.
Of course, biathlon as any sport, proved very difficult in practice. I... | As it has been guaranteed that no two circles intersect with each other, the given point can only fall into at most one particular circle (one special case is that two circles touch each other at the given point). Thus, we first sort the circles in an increasing order of their X-coordinates, and find out two circles be... | [
"binary search",
"implementation"
] | 1,700 | null |
85 | C | Petya and Tree | One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time h... | So, let remember statement of the problem. We have the correct binary search tree and the set of request keys. For each request key we consider paths in the tree with one error. These paths are constructed by the search of request key in the tree with one wrong choice of the next vertice. Each wrong choice generate one... | [
"binary search",
"dfs and similar",
"probabilities",
"sortings",
"trees"
] | 2,200 | null |
86 | A | Reflection | For each positive integer $n$ consider the integer $ψ(n)$ which is obtained from $n$ by replacing every digit $a$ in the decimal notation of $n$ with the digit $(9 - a)$. We say that $ψ(n)$ is the reflection of $n$. For example, reflection of $192$ equals $807$. Note that leading zeros (if any) should be omitted. So re... | First note that if the interval contains a number with $a$ digits and a number with $b$ digits (where $a$ > $b$) then there is no need to consider the number with $b$ digits (as the weight of $10^{k}$ is greater then the weights of the numbers less than $10^{k}$). If we consider only numbers with fixed number of digits... | [
"math"
] | 1,600 | null |
86 | B | Tetris revisited | Physicist Woll likes to play one relaxing game in between his search of the theory of everything.
Game interface consists of a rectangular $n × m$ playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean conn... | It's easy to see that the field may be filled with such figures if and only if there is no isolated cell. There are many different ways to do that, we will show some of them. 1. Domino filling. We construct greedy matching on the cells of our field combining them in domino-like figures (rectangles 1 $ \times $ 2). Pass... | [
"constructive algorithms",
"graph matchings",
"greedy",
"math"
] | 2,200 | null |
86 | C | Genetic engineering | "Multidimensional spaces are completely out of style these days, unlike genetics problems" — thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string ... | Suppose we've built a string $wp$ of length $k < n$ and want to know how many ways there exist to complement $wp$ to the suitable string of length $n$. What parameters do we need to know in order to build it further? First of all, we need to know the index $wp$ is covered up to (we denote it by $ci$ and call it coverin... | [
"dp",
"string suffix structures",
"trees"
] | 2,500 | null |
86 | D | Powerful array | An array of positive integers $a_{1}, a_{2}, ..., a_{n}$ is given. Let us consider its arbitrary subarray $a_{l}, a_{l + 1}..., a_{r}$, where $1 ≤ l ≤ r ≤ n$. For every positive integer $s$ denote by $K_{s}$ the number of occurrences of $s$ into the subarray. We call the power of the subarray the sum of products $K_{s}... | Let's solve the problem offline in O(n sqrt(t)) time and O(n) memory. For the simplicity of the reasoning let t = n. Assume we know the answer to the problem for some interval and want to find it to another one. Let us move the left end of the first one towards the left end of the second, similarly dealing with the rig... | [
"data structures",
"implementation",
"math",
"two pointers"
] | 2,200 | null |
86 | E | Long sequence | A sequence $a_{0}, a_{1}, ...$ is called a recurrent binary sequence, if each term $a_{i}$ $(i = 0, 1, ...)$ is equal to 0 or 1 and there exist coefficients $c_{1},c_{2},\dots,c_{k}\in\{0,1\}$ such that
\[
a_{n} = c_{1}·a_{n - 1} + c_{2}·a_{n - 2} + ... + c_{k}·a_{n - k} (mod 2),
\]
for all $n ≥ k$. Assume that not a... | Firstly let's note that there are only 49 different possible inputs. So any solution that works finite time at all tests (even if does not pass timelimit) is enough, because we can memorize all the answers. It is not necessary, of course, but may help with slow solutions. Then, let's answer a more particular question. ... | [
"brute force",
"math",
"matrices"
] | 2,700 | null |
87 | A | Trains | Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,... | This problem can be approached from two sides - from a programmer's perspective and a mathematician's one. We consider both approaches. First, let's write some general propositions. Let's put on a straight line all the moments of time when the trains arrive. We will refer the interval between two successive points to t... | [
"implementation",
"math"
] | 1,500 | null |
87 | B | Vasya and Types | Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below... | In this task, it was necessary to do exactly what is written in the problem's statement, for practically any complexity. You are suggested to do the following. For each data type we shall store two values - its name and the number of asterisks when it is brought to void. Then the typeof request is processed by consecut... | [
"implementation",
"strings"
] | 1,800 | null |
87 | C | Interesting Game | Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of $n$ stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of $a_{1} > a_{2} > ... > a_{k} > 0$ stones. The piles should meet the condition $a_{1} - a_{2} = a_{2} - a... | In this task you should analyze the game. However, due to the fact that with every move the game is divided into several independent ones, the analysis can be performed using the Grundy's function (you can read about it here, or here). Now all we have to do is to construct edges for each position. We can build the edge... | [
"dp",
"games",
"math"
] | 2,000 | null |
87 | D | Beautiful Road | A long time ago in some country in Asia were civil wars.
Each of $n$ cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city.
Road making was difficult, so the country had few roads, exactly $n - 1$. Also you could reach any city from any other city go... | In this task we should count for each edge the number of ways on which it is maximal. Since for one edge alone it does not seem possible to find the answer faster than in the linear time, the solution will compute answer for all the edges at once. We shall solve the problem first for the two extreme cases, then, combin... | [
"dfs and similar",
"dp",
"dsu",
"graphs",
"implementation",
"sortings",
"trees"
] | 2,300 | null |
87 | E | Mogohu-Rea Idol | A long time ago somewhere in the depths of America existed a powerful tribe governed by the great leader Pinnie-the-Wooh. Once the tribe conquered three Maya cities. Pinnie-the-Wooh grew concerned: there had to be some control over the conquered territories. That's why he appealed to the priests of the supreme god Mogo... | In this task we had to verify that the point is the centroid of the triangle formed by points of the given three polygons. Lets reformulate the problem. We should verify the existence of three points A, B, C, such that A belongs to the first polygon, B - to the second one, C - to the third one, and ${\overrightarrow{O ... | [
"geometry"
] | 2,600 | null |
88 | A | Chord | Vasya studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note afte... | First we need to understand a simple fact - the notes are actually residues modulo 12. It means the minor chord has the form {x, x +3, x +7} (mod 12), and the major one - {x, x +4, x +7}. It is convenient to read the notes as strings, after that it is better to immediately replace them by a corresponding number from 0 ... | [
"brute force",
"implementation"
] | 1,200 | null |
88 | B | Keyboard | Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has $n$ rows of keys containing $m$ keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they m... | Here we simply consecutively check for each letter of the alphabet in its two variants, uppercase and lowercase, whether it can be typed with one hand or not. And if we can't type it with one hand, we check whether it can be typed with two hands or can't be typed at all however how many hands one would use :-) To verif... | [
"implementation"
] | 1,500 | null |
89 | A | Robbery | It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has $n$ cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from $1$ to $n$ from the left to the right.
Unfortunately... | Determine a form of all arrangements of diamonds that set of all sums of pairs adjacent cells is invariably. If you remove from the first cell exactly $c$ diamonds, you should add exactly $c$ diamonds into the second cell, remove $c$ diamonds from the third cell and so on. In other words, all valid arrangements can be ... | [
"greedy"
] | 1,800 | null |
89 | B | Widget Library | Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other.
A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on th... | Here you can build some miltigraph in which nodes are widgets and edges are relationship of pack()-method. This graph is acyclic. Next, you should do topological sort of nodes. Sizes of widgets should be calculated in the obtained order. At the last, you should sort all nodes by thier names and output an answer. About ... | [
"dp",
"expression parsing",
"graphs",
"implementation"
] | 2,300 | null |
89 | C | Chip Play | Let's consider the following game. We have a rectangular field $n × m$ in size. Some squares of the field contain chips.
Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right.
The player may choose a chip and make a move with it.
The mov... | This problem can be solved by simulation. You can just iterate over all chips and for every of them calculate number of points. But srupid simulate can give $O(k^{3})$ time solution, where $k$ is total number of chips. It doesn't fit into time limits. For example, try test like 1 5000 RRRR...[2500 times]LLLL...[2500 ti... | [
"brute force",
"data structures",
"implementation"
] | 2,300 | null |
89 | D | Space mines | Once upon a time in the galaxy of far, far away...
Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.
When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — sp... | Initially lets pump all mines on radius of Death Star and squeeze Death Star into point. Now you should determine an intersection of a ray with obtained figures. Mine's body with radius $r$ is pumped into ball with radius $r + R$. Every mine's spike is pumped into union of two balls with radius $R$ and cylinder. One of... | [
"geometry"
] | 2,500 | null |
89 | E | Fire and Ice | The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment $n$ in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom.
The $n$-long segment is located at a distance equal exactly to $1$ ... | Solomon can just create some segments of ice cubes and cut its. Consider a segment with rightmost begin. You can assume that it ends in position of the last demon (you always can cut end of a segment that ends on last demon and add it to current segment). For cutting the last segment you should build "ice bridge" to it... | [
"greedy"
] | 2,900 | null |
90 | A | Cableway | A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them ... | In this problem you can simulate the process. You can consider all minutes and in dependence by a color of a current cablecar decrease size of corresponding group of students $G$ by $min(|G|, 2)$, where $|G|$ is size of the group. After that you should determine the first minute $t$ in that all three groups of students... | [
"greedy",
"math"
] | 1,000 | null |
90 | B | African Crossword | An African crossword is a rectangular table $n × m$ in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a let... | It this problem you should write exactly that is written in statement. For every letter you should see a row and a column of the letter. If equal letter was found, current letter sould not be output. You can combine scanning rows and columns and output an answer, for example, this way: FOR(a,1,n) FOR(b,1,m) { bool shou... | [
"implementation",
"strings"
] | 1,100 | null |
91 | A | Newspaper Headline | A newspaper is published in Walrusland. Its heading is $s_{1}$, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get ... | In this problem letters from $s1$ should be taken greedily: take the left letter from the right of the last used letter, if there is no necessary letter from the right of the right used letter the the search should be started from the beginning of string $s1$ and the answer should be increased by one. But the brute sol... | [
"greedy",
"strings"
] | 1,500 | null |
91 | B | Queue | There are $n$ walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the $1$-st walrus stands at the end of the queue and the $n$-th walrus stands at the beginning of the queue. The $i$-th walrus has the age equal to $a_{i}$.
The $i$-th walrus becomes displeased if there's a youn... | There were a lot of different solutions but I will tell you the author solution. Let's precalculate $[i, n]$. It can be done with the time equal to $O(n)$ moving from the right to the left. Define $[i, n]$ as $Min_{i}$. Obviously, that $Min_{i} < = Min_{i + 1}$. Now for every position $i$ using binary search let's find... | [
"binary search",
"data structures"
] | 1,500 | null |
91 | C | Ski Base | A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains $n$ ski junctions, numbered from $1$ to $n$. Initially the junctions aren't connected in any way.
In the constructing process $m$ bidirection... | We will count the number of ski bases including the base consisted of empty subset of edges (before printing just subtract one). In the beginning the number of bases is equal to $1$. If we connect vertexes in the same connected components then the result should be multiplied by $2$ else do nothing. You should use DJS d... | [
"combinatorics",
"dsu",
"graphs"
] | 2,300 | null |
91 | D | Grocer's Problem | Yesterday was a fair in a supermarket's grocery section. There were $n$ jars with spices on the fair. Before the event the jars were numbered from $1$ to $n$ from the left to the right. After the event the jars were moved and the grocer had to sort them by the increasing of the numbers.
The grocer has a special machin... | Let's find all cycles in substitution: $1$ $2$ $3$ $4$ $5$ ... $a_{1}$ $a_{2}$ $a_{3}$ $a_{4}$ $a_{5}$ ... For example, in sequence $a = {2, 1, 4, 5, 3}$ exist two cycles with length $2$ and $3$ on positions $1$ $2$ and $3$ $4$ $5$ respectively. If the length of the cycle is more than $5$, then we can take $5$ consecut... | [
"constructive algorithms",
"graphs",
"greedy"
] | 2,600 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.