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
325
C
Monsters and Diamonds
Piegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are $n$ types of monsters, each with an ID between $1$ and $n$. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. M...
First part of the problem is to find minimum number of diamonds one can achieve by starting with a given monster. To do so, we will be using Dijkstra algorithm. Originally we don't know the minimum for any monster. For every rule we will maintain how many monsters with unknown minimums it has (let's call it $k_{i}$ for...
[ "dfs and similar", "graphs", "shortest paths" ]
2,600
null
325
D
Reclamation
In a far away land, there exists a planet shaped like a cylinder. There are three regions in this planet: top, bottom, and side as shown in the following picture. Both the top and the bottom areas consist of big cities. The side area consists entirely of the sea. One day, a city decides that it has too little space a...
Assume there's an extra sea cells on a row above the topmost row, and a row below the bottom most row. Hence, we can assume that the top and bottom row consists entirely of sea. We claim that: There does not exist a sea route if and only if there exists a sequence of land cells that circumfere the planet (2 cells are a...
[ "dsu" ]
2,900
null
325
E
The Red Button
Piegirl found the red button. You have one last chance to change the inevitable end. The circuit under the button consists of $n$ nodes, numbered from 0 to $n$ - 1. In order to deactivate the button, the $n$ nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node $i$, the next...
In this part of editorial, all numbers we speak are in modulo $N$. So, if I say 10, it actually means 10 modulo $N$. First, observe that this problem asks us to find a cycle that visits each node exactly once, i.e., a hamiltonian cycle. Thus, for each node $X$, there exists one other node that we used to go to node $X$...
[ "combinatorics", "dfs and similar", "dsu", "graphs", "greedy" ]
2,800
null
327
A
Flipping Game
Iahub got bored, so he invented a game to be played on paper. He writes $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices $i$ and $j$ ($1 ≤ i ≤ j ≤ n$) and flips all values $a_{k}$ for which their positions are in range $[i...
I'll present here the O(N ^ 3) algorithm, which is enough to solve this task. Then, for those interested, I'll show a method to achieve O(N) complexity. O(N ^ 3) method: The first thing to observe is that constrains are slow enough to allow a brute force algorithm. Using brute force, I can calculate for each possible s...
[ "brute force", "dp", "implementation" ]
1,200
null
327
B
Hungry Sequence
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of $n$ integers. A sequence $a_{1}$, $a_{2}$, ..., $a_{n}$, consisting of $n$ integers, is Hungry if and only if: - Its elements are ...
We'll present two different solutions for this task. Solution 1. What if we solve a more general task? What if each hungry number from the solution isn't allowed to be divided by any number smaller than it (except 1, which is divides every natural number). If this more general condition would be met, then the "hungry" ...
[ "math" ]
1,200
null
327
C
Magic Five
There is a long plate $s$ containing $n$ digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by $5$. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number o...
Property: A number is divisible by 5 if and only if its last digit is either 0 or 5. A first solution: Suppose you're given a plate S, not so big, so we can iterate all its elements. Can we get the answer? I build a new array sol[]. In explanation, both S and sol will be 1-based. Denote N = size of S. Also, denote sol[...
[ "combinatorics", "math" ]
1,700
null
327
D
Block Tower
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with $n$ rows and $m$ columns (it contains $n × m$ cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build a...
The restriction given in the problem poses you to think of building as many Red Towers as possible, and fill the rest with Blue Towers (since there is no profit of letting cells empty, such cells can be filled by Blue Towers). Also, it's quite obvious to see that each connected component (containing empty cells only) i...
[ "constructive algorithms", "dfs and similar", "graphs" ]
1,900
null
327
E
Axis Walking
Iahub wants to meet his girlfriend Iahubina. They both live in $Ox$ axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point $d$. Iahub has $n$ positive integers $a_{1}$, $a_{2}$, ..., $a_{n}$. The sum of those numbers is $d$. Suppose $p_{1}$, $p_{2}$, ..., $p_{n}$ is a permutation of ${1, 2, ..., n}$....
Usually when dealing with complicated problems, a good idea is to solve them for small cases. Let's try this here. First case: K = 0. The answer is obviously N! (each permutation of p1, p2, \dots , pn would be good). Next case: K = 1. The answer of this one is N! - |L1|. By L1 I denote all routes for which a prefix su...
[ "bitmasks", "combinatorics", "constructive algorithms", "dp", "meet-in-the-middle" ]
2,300
null
329
A
Purification
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an $n × n$ grid. The rows are numbered $1$ through $n$ from top to bottom, and the columns are numbered $1$ through $n$ from left to right. At the far side...
Obviously the minimum possible answer is n (why?). But is it always possible to purify all the cells with n spells? If there exist a row consisting of entirely "E" cells and a column consisting of entirely "E" cells, then the answer is -1. This is since the cell with that row and that column cannot be purifed. Otherwis...
[ "constructive algorithms", "greedy" ]
1,500
null
329
B
Biridian Forest
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest. \textbf{The forest} The Biridian Forest is a two-dimensional grid consisting of $r$ rows and $c$ columns. Each cell in Biridian Forest may contain a tree, or m...
The only non ad hoc problem in the round! ...sort of. Despite the very long problem statement, the solution is really simple. We should take any shortest path from S to E (yes, any!). We will see why this is optimal at the end. If a breeder can reach E faster than or equal to us, then he will battle us. This is since h...
[ "dfs and similar", "shortest paths" ]
1,500
null
329
C
Graph Reconstruction
I have an undirected graph consisting of $n$ nodes, numbered 1 through $n$. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: - The new graph consists of the same number ...
If n <= 7, brute force all possible subsets of the edges (at most 2^(7 * (7 - 1) / 2)), and check if they satisfy the constraint. Otherwise, a solution always exists. Here is how to construct one. Partition the nodes into connected components. Note that each component will be either a cycle or a chain. List the nodes o...
[ "constructive algorithms" ]
2,400
null
329
D
The Evil Temple and the Moving Rocks
\underline{Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.} You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of ti...
Post your solution in the comment! Here's mine for the last case! (approximately 120,000 sounds). You can get the number of sounds your solution produces when submitting it to the server. 1 copy of v<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< v>v>v>v>v>v>v>v>v>v>v...
[ "constructive algorithms" ]
2,500
null
329
E
Evil
There are $n$ cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all $n$ cities. The length of this Hamiltonian cycle is defined as the sum of the di...
This problem asks us to prove something very long (the proof below is of 80+ lines). Assume that the number of cities is at least 4. The case where it's less than 4 is trivial. First, we will assume that no two cities will have same X or Y coordinates. To get this assumption, we can juxtapose every city very slightly t...
[ "math" ]
3,100
import sys n = int(raw_input()) coordinates = [] xs = [] ys = [] for i in range(n): x, y = map(int, raw_input().split()) coordinates.append(((x, i), (y, i))) xs.append((x, i)) ys.append((y, i)) xs = sorted(xs) ys = sorted(ys) amt = [[0] * 2 for _ in range(2)] medians = 0 for x, y in coordinates: if ...
330
A
Cakeminator
You are given a rectangular cake, represented as an $r × c$ grid. Each cell either has an evil strawberry, or is empty. For example, a $3 × 4$ cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at ...
Long solution: Once an evil strawberry, always an evil strawberry (since they can't be eaten). Thus, if a row cannot be eaten before any eat is performed, it can never be eaten. Same with column. Thus, you can know which columns and which rows you can eat. Just try to eat them all and calculate how many cells you actua...
[ "brute force", "implementation" ]
800
null
330
B
Road Construction
A country has $n$ cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two...
Since m < n/2, there exists at least one node that is not incident to any edge. The constraints can be satisfied if and only if the graph is a star graph. We can just create a star graph centered with the node and connect it to all other nodes.
[ "constructive algorithms", "graphs" ]
1,300
null
332
A
Down the Hatch!
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
Since $n \ge 4$, one Vasya's turn does not affect his other turns. Consequently, you should find just the number of positions (0-indexed) in the given string, which indexes are multiples of $n$ and before which there are at least three same symbols. Asymptotics of the solution - $O(|s|)$
[ "implementation" ]
1,300
#include <iostream> #include <string> #include <cstdio> #include <vector> #include <algorithm> #include <cmath> using namespace std; int main() { int n; string s; cin >> n; getline(cin, s); getline(cin, s); int ans = 0; for (int i = n; i < s.length(); i += n) if (s[i - 1] == s[i - ...
332
B
Maximum Absurdity
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as $n$ laws (each law has been assigned a unique number from 1 to $n$). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed. This time mr. Boosch plans to sign ...
Let's build the array of partial sums, which will permit to find the sum in any segment of the array in $O(1)$. Let's iterate through the number $a$ (the left edge of the leftmost segment) in descending order. Now we need to find among segments of length $k$, starting from position which index is greater than or equal ...
[ "data structures", "dp", "implementation" ]
1,500
#include <iostream> #include <cstdio> #include <vector> using namespace std; inline __int64 get_sum(const vector<__int64> &sum, int l, int r) { return (l == 0) ? sum[r] : (sum[r] - sum[l - 1]); } int main() { int n, k; scanf("%d %d", &n, &k); vector<__int64> a(n), sum(n); scanf("%I64d", &a[0]); ...
332
C
Students' Revenge
A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banni...
Let's sort orders ascending $b_{i}$, and by equality of $b_{i}$ - descending $a_{i}$. One can assume that in an optimal solution all the orders obeyed by the chairperson go in the sorted list after orders that she hasn't obeyed (it may be wrong if there are several same orders, but it doesn't affect parameters of an an...
[ "data structures", "greedy", "sortings" ]
2,200
#include <iostream> #include <algorithm> #include <set> #include <cstdio> #include <cassert> #include <cmath> using namespace std; const int MAXN = 100000; struct Order { int a, b, nmb; } orders[MAXN]; int n, p, k; multiset<int> s; __int64 pref[MAXN]; bool cmp1(const Order &x, const Order &y) { retu...
332
D
Theft of Blueprints
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of $n$ missile silos connected by bidirectional underground passages. The passages ...
In the problem is given the weighted undirected graph without loops and multiple edges satisfying the following property: for every set $S$ containing $k$ vertices there is exactly one vertex adjacent to all vertices from this set (*) (this vertex is called "adjacent with $S$"). For any $k$-element set of vertices we c...
[ "graphs", "math" ]
2,400
#include <iostream> #include <vector> #include <cstdio> #include <cmath> using namespace std; const int MAXN = 2000; __int64 c[MAXN][MAXN]; int main() { int n, k, temp; scanf("%d %d", &n, &k); for (int i = 0; i < n - 1; ++i) { c[i][i] = -1; for (int j = i + 1; j < n; ++j) { ...
332
E
Binary Key
Let's assume that $p$ and $q$ are strings of positive length, called the container and the key correspondingly, string $q$ only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message $s$ from the given container $p$: \begin{verbatim} i = 0; j = 0; s = <>; while i is less than the...
Let's iterate through the number of ones in the key ($cnt$). One can note that $cnt$ can't be large than $min(|s|, k)$, as the keys containing more than $|s|$ ones can't be lexicographically minimal. Let's consider the solution of this problem with the fixed $cnt$. Any complete pass on the key corresponds to the extrac...
[ "dp", "greedy", "implementation" ]
2,400
#include <iostream> #include <string> #include <cstdio> #include <vector> #include <algorithm> #include <cmath> using namespace std; bool d[2050][250]; bool pr[2050][250]; int main() { string p, s; getline(cin, p); getline(cin, s); int k; cin >> k; string result = ""; for...
333
A
Secrets
Gerald has been selling state secrets at leisure. All the secrets cost the same: $n$ marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of o...
Actually we are looking for longest sequence of natural number $a_{1}, a_{2}, ..., a_{k}$, so that every number in it sequence is the power of three, sum of all numbers is more then $n$ and if we remove any number sum will be less then $n$. To be precise we are looking for length of this sequence. Consider minimal numb...
[ "greedy" ]
1,600
null
333
B
Chips
Gerald plays the following game. He has a checkered field of size $n × n$ cells, where $m$ various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for $n - 1$ minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its or...
At first lets make two remarks: On every (vertical of horizontal) line we can put only one chip. If there is at least one forbidden cell on the line then we can't put chip on this line. Follow last remark we will avoid hits chip on forbidden cells. Lets avoid ``collisions'' of chips. Lets consider these four line: vert...
[ "greedy" ]
1,800
null
333
C
Lucky Tickets
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such ...
In this problem we can find the right amount of lucky tickets. Lets consider amount of different numbers we can get from one four-digit ticket number. It is easy to iterate all this tickets, since it amount only $10^{4}$. It happened that we can get almost 60 numbers from ticket on the average. Suppose we can get numbe...
[ "brute force", "constructive algorithms" ]
2,700
null
333
D
Characteristics of Rectangles
Gerald found a table consisting of $n$ rows and $m$ columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value — it seemed to be too small. And to...
In this problem we must to find maximal value of minimum of values on four intersections of two rows and two columns of table. In another words, we are looking for maximum value of $min(a_{i1, j1}, a_{i1, j2}, a_{i2, j1}, a_{i2, j2})$ for all $i_{1}, i_{2}, j_{1}, j_{2}$ such that $1 \le i_{1}, i_{2} \le n$, $1 \l...
[ "binary search", "bitmasks", "brute force", "implementation", "sortings" ]
2,100
null
333
E
Summer Earnings
Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a pl...
In this problem it is need to draw three circle equals together with maximum possible radius with centers in given points. In another words it is need to find triangle wich minimum side is maximal. Unfortunately solution with bit optimize is not expected for us. Lets call to memory two simple geometric facts. Firstly, ...
[ "binary search", "bitmasks", "brute force", "geometry", "sortings" ]
2,500
null
334
A
Candy Bags
Gerald has $n$ younger brothers and their number happens to be even. One day he bought $n^{2}$ candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer $k$ from $1$ to $n^{2}$ he has exactly one bag with $k$ candies. Help him give $n$ bags of candies to...
In this problem one must divide all natural numbers from 1 to $n^{2}$ to groups size of $n$ with the same sums. Lets divide all this numbers to pairs $(1,n^{2}),(2,n^{2}-1),\cdot\cdot\cdot,(\frac{n^{2}}{2},\frac{n^{2}}{2}+1)$. We can to do it since $n$ is even and therefore $n^{2}$ is even too. Then we can just make $n...
[ "implementation" ]
1,000
null
334
B
Eight Point Sets
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three int...
In this problem you must to do only what's written - you must to define does this set of points sutisfies to decribed conditions. There are many ways to define it. For instance: Check if there are exactly 3 discinct $x$'s and $y$'s. One can put all $x$'s to set and then get it size to find amount of distinct $x$'s (as ...
[ "sortings" ]
1,400
null
335
A
Banana
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly $n$ stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length $n$. Piegirl wants to create a string $s$ using stickers. She may buy as many s...
Instead of calculating the smallest possible number of sheets given a fixed $n$, let us instead try to compute the smallest possible value of $n$ given a fixed number of sheets. Let $k$ denote the number of sheets. If a particular letter appears $p$ times in $s$, then it must appear at least $ceil(p / k)$ times in the ...
[ "binary search", "constructive algorithms", "greedy" ]
1,400
from collections import Counter def main(): s = raw_input().strip() l = int(raw_input()) d = Counter(s) if len(d) > l: print -1 return lo = 0 hi = 10000 while lo + 1 < hi: mid = (lo + hi) / 2 c = 0 for x in d.itervalues(): c += (x + mid - 1...
335
B
Palindrome
Given a string $s$, determine if it contains any palindrome of length exactly $100$ as a \textbf{subsequence}. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of $s$ and is as long as possible.
There's a well known $O(n^{2})$ solution that allows one to find a longest subsequence of a string which is a palindrome: for every pair of positions $l$ and $r$, such that $l \le r$, find the length $d$ of the longest palindrome subsequence between those positions. d[l][r] = max(d[l][r-1], d[l + 1][r], s[l] == s[r] ...
[ "constructive algorithms", "dp" ]
1,900
#include <string> #include <vector> #include <algorithm> #include <cmath> #include <set> #include <queue> #include <map> #include <cstdio> #include <iomanip> #include <sstream> #include <iostream> #include <cstring> #define REP(i,x,v)for(int i=x;i<=v;i++) #define REPD(i,x,v)for(int i=x;i>=v;i--) #define FOR(i,v)for(int...
335
C
More Reclamation
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land. The river area can be represented by a grid with $r$ rows and exactly two columns — each cell represents a rectangular area. The rows are numbere...
The most straightforward way to solve this problem is to use Grundy numbers. Define a segment as a maximal range of rows in which no cells have been reclaimed. Since segments have no bearing on other segments, they can be assigned Grundy numbers. There are 4 types of segments: The entire river. A section of river conta...
[ "games" ]
2,100
#include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <ctime> #include <cmath> #include <algorithm> #include <string> #include <vector> #include <deque> #include <queue> #include <list> #include <set> #include <map> #include <iostream> #define pb push_back #define mp make_pair #define TA...
335
D
Rectangles and Square
You are given $n$ rectangles, labeled 1 through $n$. The corners of rectangles have integer coordinates and their edges are parallel to the $Ox$ and $Oy$ axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task i...
Even though constraints were allowing O(k^2) solutions, in this editorial we will describe an O(n log(n)) solution. This problem has a rather long solution, involving several very different ideas: On the first step, for every rectangle we want to determine, if we were to consider this rectangle as the top left corner o...
[ "brute force", "dp" ]
2,400
#include <stdio.h> #include <assert.h> #include <map> #include <vector> #include <algorithm> using namespace std; const int maxn = 100005; const int maxt = 131072 * 2; const int rright = 131072; struct square_t; int n; struct point_t { point_t(int _x, int _y) : x(_x), y(_y), r(-1), l(-1), t(-1), b(-1) { ...
335
E
Counting Skyscrapers
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between $2$ and $314!$ (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height $i$ having probability $2^{ - i}$ for all positive integers $i$. The f...
The skyscrapers in this problem depict a data structure called Skip List. Skip list is similar to AVL and red black trees in a sense that it allows O(log N) insertions, deletions and searches (including searching for lower and upper bounds), as well as moving to the next element in sorted order in constant time. Skipli...
[ "dp", "math", "probabilities" ]
2,800
#include <cstdio> using namespace std; int main() { char name[9]; int N, H; while(scanf("%s %d %d", name, &N, &H)!=EOF) { if(name[0]=='B'){ printf("%d\n", N); continue; } double res=N; double ph=.5, pc=.5; for(int h=1; h<=H; h++){ ...
335
F
Buy One, Get One Free
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
This problem is equivalent to maximizing the total value of items that we can get for free. First, process the items into <#value, #number_of_items_with_that_value> tuples, which means we have #number_of_items_with_that_value items of value #value. Then, sort the tuples in descending order of #value. Iterate over those...
[ "dp", "greedy" ]
3,000
#include <cstdio> #include <algorithm> #include <map> #include <set> #include <vector> #include <numeric> using namespace std; int main() { int N; scanf("%d", &N); long long basecost=0; map<int, int> vals; for(int i=0; i<N; i++){ int val; scanf("%d", &val); vals[val]++; ...
336
A
Vasily the Bear and Triangle
Vasily the bear has a favorite rectangle, it has one vertex at point $(0, 0)$, and the opposite vertex at point $(x, y)$. Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point $B = (0, 0)$. That's why today he asks ...
$val = |x| + |y|$. Then first point is $(val * sign(x), 0)$, second - $(0, val * sign(y))$. Swap points if needed according to statement. Let's see why this is the answer. Conditions $x \neq 0$ and $y \neq 0$ give us that one point is on X-axis, and the other on Y-axis. Let's see how it works for $x > 0$ and $y > 0...
[ "implementation", "math" ]
1,000
#include <cstdio> #include <utility> #include <cmath> using namespace std; int sgn(int x) { if (x > 0) return 1; if (x == 0) return 0; return -1; } int main() { int x, y; scanf("%d %d", &x, &y); int v = abs(x) + abs(y); pair<int,int> f = make_pair(v * sgn(x), 0); pair<int,int> s = make_pair(0, v * sgn(y)); ...
336
B
Vasily the Bear and Fly
One beautiful day Vasily the bear painted $2m$ circles of the same radius $R$ on a coordinate plane. Circles with numbers from $1$ to $m$ had centers at points $(2R - R, 0)$, $(4R - R, 0)$, $...$, $(2Rm - R, 0)$, respectively. Circles with numbers from $m + 1$ to $2m$ had centers at points $(2R - R, 2R)$, $(4R - R, 2R)...
Also you could iterate circles, adding distance for each of them and dividing by $m^{2}$ in the end. Let's see how the $i$-th iteration works $1 \le i \le m$. Distance to $m + i$-th circle is $2R$. Distance to $m + j$-th circle, where $|j - i| = 1$, is $R(2+{\sqrt{2}})$. For other circles it's quite simple to calcu...
[ "math" ]
1,900
#include <iostream> #include <string> #include <cstring> #include <cmath> #include <cstdio> using namespace std; int main() { int m, r; scanf("%d%d", &m, &r); double result = 0; for (int i = 0; i < m; ++i) { result += 2; if (i > 0) result += (2 + sqrt(2.)); if (i + 1 < m) result += (2 + sqrt(2.))...
336
C
Vasily the Bear and Sequence
Vasily the bear has got a sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers $b_{1}, b_{2}, ..., b_{k}$ is such maximum non-negative integer $v...
Let's check max beauty from 29 to 0. For every possible beauty $i$ our aim is to find largest subset with such beauty. We will include in this subset all numbers, that have $1$ at $i$-th bit. After that we do bitwise $and$ as in statement, and if the resulting value is divisible by $2^{i}$, then there is the answer. So...
[ "brute force", "greedy", "implementation", "number theory" ]
1,800
#include <cstdio> #include <vector> #include <cassert> using namespace std; vector < int > a, cur, ans; int n, curb, bestb; int main(){ scanf("%d", &n); a.resize(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int bit = 0; bit < 31; bit++) { int totalAnd = (1<<30) - 1; cur.clear(); for(int i = 0; i <...
336
D
Vasily the Bear and Beautiful Strings
Vasily the Bear loves beautiful strings. String $s$ is beautiful if it meets the following criteria: - String $s$ only consists of characters $0$ and $1$, at that character $0$ must occur in string $s$ exactly $n$ times, and character $1$ must occur exactly $m$ times. - We can obtain character $g$ from string $s$ with...
$any$ - random binary string, $s + g$ - concatenation of strings, $MOD = 1000000007$. String $1 + any$ always transforms into $0$, string $1$ - into $1$. String $01 + any$ always transforms into $1$, string $01$ - into $0$. String $001 + any$ transforms into $0$, string $001$ - into $1$, and so on. Using these facts le...
[ "combinatorics", "math", "number theory" ]
2,100
#include <iostream> using namespace std; const int N = 2000000, mod = 1000000007; int cnt[2], target; long long fact[N]; #define forn(i,n) for(int i = 0; i < (int) n; i++) #define sz(a) (int)(a).size() inline bool read() { return (cin >> cnt[0] >> cnt[1] >> target); } inline long long bpow(long long v, int power...
336
E
Vasily the Bear and Painting Square
Vasily the bear has two favorite integers $n$ and $k$ and a pencil. Besides, he's got $k$ jars with different water color paints. All jars are numbered in some manner from $1$ to $k$, inclusive. The jar number $i$ contains the paint of the $i$-th color. Initially the bear took a pencil and drew four segments on the co...
Pretty tough problem. Consider following DP $dp[lvl][op][cur][type]$ - number of ways to take $op$ triangles, if we have $2lvl + 1$ squares. $cur, type$ - auxiliary values. Answer will be $dp[n][k][0][2]k!$. $type$ means type of transitions we make. $cur$ - amount of used quarters ($cur = 4$ - 2 quarters, $cur < 4$ - $...
[ "bitmasks", "combinatorics", "dp", "implementation" ]
2,700
#include <stdio.h> #include <memory.h> const int MOD = 1000000007, N = 205, K = 10; int dp[N][N][5][3], C[K][K], con[5], get[5], fact = 1, n, k; inline void add(int &v1, int v2) { v1 += v2; if (v1 >= MOD) v1 -= MOD; } inline int mul(int v1, int v2) { long long res = v1; res *= v2; return (res % MOD); } int ...
337
A
Puzzles
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her $n$ students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often od...
First, let's sort the numbers f[i] in ascending order. Now assume that the smallest jigsaw puzzle which the teacher purchases consists of f[k] pieces. Obviously, she should buy the smallest n puzzles which are of size f[k] or greater to minimize the difference. These are the puzzles f[k], f[k+1], ..., f[k+n-1] (this is...
[ "greedy" ]
900
null
337
B
Routine Problem
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio $a$:$b$. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio $c$:$d$. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on ...
Suppose that the width and height of the screen are W and H correspondingly. Since W:H = a:b, we have H=W*b/a. Similarly, the width and height of the film frame w and h are related as h=w*d/c. Imagine that Manao stretches/constricts the frame until it fits the screen horizontally or vertically, whichever happens first....
[ "greedy", "math", "number theory" ]
1,400
null
337
C
Quiz
Manao is taking part in a quiz. The quiz consists of $n$ consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectl...
Assume that Manao has doubled his score (i.e. gave k consecutive correct answers) exactly X times. Then the least possible score is obtained when this doublings happen in the beginning of the game, i.e., when he answers the first X*k questions and never manages to answer k consecutive questions after that. The correctn...
[ "binary search", "greedy", "math", "matrices", "number theory" ]
1,600
null
337
D
Book of Evil
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains $n$ settlements numbered from 1 to $n$. Moving through the swamp is very difficult, so people tramped exactly $n - 1$ paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possibl...
Obviously, in graph theory language our problem is: given a tree with n vertices, m of which are marked, find the number of vertices which are at most distance d apart from each of the marked vertices. Let us hang the tree by some vertex r, that is, assume that it is a rooted tree with root in vertex r. Let us also rep...
[ "dfs and similar", "divide and conquer", "dp", "trees" ]
2,000
null
337
E
Divisor Tree
A divisor tree is a rooted tree that meets the following conditions: - Each vertex of the tree contains a positive integer number. - The numbers written in the leaves of the tree are prime numbers. - For any inner vertex, the number within it is equal to the product of the numbers written in its children. Manao has $...
Let us first show that in an optimal divisor tree only the root or a leaf can hold a value other than one of a[i]. Suppose that we have an inner vertex different from the root which holds a number X not equal to any of a[i]. Then we can exclude this vertex from the tree and tie its children to its parent without violat...
[ "brute force", "number theory", "trees" ]
2,200
null
338
D
GCD Table
Consider a table $G$ of size $n × m$ such that $G(i, j) = GCD(i, j)$ for all $1 ≤ i ≤ n, 1 ≤ j ≤ m$. $GCD(a, b)$ is the greatest common divisor of numbers $a$ and $b$. You have a sequence of positive integer numbers $a_{1}, a_{2}, ..., a_{k}$. We say that this sequence occurs in table $G$ if it coincides with consecut...
Observation 1. If the sequence a occurs in table G, then it should occur in row i = LCM(a[1], ..., a[k]). The proof follows. It is clear that theoretically it may only occur in rows with numbers which are multiple to i, since the row number should divide by each of a[index]. Consider some a row with number i*x, where x...
[ "chinese remainder theorem", "math", "number theory" ]
2,900
null
338
E
Optimize!
Manao is solving a problem with the following statement: He came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem: \begin{verbatim} getAnswer(a[1..n], b[1..len], h) answer = 0 for i = 1...
Decyphering Manao's pseudocode, we unearth the following problem: you are given arrays a[1..n] and b[1..len] and a number h. Consider each subarray of a of length L. Let us call it s. Count how many of them have the property that the elements of b can be shuffled in such a way that each sum s[i]+b[i] (1<=i<=L) is at le...
[ "data structures" ]
2,600
null
339
A
Helpful Maths
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
To solve this problem we can count the number of digits 1, 2 and 3 in the input. If there are $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Then we must print the sequence of $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Digits must be separated by + sign.
[ "greedy", "implementation", "sortings", "strings" ]
800
null
339
B
Xenia and Ringroad
Xenia lives in a city that has $n$ houses built along the main ringroad. The ringroad houses are numbered 1 through $n$ in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got $m$ things to do. In order to complete...
To solve this problem we must learn how to calculate fast enought the time, needed to travel between houses $a$ and $b$. Let's consider the case when $a \le b$. Than Xenia needs $b - a$ seconds to get from $a$ to $b$. Otherwise $a > b$, Xenia will have to go thought house number 1. So she will need $n - a + b$ second...
[ "implementation" ]
1,000
null
339
C
Xenia and Weights
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes ...
Let's consider the definition of balance. Balance is the difference between sum of all weights on the left pan and sum of all weights on the right pan. At the beginning balance is equal to 0. Att each step Xenia puts one weight on the pan. It means she adds to or substracts from balance integer from 1 to 10. In each od...
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "greedy", "shortest paths" ]
1,700
null
339
D
Xenia and Bit Operations
Xenia the beginner programmer has a sequence $a$, consisting of $2^{n}$ non-negative integers: $a_{1}, a_{2}, ..., a_{2^{n}}$. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value $v$ for $a$. Namely, it takes several iterations to calculate value $v$. A...
The problem could be solved by using a typical data structure (segment tree). The leafs of the segment tree will store the values of $a_{i}$. At the vertices, the distance from which to the leafs is 1, we will store OR of the numbers from the leafs, which are the sons of this node in the segment tree. Similarly, vertic...
[ "data structures", "trees" ]
1,700
null
339
E
Three Swaps
Xenia the horse breeder has $n$ $(n > 1)$ horses that stand in a row. Each horse has its own unique number. Initially, the $i$-th left horse has number $i$. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, $...$, $n$. Xenia trains horses before the performance. During...
We will call the command $l, r$ a reverse, also we will call the row of horses an array. Suddenly, right? The problem can be solved with clever bruteforcing all possible ways to reverse an array. To begin with, assume that the reverse with $l = r$ is ok. Our solution can find an answer with such kind of reverses. It is...
[ "constructive algorithms", "dfs and similar", "greedy" ]
2,700
null
340
A
The Wall
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered $1$, $2$, $3$ and so on. Iahub has the following scheme of painting: he skips $x - 1$ consecutive bricks, then he paints...
You are given a range $[A, B]$. You're asked to compute fast how many numbers in the range are divisible by both $x$ and $y$. I'll present here an $O(log(max(x, y))$ solution. We made tests low so other not optimal solutions to pass as well. The solution refers to the original problem, where $x, y \le 10^{9}$. Firstl...
[ "math" ]
1,200
#include <stdio.h> int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } int solve(int x, int y, int uppBound) { long long lcm = 1LL * x * y; lcm = lcm / gcd(x, y); return uppBound / lcm; } int main() { int x, y, A, B; scanf("%d%d%d%d", &x, &y, &A, &B); prin...
340
B
Maximal Area Quadrilateral
Iahub has drawn a set of $n$ points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is o...
I want to apologize for not estimating the real difficulty of this task. It turns out that it was more complicated than we thought it might be. Let's start explanation. Before reading this, you need to know what is signed area of a triangle (also called cross product or ccw function). Without it, this explanation will ...
[ "brute force", "geometry" ]
2,100
#include <stdio.h> #include <algorithm> #define eps 0.00000001 #define x first #define y second #define point pair <int, int> using namespace std; point x[301]; inline double ccw(point A, point B, point C) { return ((double)(B.x - A.x) * (C.y - B.y) - (B.y - A.y) * (C.x - B.x)) * 0.5; } inline double chmax(...
340
C
Tourist Problem
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are $n$ destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The $n$ destinations are described by a non-negative integers sequence $a_{1}$, $a_{2}$, ..., $a_{n}$. The num...
Despite this is a math task, the only math formula we'll use is that number of permutations with $n$ elements is $n!$. From this one, we can deduce the whole task. The average formula is sum_of_all_routes / number_of_routes. As each route is a permutation with n elements, number_of_routes is $n!$. Next suppose you have...
[ "combinatorics", "implementation", "math" ]
1,600
#include <stdio.h> #include <algorithm> #define ll long long using namespace std; int x[100010]; ll gcd(ll A, ll B) { if (B == 0) return A; return gcd(B, A % B); } int main() { int n; ll sum1 = 0, sum2 = 0, sumBefore = 0, sumtot = 0; scanf("%d", &n); for (int i = 1; i <= n; ++i) ...
340
D
Bubble Sort Graph
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with $n$ elements $a_{1}$, $a_{2}$, ..., $a_{n}$ in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it $G$) initially has $n$ vertices and 0 edges. During Bubble Sort exec...
A good way to approach this problem is to notice that you can't build the graph. In worst case, the graph will be built in $O(N^{2})$ complexity, which will time out. Also, notice that "maximal independent set" is a NP-Hard task, so even if you can build the graph you can't continue from there. So, the correct route to...
[ "binary search", "data structures", "dp" ]
1,500
null
340
E
Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
In this task, author's intended solution is an O(N ^ 2) dp. However, during testing Gerald fount a solution using principle of inclusion and exclusion. We've thought to keep both solutions. We're sorry if you say the problem was well-known, but for both me and the author of the task, it was first time we saw it. Dynami...
[ "combinatorics", "math" ]
2,000
#include <string> #include <vector> #include <algorithm> #include <cmath> #include <set> #include <queue> #include <map> #include <cstdio> #include <iomanip> #include <sstream> #include <iostream> #include <cstring> #define REP(i,x,v)for(int i=x;i<=v;i++) #define REPD(i,x,v)for(int i=x;i>=v;i--) #define FOR(i,v)for(int...
341
D
Iahub and Xors
Iahub does not like background stories, so he'll tell you exactly what this problem asks you for. You are given a matrix $a$ with $n$ rows and $n$ columns. Initially, all values of the matrix are zeros. Both rows and columns are 1-based, that is rows are numbered 1, 2, ..., $n$ and columns are numbered 1, 2, ..., $n$....
The motivation of the problem is that x ^ x = 0. x ^ x ^ x \dots ^ x (even times) = 0 Update per range, query per element When dealing with complicated problems, it's sometimes a good idea to try solving easier versions of them. Suppose you can query only one element each time (x0 = x1, y0 = y1). To update a submatrix...
[ "data structures" ]
2,500
#include <stdio.h> int n; long long F[4][1024][1024]; inline int lsb(int X) { return X & -X; } int parity(int x0, int y0) { int res = 0; if (x0 % 2) res += 1; if (y0 % 2) res += 2; return res; } long long query(int x0, int y0) { long long res = 0; int which = parity(x...
341
E
Candies Game
Iahub is playing an uncommon game. Initially, he has $n$ boxes, numbered 1, 2, 3, $...$, $n$. Each box has some number of candies in it, described by a sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$. The number $a_{k}$ represents the number of candies in box $k$. The goal of the game is to move all candies into \textbf{exa...
Key observation Suppose you have 3 boxes containing A, B, C candies (A, B, C all greater than 0). Then, there will be always possible to empty one of boxes using some moves. Proof We can suppose that A <= B <= C. We need some moves such as the minimum from A, B, C will be zero. If we always keep the numbers in order A ...
[ "constructive algorithms", "greedy" ]
3,000
#include <stdio.h> #include <vector> #include <algorithm> #define mp make_pair #define x first #define y second #define pi pair <int, int> using namespace std; pi goodA, goodB, x[1024]; vector <pi> ans; void emptyOneBox(pi A, pi B, pi C) { if (A.x > B.x) swap(A, B); if (A.x > C.x) swap(A, ...
342
A
Xenia and Divisors
Xenia the mathematician has a sequence consisting of $n$ ($n$ is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three $a, b, c$ the following conditions held: - $a < b < c$; - $a$ divides $b$, $b$ divides $c$. Naturally, Xen...
In this problem you should guess that exists only three valid groups of three 1) 1, 2, 4 2) 1, 2, 6 3) 1, 3, 6 (You can see that integers 5 and 7 are bad). So, we will greedy take these groups of three. If some integers will be not used, the answer is -1. In other case, print found answer.
[ "greedy", "implementation" ]
1,200
null
342
B
Xenia and Spies
Xenia the vigorous detective faced $n$ $(n ≥ 2)$ foreign spies lined up in a row. We'll consider the spies numbered from 1 to $n$ from left to right. Spy $s$ has an important note. He has to pass the note to spy $f$. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can ...
The problem is solved by greedy algorithm. We will pass the note only in correct direction. Also, if we can pass the note at the current moment of time, we do it. In other case, we will hold it and don't give it to neighbors (we can make this action at any moment of time). Obviously this algorithm is correct. You shoul...
[ "brute force", "greedy", "implementation" ]
1,500
null
342
C
Cupboard and Balloons
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius $r$ (the cupboard's top) and two walls of height $h$ (the cupboard's sides). The cupboard's depth is $r$, that is, it looks like a rectangle with base $r$ and height $h + r$ from the sides. The figure below ...
In the problem you should carefully get formula. The optimal solution put marbles by two in a row. And then put one marble upon others if it possible. The most difficulties were to deal with this last phase. In comments to the post were given formulas how to put the last marble (exactly in the middle). And there was a ...
[ "geometry" ]
1,900
null
342
D
Xenia and Dominoes
Xenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles. A puzzle is a $3 × n$ table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets the fo...
In the problem you can count number of correct puzzles or substract number of incorrect puzzles from number of all puzzles. In any case you should count DP, where the state is $(j, mask)$ - $j$ - number of the last full column, $mask$ - mask of the last column. This problem is equivalent to the well known problem about...
[ "bitmasks", "dfs and similar", "dp" ]
2,100
null
342
E
Xenia and Tree
Xenia the programmer has a tree consisting of $n$ nodes. We will consider the tree nodes indexed from 1 to $n$. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes $v$ and $u$ is the number of edges in the shortest path between...
The problem can be solved in different ways. The most easy idea is sqrt-optimization. Split all queries into $sqrt(m)$ blocks. Each block we will process separately. Before processing each block, we should calculate minimum distances from every node to the closest red node using bfs. To answer the query we should updat...
[ "data structures", "divide and conquer", "trees" ]
2,400
null
343
A
Rational Resistance
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance $R_{0} = 1$. Elements with other resistance can be constructed from these resistors. In this problem, we wi...
If a fraction $\overset{\stackrel{\rightarrow}}{b}$ can be obtained with $k$ resistors, then it is simple to calculate that we can obtain fractions $\frac{a+b}{b}$ and $\frac{a}{a+b}$ with $k + 1$ resistors. So adding one resistor means performing one operation backwards in Euclidean algorithm. That means that the answ...
[ "math", "number theory" ]
1,600
null
343
B
Alternating Current
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
Let us solve the following problem first: we are given a string of symbols A and B. If the $i$-th symbol is $A$, then at the $i$-th step the upper wire (see figure) is being put over the lower wire. If the $i$-th symbol is $B$, the lower wire is being put over the upper wire at $i$-th step. Observe that if some two sym...
[ "data structures", "greedy", "implementation" ]
1,600
null
343
C
Read Time
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but $n$ different heads that can read data in parallel. When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In t...
Let's search the answer $t$ with the binary search. Fix some value of $t$. Look at the first head from the left $h[i]$ that can read track $p[0]$. If $p[0] > h[i]$, then $h[i]$ goes to the right $t$ seconds and reads all tracks on its way. Otherwise if $p[0] \le h[i]$, then the head has two choices: Obviously, for $h...
[ "binary search", "greedy", "two pointers" ]
1,900
null
343
D
Water Tree
Mad scientist Mike has constructed a rooted tree, which consists of $n$ vertices. Each vertex is a reservoir which can be either empty or filled with water. The vertices of the tree are numbered from 1 to $n$ with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of ...
Let's learn how to color a whole subtree. For that enumerate all vertices in post-order DFS. Then each subtree covers a single continious vertex number segment. For each vertex we store the bounds of such segment for a subtree with a root in this vertex. Then to color a subtree means to color a segment in a segment tre...
[ "data structures", "dfs and similar", "graphs", "trees" ]
2,100
null
343
E
Pumping Stations
Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations. The system consists of $n$ pumping stations, which are numbered by integers from 1 to $n$. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at...
In this problem we are asked to find such graph vertex permutation that maximizes the sum of the maximum flows sent between each two consequtive vertices in the permutation. The problem can be solved with Gomory-Hu tree data structure. For a given weighted graph the tree has the following properties: Surprisingly, such...
[ "brute force", "dfs and similar", "divide and conquer", "flows", "graphs", "greedy", "trees" ]
2,900
null
344
A
Magnets
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
By the definition each block consists of a number of consequent and equally oriented dominoes. That means that in places where adjacent dominoes are not oriented equally, one block ends and another block starts. So, if there are $x$ such places, the answer is equal to $x + 1$. Solution complexity: $O(n)$.
[ "implementation" ]
800
null
344
B
Simple Molecules
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule. A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form \te...
First solution. First, the sum $a + b + c$ should be even, since each bond adds 2 to the sum. Now let $x$, $y$, $z$ be the number of bonds between 1st and 2nd, 2nd and 3rd, 3rd and 1st atoms, accordingly. So we have to solve the system $x + z = a$, $y + x = b$, $z + y = c$. Now observe that the solution to the system i...
[ "brute force", "graphs", "math" ]
1,200
null
346
A
Alice and Bob
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of $n$ distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two ...
First, no matter what happend, the number set we get at the very endding will be same all the time. Let's say $d = gcd{x_{i}$}. Then the set in the endding will be some things like {$d$, $2d$, $3d$, ... $max{x_{i}$}}. So there is always $max{x_{i}} / d$ - $n$ rounds. And what we should do rest is to check the parity of...
[ "games", "math", "number theory" ]
1,600
null
346
B
Lucky Common Subsequence
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri...
This is a rather classical problem, let's say if there is no virus, then it is the classical **LCS ** problem. You can solve this by a $O(n^{2})$ dynamic programing. When consider about the virus, we should add 1 more dimension on the state to trace the growth of the virus. It can be done by wheather Aho-Corasick autom...
[ "dp", "strings" ]
2,000
null
346
C
Number Transformation II
You are given a sequence of positive integers $x_{1}, x_{2}, ..., x_{n}$ and two non-negative integers $a$ and $b$. Your task is to transform $a$ into $b$. To do that, you can perform the following moves: - subtract 1 from the current $a$; - subtract $a$ mod $x_{i}$ $(1 ≤ i ≤ n)$ from the current $a$. Operation $a$ m...
I bet there is a few people know the greedy method even if he/she have solved the early version before. Codeforces #153 Div 1. Problem C. Number Transformation Let dp[k] denotes the minimum number of steps to transform b+k to b. In each step, you could only choose i which makes b+k-(b+k) mod x[i] minimal to calc dp[k]....
[ "greedy", "math" ]
2,200
null
346
D
Robot Control
The boss of the Company of Robot is a cruel man. His motto is "Move forward Or Die!". And that is exactly what his company's product do. Look at the behavior of the company's robot when it is walking in the directed graph. This behavior has been called "Three Laws of Robotics": - Law 1. The Robot will destroy itself w...
Let's dp from t to s. dp[u] = min(min(dp[v]) + 1 , max(dp[v])) | u->v Here dp[u] means, the minimum number of orders mzry1992 needs to send in the worst case. The left-hand-side is sending order while the right-hand side is not. At the beginning, we have dp[t] = 1, and dp[s] will be the answer. We can see there is circ...
[ "dp", "graphs", "shortest paths" ]
2,600
#include <cstdio> #include <vector> #include <memory.h> using namespace std; const int MX=1000100,MD=2*MX; int n,m,i,j,k,x,y,z,fi,fr,v[MX],p[MX],q[2*MD]; vector<int> g[MX],o[MX]; bool u[MX]; int main() { scanf("%d%d",&n,&m); for (i=0; i<m; i++) { scanf("%d%d",&x,&y); g[x].push_back(y); o[y].push_back(x); v[x...
346
E
Doodle Jump
\underline{In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. — Wikipedia.} It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't r...
Take $a$ =5, $p$ =23 for example ... Divided the numbers in group. 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16 21 3 8 13 18We start a new group when the number > P We found the difference between the elements of the first group is 5, The subsequent is filling some gap between the them ... After some observation we co...
[ "math", "number theory" ]
3,000
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ publi...
348
A
Mafia
One day $n$ friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other $n - 1$ people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the $i$-th person wants to play $a_{i}$ rounds. What is the mini...
In the problem you need to find out how many games you need to play in order to make all people happy. It means that each of them played as many games as he wanted. Let the answer be $x$ games. Notice that $max(a_{1}, a_{2}, \dots , a_{n}) \le x$. Then $i$-th player can be game supervisor in $x-a_{i}$ games. If we s...
[ "binary search", "math", "sortings" ]
1,600
null
348
B
Apple Tree
You are given a rooted tree with $n$ vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf. A tree is ...
In the problem you need to find out minimal number of apples that you need to remove in order to make tree balanced. Notice, that if we know the value in the root then we know values in all other vertices. The value in the leaf is equal to the value in the root divided to the product of the powers of all vertices on th...
[ "dfs and similar", "number theory", "trees" ]
2,100
null
348
C
Subset Sums
You are given an array $a_{1}, a_{2}, ..., a_{n}$ and $m$ sets $S_{1}, S_{2}, ..., S_{m}$ of indices of elements of this array. Let's denote $S_{k} = {S_{k, i}} (1 ≤ i ≤ |S_{k}|)$. In other words, $S_{k, i}$ is some element from set $S_{k}$. In this problem you have to answer $q$ queries of the two types: - Find the ...
This problem is about data structures. First step of the solution is to divide sets to heavy and light. Light ones are those that contains less than $\sqrt{n}$ elements. All other sets are heavy. Key observation is that every light set contains less than $\sqrt{n}$ elements and number of heavy sets doesn't exceed $\sqr...
[ "brute force", "data structures" ]
2,500
null
348
D
Turtles
You've got a table of size $n × m$. We'll consider the table rows numbered from top to bottom 1 through $n$, and the columns numbered from left to right 1 through $m$. Then we'll denote the cell in row $x$ and column $y$ as $(x, y)$. Initially cell $(1, 1)$ contains two similar turtles. Both turtles want to get to cel...
In the problem you're asked to find the number of pairs of non-intersecting paths between left upper and right lower corners of the grid. You can use following lemma for that. Thanks to rng_58 for the link. More precisely, considering our problem, this lemma states that given sets of initial $A = {a1, a2}$ and final $B...
[ "dp", "matrices" ]
2,500
null
348
E
Pilgrims
A long time ago there was a land called Dudeland. Dudeland consisted of $n$ towns connected with $n - 1$ bidirectonal roads. The towns are indexed from $1$ to $n$ and one can reach any city from any other city if he moves along the roads of the country. There are $m$ monasteries in Dudeland located in $m$ different tow...
Let's build a simple solution at first and then we will try to improve it to solve problem more effectively given the constraints. For every vertex let's find the list of the farthest vertices. Let's find vertices on the intersection of the paths between current vertex and each vertex from the list that don't contain m...
[ "dfs and similar", "dp", "trees" ]
2,800
null
349
A
Cinema Line
The new "Die Hard" movie has just been released! There are $n$ people at the cinema box office standing in a huge line. Each of them has a single $100$, $50$ or $25$ ruble bill. A "Die Hard" ticket costs $25$ rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and...
In the problem you need to decide whether cashier can give a change to all customers if the price of the ticket is 25 rubles and there's 3 kinds of bills: 25, 50 and 100 rubles. There's no money in the ticket office in the beginning. Let's consider 3 cases. Customer has 25 rubles hence he doesn't need a change. Custome...
[ "greedy", "implementation" ]
1,100
null
349
B
Color the Fence
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get $v$ liters of paint. He did the math and concluded that digit $d$...
In the problem you're asked to write the largest possible number given number of paint that you have and number of paint that you need to write each digit. Longer number means larger number so it's worth to write the longest possible number. Because of that we choose the largest digit among those that require the least...
[ "data structures", "dp", "greedy", "implementation" ]
1,700
null
350
A
TL
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written $n$ correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote $m$ wrong solutions and for each wrong solution he knows its running ...
Let's $v = min(a_{i}), p = max(a_{i}), c = min(b_{i})$. So, if $max(2 * v, p) < c$, then answer is $max(2 * v, p)$, else answer is $- 1$.
[ "brute force", "greedy", "implementation" ]
1,200
#include <cstdio> #include <algorithm> using namespace std; const int N = 300 + 5; int n, m, a[N], b[N]; int main() { scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < m; i++) scanf("%d", &b[i]); sort(a, a + n); sort(b, b + m); int tmin = 2 * a[0]; ...
350
B
Resort
Valera's finally decided to go on holiday! He packed up and headed for a ski resort. Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has $n$ objects (we will consider the objects indexed in some way by integers from $1$ to $n$), eac...
Input data represents a graph, by using a array of parents of every vertex. Because every vertex has at most one parent, we can use following solution: we will go up to parent of vertex $v$ ($prev[v]$) until not found vertex with the outcome degree $ \ge 2$. It is better to calculate outcome degrees in advance. After ...
[ "graphs" ]
1,500
#include <cstdio> #include <vector> #include <algorithm> #include <iostream> using namespace std; const int N = 1000 * 100 + 5; int type[N], prev[N]; int cntFrom[N]; int n; inline bool read() { if (!(cin >> n)) return false; for(int i = 0; i < n; i++) scanf("%d", &type[i]); for(int i = 0; i < n; ...
350
C
Bombs
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains $n$ bombs, the $i$-th bomb is at point with coordinates $(x_{i}, y_{i})$. We know that no two bombs are at the same point and that no bomb is at point with coordinates $(0, 0)$. Initially, the robot is at point w...
First of all, Let's sort all point by increasing of value $|x_{i}| + |y_{i}|$, all points we will process by using this order. We will process each point greedily, by using maximum six moves. Now we want to come to the point $(x, y)$. Let's $x \neq 0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x ...
[ "greedy", "implementation", "sortings" ]
1,600
import java.io.IOException; import java.util.Arrays; import java.io.UnsupportedEncodingException; import java.util.InputMismatchException; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in ...
350
D
Looking for Owls
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain $n$ distinct segments and $m$ distinct circles. We will consider the segments indexed from $1$ to $n$ in some way and the circles — indexed from $1$ to $m$ in some way. Palpatine defines an owl as a ...
It's possible to solve this problem by using only integer calculations. Normalization of the line $Ax + By + C$ is following operation: we multiply our equation on the value $\textstyle{\frac{\theta m}{\theta}}$, where $g = gcd(A, gcd(B, C))$, if $A < 0$ $(orA = 0andB < 0)$ then $sgn$ equals to $- 1$, else sgn equals t...
[ "binary search", "data structures", "geometry", "hashing", "sortings" ]
2,400
#define _CRT_SECURE_NO_DEPRECATE #define _USE_MATH_DEFINES #include <algorithm> #include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include <cassert> #include <climits> #include <ctime> #include <cstring> #include <cmath> #include <iomanip> #include <utility> #include <complex> #include <vect...
350
E
Wrong Floyd
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it. Valera's already written the code that counts the shortest distance between any pair of vertexes in a \textbf{non-directed connected graph} from $n$ vertexes and $m$ ...
Let's do the following: construct the graph with the maximum possible number of edges and then remove the excess. First of all, you can notice that if $k = n$ answer is $- 1$. Else let's fix some marked vertex, for example $a_{1}$. Let's put in our graph all edges except edges beetween $a_{1}$ and $x$, where $x$ - an a...
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
2,200
#include <cstdio> #include <algorithm> #include <vector> using namespace std; const int N = 300 + 5; int n, m, ok, a[N], used[N]; inline bool read() { if (scanf("%d %d %d", &n, &m, &ok) != 3) return false; for(int i = 0; i < ok; i++) scanf("%d", &a[i]), a[i]--; sort(a, a + ok); return true; } ...
351
A
Jeff and Rounding
Jeff got $2n$ real numbers $a_{1}, a_{2}, ..., a_{2n}$ as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes $n$ operations, each of them goes as follows: - choose indexes $i$ and $j$ $(i ≠ j)$ that haven't been chosen yet...
Initially, we should remember the number of integers - $C$. On next step we will round down all numbers and count the sum. Now we can change the sum, rounding up some numbers, with those not matter what kind of, the main thing - how many. Consider a couple what we could get: 1. $(int, int)$ $(c_{1})$ 2. $(int, double)$...
[ "dp", "greedy", "implementation", "math" ]
1,800
null
351
B
Jeff and Furik
Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of $n$ numbers: $p_{1}$, $p_{2}$, $...$, $p_{n}$. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff...
ote that after each step, the number of inversions in the permutation is changed by 1. Let us turn to the inversions of the permutation - let them be $I$ pcs. It is clear that when we have one inversion, then the answer - $1$. Now we will see how to use it further: 1. it is clear that after a Jeff's step inversions wil...
[ "combinatorics", "dp", "probabilities" ]
1,900
null
351
C
Jeff and Brackets
Jeff loves regular bracket sequences. Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of $nm$ brackets. Let's number all brackets of this sequence from $0$ to $nm$ - $1$ from left to right. Jeff knows that he is going to spend $a_{i mod n}$ liters of ink on the $i$-t...
How to solve the problem for small $NM$? Just use the dynamic programming $dp_{i, j}$ - minimum cost to build $i$ first brackets with the balance $j$. Transfers are simple: 1. $dp_{i, j} + a_{i + 1}$ -> $dp_{i + 1, j + 1}$ 2. $dp_{i, j} + b_{i + 1}$ -> $dp_{i + 1, j - 1}$ 3. we make transfers only when balance will be ...
[ "dp", "matrices" ]
2,500
null
351
D
Jeff and Removing Periods
Cosider a sequence, consisting of $n$ integers: $a_{1}$, $a_{2}$, $...$, $a_{n}$. Jeff can perform the following operation on sequence $a$: - take three integers $v$, $t$, $k$ $(1 ≤ v, t ≤ n; 0 ≤ k; v + tk ≤ n)$, such that $a_{v}$ = $a_{v + t}$, $a_{v + t}$ = $a_{v + 2t}$, $...$, $a_{v + t(k - 1)}$ = $a_{v + tk}$; - r...
After the first request we can sort the numbers and for further moves will be able to remove all occurrences of a certain number. So the answer is the number of different numbers + 1 if there is no number, occurrence of which form an arithmetic progression. Number of different numbers on a segment - standart problem, c...
[ "data structures" ]
2,700
null
351
E
Jeff and Permutation
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence $p_{1}, p_{2}, ..., p_{n}$ for his birthday. Jeff hates inversions in sequences. An inversion in sequence $a_{1}, a_{2}, ..., a_{n}$ is a pair of indexes $i, j$ $(1 ≤ i < j ≤ n)$, such that an inequal...
We make the zero step, replace the elements on their modules. The first thing you need to understand the way in which we will build our response. After selecting a few ways to understand the fact that initially you need to determine the sign of the largest numbers. Consider the case where the current step we have only ...
[ "greedy" ]
2,200
null
352
A
Jeff and Digits
Jeff's got $n$ cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that numbe...
Solution is looking for few cases: 1. If we do not have zeros, then the answer is -$1$. 2. If we have less than $9$ fives, then the answer is $0$. 3. Otherwise, the answer is: 4. 1. The maximum number of fives divisible by $9$ 4. 2. All zeros, we have
[ "brute force", "implementation", "math" ]
1,000
null
352
B
Jeff and Periods
One day Jeff got hold of an integer sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$ of length $n$. The boy immediately decided to analyze the sequence. For that, he needs to find all values of $x$, for which these conditions hold: - $x$ occurs in sequence $a$. - Consider all positions of numbers $x$ in the sequence $a$ (suc...
We will go through the array from left to right. At each step, we will store the arrays: 1. $next_{x}$ - the last occurrence of the number $x$ 2. $period_{x}$ - period, which occurs $x$ 3. $fail_{x}$ - whether a time when the number of $x$ no longer fit Now, when we get a new number we considering the case when it is t...
[ "implementation", "sortings" ]
1,300
null
354
A
Vasya and Robot
Vasya has $n$ items lying in a line. The items are consecutively numbered by numbers from $1$ to $n$ in such a way that the leftmost item has number $1$, the rightmost item has number $n$. Each item has a weight, the $i$-th item weights $w_{i}$ kilograms. Vasya needs to collect all these items, however he won't do it ...
Brute force how many times we will use operation from the left. So, if we use it $k$ times, then it's clear, that we will take first $k$ items by the left operations and last $(n - k)$ items by the right operations. So, robot will spend $sumLeft[k] \cdot l + sumRight[n - k] \cdot r$ energy plus some penalty for the sam...
[ "brute force", "greedy", "math" ]
1,500
null
354
B
Game with Strings
Given an $n × n$ table $T$ consisting of lowercase English letters. We'll consider some string $s$ good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's th...
We will say that cell $(r, c)$ corresponds to a string $s$, if there exist correct path, which ends in the cell $(r, c)$ and this path corresponds to a string $s$. Let call a set of cells which corresponds to some string $s$ a state. One state can correspond to different strings. We can't brute force all possible strin...
[ "bitmasks", "dp", "games" ]
2,400
null
354
C
Vasya and Beautiful Arrays
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers $a$ of length $n$. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately...
The problem was to find greatest $d$, such that $a_{i} \ge d, a_{i} mod d \le k$ holds for each $i$. Let $m = min(a_{i})$, then $d \le m$. Let consider two cases: $m\leq k+1\Rightarrow a_{i}\,m o d\,m\leq m-1\leq k\Rightarrow A n s w e r=m$ $m>k+1\Rightarrow A n s w e r\geq k+1$. In this case we will brute force ...
[ "brute force", "dp", "number theory" ]
2,100
null
354
D
Transferring Pyramid
Vasya and Petya are using an interesting data storing structure: a pyramid. The pyramid consists of $n$ rows, the $i$-th row contains $i$ cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to $\textstyle{\frac{n(n+1)}{2}}$ as shown on the picture ...
This tasks is solvable with dynamic programming. First of all let consider solution with complexity $O(n^{3})$. Let $dp[i][j]$ be the answer for the highlighted in blue part (minimal cost of transferring all special cells that lies inside this area). Then $dp[n][0]$ will be the answer for our original problem. How to r...
[ "dp" ]
2,900
null
354
E
Lucky Number Representation
We know that lucky digits are digits $4$ and $7$, however Vasya's got another favorite digit $0$ and he assumes it also is lucky! Lucky numbers are such \textbf{non-negative} integers whose decimal record only contains lucky digits. For example, numbers $0, 47, 7074$ are lucky, but $1, 7377, 895, $ -$7$ are not. Vasya...
Author's solution, much more complicated than suggested by many participants during the competition, easy solution will be described below. First of all, let write a DP with complexity $O(N * lucky_count(N))$, where $lucky_count(N)$ is the count of lucky numbers $ \le N$, $lucky_count(10^{n}) = 3^{n}$. As we can see, ...
[ "constructive algorithms", "dfs and similar", "dp" ]
2,200
null
355
A
Vasya and Digital Root
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that $S(n)$ is the sum of digits of number $n$, for example, $S(4098) = 4 + 0 + 9 + 8 = 21$. Then the digital root of number $n$ equals to: - $dr(n) = S(n)$, if $S(n) < 10$; - $dr(n) = dr( S(n)...
If $d = 0$, the there is the only number with $d r(x)=0\Leftrightarrow x=0$, so, if $k = 1$, the answer is $0$, otherwise - $No solution$. If $d > 0$, then one of correct numbers is $d \times 10^{k - 1}$. Time complexity: $O(1)$ + $O(k)$ for the output.
[ "constructive algorithms", "implementation" ]
1,100
null
355
B
Vasya and Public Transport
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has $n$ buses and $m$ trolleys, the buses are numbered by integers from $1$ to $n$, the trolleys are numbered by integers from $1$ to $m$. Public transport is not free. There are 4 types of tickets: - A ticket f...
If we buy a ticket of the fourth type, we don't have to buy anything else, so, the answer is $min(c_{4}, answer using tickets of first three types)$. Now, when we don't have ticket of the fourth type, we can solve the task separately for buses and trolleys. Solving the problem only for buses: if we buy a ticket of the ...
[ "greedy", "implementation" ]
1,100
null