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
553
A
Kyoya and Colored Balls
Kyoya Ootori has a bag with $n$ colored balls that are colored with $k$ different colors. The colors are labeled from $1$ to $k$. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color $i$ before drawing the last ball ...
Let $f_{i}$ be the number of ways to solve the problem using only the first $i$ colors. We want to compute $f_{n}$. Initially, we have $f_{1} = 1$, since we only have a single color, and balls of the same color are indistinguishable. Now, to go from $f_{i}$ to $f_{i + 1}$, we note that we need to put at a ball of color...
[ "combinatorics", "dp", "math" ]
1,500
import java.io.*; import java.util.*; public class ColoredBalls { public static int mod = 1000000007; public static int MAXN = 1010; public static void main (String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out, true); long[][] comb = new long[MA...
553
B
Kyoya and Permutation
Let's define the permutation of length $n$ as an array $p = [p_{1}, p_{2}, ..., p_{n}]$ consisting of $n$ distinct integers from range from $1$ to $n$. We say that this permutation maps value $1$ into the value $p_{1}$, value $2$ into the value $p_{2}$ and so on. Kyota Ootori has just learned about cyclic representati...
Solving this requires making the observation that only swaps between adjacent elements are allowed, and all of these swaps must be disjoint. This can be discovered by writing a brute force program, or just noticing the pattern for small $n$. Here's a proof for why this is. Consider the cycle that contains $n$. Since $n...
[ "binary search", "combinatorics", "constructive algorithms", "greedy", "implementation", "math" ]
1,900
import java.io.PrintWriter; import java.util.Scanner; public class PermutationFinder { public static void main (String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter (System.out, true); int N = in.nextInt(); long K = in.nextLong(); long[] fib = new ...
553
C
Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has $n$ characters. The characters are labeled from $1$ to $n$. Every pair of two characters can either mutually love each other or mutually hate each othe...
Let's look at the graph of characters who love each other. Each love-connected component can be collapsed into a single node, since we know that all characters in the same connected component must love each other. Now, we claim that the resulting collapsed graph with the hate edges has a solution if and only if the res...
[ "dfs and similar", "dsu", "graphs" ]
2,200
import java.io.*; import java.util.*; public class OddGraphs { public static int mod = 1000000007; static class Edge { public int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } public static ArrayList<Integer>[] graph; public static ArrayList<Edge> z...
553
D
Nudist Beach
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers. There are $n$ cities, labeled from 1 to $n$, and $m$ bidirectional roads between them. Currently, there are Life Fibers in ev...
The algorithm idea works as follows: Start with all allowed nodes. Remove the node with the smallest ratio. Repeat. Take the best ratio over all iterations. It's only necessary to consider these subsets. Proof for why. We say this process finds a ratio of at least p if and only if there exists a subset with ratio at le...
[ "binary search", "graphs", "greedy" ]
2,300
import java.io.*; import java.util.*; public class GraphRatios { public static ArrayList<Integer>[] graph; public static int[] deg, cur; public static boolean[] vis; public static void main (String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out, ...
553
E
Kyoya and Train
Kyoya Ootori wants to take the train to get to school. There are $n$ train stations and $m$ one-way train lines going between various stations. Kyoya is currently at train station $1$, and the school is at station $n$. To take a train, he must pay for a ticket, and the train also takes a certain amount of time. However...
The Naive solution is $O(MT^{2})$. Let $W_{j}(t)$ be the optimal expected time given we are at node $j$, with $t$ time units left. Also, let $W_{e}(t)$ be the optimal expected time given we use edge $e$ at time $t$. Now, we have $W_{j}(t)=\left\{\operatorname*{su}_{\mathrm{outest~distance~from~j~to~}}N+X\quad\mathrm{if...
[ "dp", "fft", "graphs", "math", "probabilities" ]
3,200
import java.io.*; import java.util.*; public class RandomPaths { public static int N, M, T, X; public static int[][] prob; public static Edge[] e; public static double[][] inp; public static double[][] outp; public static int K; public static double[][][][] tfd; public static double[][] re, im; p...
554
A
Kyoya and Photobooks
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
Solving this problem just requires us to simulate adding every character at every position at the string, and removing any duplicates. For instance, we can use a HashSet of Strings in Java to do this (a set in C++ or Python works as well).
[ "brute force", "math", "strings" ]
900
import java.util.HashSet; import java.util.Scanner; public class MissingLetter { public static void main (String[] args) { Scanner in = new Scanner (System.in); String s = in.next(); HashSet<String> hs = new HashSet<>(); for (int i = 0; i <= s.length(); i++) { for (char c = 'a'; c <= 'z'; c++)...
554
B
Ohana Cleans Up
Ohana Matsumae is trying to clean a room, which is divided up into an $n$ by $n$ grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square,...
For each row, there is only one set of columns we can sweep so it becomes completely clean. So, there are only $n$ configurations of sweeping columns to look at. Checking a configuration takes $O(n^{2})$ time to count the number of rows that are completely clean. There are $n$ configurations in all, so this takes $O(n^...
[ "brute force", "greedy", "strings" ]
1,200
import java.io.PrintWriter; import java.util.Scanner; public class LightMatrix { public static void main (String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter (System.out, true); int N = in.nextInt(); String[] board = new String[N]; for (int i = 0; i < ...
555
A
Case of Matryoshkas
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of $n$ matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from $1$ to $n$. A matryoshka with a smaller number c...
Suppose we don't need to disassemble some sequence of dolls. Then no doll can be inserted into no doll from this chain. So we don't need to disassemble a sequence of dolls only if they are consecutive and start from $1$. Let the length of this chain be $l$. Then we will need to get one doll from another $n - k - l + 1$...
[ "implementation" ]
1,500
null
555
B
Case of Fugitive
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of $n$ narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line...
We can put a bridge between bridges $i$ and $i + 1$ if its length lies in the segment $[l_{i + 1} - r_{i};r_{i + 1} - l_{i}]$. Now we have a well-known problem: there are $n - 1$ segments and $m$ points on a plane, for every segment we need to assign a point which lies in it to this segment and every point can be assig...
[ "data structures", "greedy", "sortings" ]
2,000
null
555
C
Case of Chocolate
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom. A bar of chocolate can be presented as an $n × n$ table, where each cell represents one piece of chocolate. The columns of the table are numbered from $1$ to $n$ from left to right and the row...
Let's solve this problem with two segment trees: we'll keep the lowest eaten piece for each column in one of them and the leftmost eaten piece for each row in another. Suppose we have a query $x$ $y$ $L$. Position where we'll stop eating chocolate is stored in the row segment tree so we can easily find the number of ea...
[ "data structures" ]
2,200
null
555
D
Case of a Top Secret
Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure. However, he needs help conducting one of the investigative experiment. There are $n$ pegs put on a plane, they are numbered from $1$ to $n$, the coordinates of the $i$-th of the...
I call the length of the part of the rope from the weight to the last met peg the active length (denoted as $L_{a}$). After each met peg active length is reduced. Let's process queries separately: at each step we can find next peg with using binary search. If active length becomes at least two times shorter or current ...
[ "binary search", "implementation", "math" ]
2,500
null
555
E
Case of Computer Network
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network. In this network are $n$ vertices, some pairs of vertices are connected by $m$ undirected channels. It is planned to transfer $q$ important messages via this network, the $i$...
First of all, let's reduce this problem to a problem on a tree. In order to achieve this let's orient edges in all biconnected components according to a DFS-order. We'll get a strongly connected component. Suppose it's false. Then this component can be divided into parts $A$ and $B$ such that there's no edge from $B$ t...
[ "dfs and similar", "graphs", "trees" ]
2,800
null
556
A
Case of the Zeros and Ones
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length $n$ consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, an...
If there still exist at least one $0$ and at least one $1$ in the string then there obviously exists either substring $01$ or substring $10$ (or both) and we can remove it. The order in which we remove substrings is unimportant: in any case we will make $min(#zeros, #ones)$ such operations. Thus the answer is $#ones + ...
[ "greedy" ]
900
null
556
B
Case of Fake Numbers
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of $n$ similar gears. Each gear has $n$ teeth containing all numbe...
Notice that after pressing the button $n$ times gears return to initial state. So the easiest solution is to simulate the process of pressing the button $n$ times and if at some step the active teeth sequence is $0, 1, ... , n - 1$ output "Yes" else "No". But this solution can be improved. For instance, knowing the act...
[ "brute force", "implementation" ]
1,100
null
557
A
Ilya and Diplomas
Soon a school Olympiad in Informatics will be held in Berland, $n$ schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the $n$ participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly...
This problem can be solved in the different ways. We consider one of them - parsing cases. If $max_{1} + min_{2} + min_{3} \le n$ then the optimal solution is ($n - min_{2} - min_{3}$, $min_{2}$, $min_{3}$). Else if $max_{1} + max_{2} + min_{3} \le n$ then the optimal solution is ($max_{1}$, $n - max_{1} - min_{3}$...
[ "greedy", "implementation", "math" ]
1,100
null
557
B
Pasha and Tea
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of $w$ milliliters and $2n$ tea cups, each cup is for one of Pasha's friends. The $i$-th cup can hold at most $a_{i}$ milliliters of water. It turned out that among Pasha's friends there are exactly $n$ boys ...
This problem can be solved in different ways too. We consider the simplest solution whici fits in the given restrictions. At first we sort all cups in non-decreasing order of their volumes. Due to reasons of greedy it is correct thatsorted cups with numbers from $1$ to $n$ will be given to girls and cups with numbers f...
[ "constructive algorithms", "implementation", "math", "sortings" ]
1,500
null
557
C
Arthur and Table
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable. In total the table Arthur bought has $n$ legs, the length of the $i$-th leg is $l_{i}$. Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number $...
This problem can be solved as follows. At first we need to sort all legs in non-descending order of their length. Also we need to use array $cnt[]$. Let iterate on length of legs (which will stand table) from the least. Let this lenght is equals to $maxlen$. Count of units of energy which we need for this we will store...
[ "brute force", "data structures", "dp", "greedy", "math", "sortings" ]
1,900
null
557
D
Vitaly and Cycle
After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of $n$ vertices and $m$ edges, no...
To solve this problem we can use dfs which will check every connected component of graph on bipartite. It is clearly that count of edges which we need to add in graph to get the odd cycle is no more than three. Answer to this problem is three if count of edges in graph is zero. Then the number of ways to add three edge...
[ "combinatorics", "dfs and similar", "graphs", "math" ]
2,000
null
557
E
Ann and Half-Palindrome
Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark. On the last theoretical class the teacher introduced the notion of a half-palindrome. String $t$ is a half-palindrome, if for all the odd positions $i$ ($1\leq i\leq{\frac{i|+1}{2}}$) the following condition is held: $t_{i} = t...
This problem can be solved with help of dynamic programming. At first we calculate matrix $good[][]$. In $good[i][j]$ we put $true$, if substring from position $i$ to position $j$ half-palindrome. Else we put in $good[i][j]false$. We can do it with iterating on "middle" of half-palindrome and expanding it to the left a...
[ "data structures", "dp", "graphs", "string suffix structures", "strings", "trees" ]
2,300
null
558
A
Lala Land and Apple Trees
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly $n$ apple trees. Tree number $i$ is located in a position $x_{i}$ and has $a_{i}$ apples growing on it. Amr wants to collect apples from...
Let's divide all the trees into two different groups, trees with a positive position and trees with a negative position. Now There are mainly two cases: If the sizes of the two groups are equal. Then we can get all the apples no matter which direction we choose at first. If the size of one group is larger than the othe...
[ "brute force", "implementation", "sortings" ]
1,100
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numer...
558
B
Amr and The Large Array
Amr has got a large array of size $n$. Amr doesn't like large arrays so he intends to make it smaller. Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subseg...
First observation in this problem is that if the subarray chosen has $x$ as a value that has the maximum number of occurrences among other elements, then the subarray should be $[x, ..., x]$. Because if the subarray begins or ends with another element we can delete it and make the subarray smaller. So, Let's save for e...
[ "implementation" ]
1,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numer...
558
C
Amr and Chemistry
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment. Amr has $n$ different types of chemicals. Each chemical $i$ has an initial volume of $a_{i}$ liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first....
Let the maximum number in the array be $max$. Clearly, changing the elements of the array to any element larger than $max$ won't be optimal, because the last operation is for sure multiplying all the elements of the array by two. And not doing this operation is of course a better answer. Now we want to count the maximu...
[ "brute force", "graphs", "greedy", "math", "shortest paths" ]
1,900
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numer...
558
D
Guess Your Way Out! II
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such t...
First, each query in the level $i$ from $L$ to $R$ can be transmitted into level $i + 1$ from $L * 2$ to $R * 2 + 1$, so, we can transform each query to the last level. Let's maintain a set of correct ranges such that the answer is contained in one of them. At the beginning we will assume that the answer is in the rang...
[ "data structures", "implementation", "sortings" ]
2,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numer...
558
E
A Simple Task
This task is very simple. Given a string $S$ of length $n$ and $q$ queries each query is on the format $i$ $j$ $k$ which means sort the substring consisting of the characters from $i$ to $j$ in non-decreasing order if $k = 1$ or in non-increasing order if $k = 0$. Output the final string after applying the queries.
In this problem we will be using counting sort. So for each query we will count the number of occurrences for each character, and then update the range like this But this is too slow. We want a data structure that can support the above operations in appropriate time. Let's make 26 segment trees each one for each charac...
[ "data structures", "sortings", "strings" ]
2,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numer...
559
A
Gerald's Hexagon
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\circ}$. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on...
Let's consider regular triangle with sides of $k$ Let's split it to regular triangles with sides of $1$ by lines parallel to the sides. Big triange area $k^{2}$ times larger then small triangles area and therefore big triangle have splitted by $k^{2}$ small triangles. If we join regular triangles to sides $a_{1}, a_{3}...
[ "brute force", "geometry", "math" ]
1,600
null
559
B
Equivalent Strings
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings $a$ and $b$ of equal length are called equivalent in one of the two cases: - They are equal. - If we split string $a$ into two halves of the same size $a_{1}$ and $a_{2}$, and string $b$ into two halves of the same size...
Let us note that "equivalence" described in the statements is actually equivalence relation, it is reflexively, simmetrically and transitive. It is meant that set of all string is splits to equivalence classes. Let's find lexicographic minimal strings what is equivalent to first and to second given string. And then che...
[ "divide and conquer", "hashing", "sortings", "strings" ]
1,700
String smallest(String s) { if (s.length() % 2 == 1) return s; String s1 = smallest(s.substring(0, s.length()/2)); String s2 = smallest(s.substring(s.length()/2), s.length()); if (s1 < s2) return s1 + s2; else return s2 + s1; }
559
C
Gerald and Giant Chess
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an $h × w$ field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of g...
Let's denote black cells ad $A_{0}, A_{1}, ..., A_{k - 1}$ . First of all, we have to sort black cells in increasing order of (row, column). If cell $x$ available from cell $y$, $x$ stands after $y$ in this order. Let $A_{k} = (h, w)$. Now we have to find number of paths from $(1, 1)$ to $A_{k}$ avoiding $A_{0}, ..., A...
[ "combinatorics", "dp", "math", "number theory" ]
2,200
null
559
D
Randomizer
Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows. A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a \textbf{basic polygon}. If you shake a Randomizer, it draws some nondege...
We can use Pick's theorem for calculate integer points number in every polygon. Integer points number on the segment between points $(0, 0)$ and $(a, b)$ one can calculate over $GCD(a, b)$. Integer points number in some choosen polynom is integer points number in basic polynom minus integer points number in segmnent of...
[ "combinatorics", "geometry", "probabilities" ]
2,800
null
559
E
Gerald and Path
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path ...
Lighted part of walking trail is union of ligted intervals. Let's sort spotlights in increasing order of $a_{i}$. Consider some lighted interval $(a, b)$. It's lighted by spotlights with numbers ${l, l + 1, ..., r}$ for some $l$ and $r$ ("substring" of spotlights). Let $x_{0}, ..., x_{k}$ is all possible boundaries of ...
[ "dp", "sortings" ]
3,000
null
560
A
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea...
If there is a banlnot of value 1 then one can to express every sum of money. Otherwise one can't to express 1 and it is minimum unfortunate sum.
[ "implementation", "sortings" ]
1,000
null
560
B
Gerald is into Art
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an $a_{1} × b_{1}$ rectangle, the paintings have shape of a $a_{2} × b_{2}$ and $a_{3} × b_{3...
It is easy to see that one can snuggle paintings to each other and to edge of board. For instance one can put one of painting right over other. Then height of two paintings equals to sum of two heights and width of two paintings is equals to maximum of two widths. Now we can just iterate orientation of paintings and bo...
[ "constructive algorithms", "implementation" ]
1,200
null
566
A
Matching Names
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching ps...
Form a trie from all names and pseudonyms. Mark with red all vertices corresponding to names, and with blue all vertices corresponding to the pseudonyms (a single vertex may be marked several times, possibly with different colors). Note that if we match a name $a$ and a pseudonym $b$, then the quality of such match is ...
[ "dfs and similar", "strings", "trees" ]
2,300
null
566
B
Replicating Processes
A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure. As part of this task, we assume that the social network is...
This problem may be solved by simulating the replication process. Let's keep a list of all replications that may be applied by the current step. Apply an arbitrary replication, after that update a list by adding/removing all suitable or now unsuitable replications touching all affected on current step servers. The list...
[ "constructive algorithms", "greedy" ]
2,600
null
566
C
Logistical Questions
Some country consists of $n$ cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of $(n - 1)$ bidirectional roads (in the other words, the graph of roads is a tree). The $i$-th road that directly connects cities $a_{i}...
Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $ \rho (a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_{i}$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum ...
[ "dfs and similar", "divide and conquer", "trees" ]
3,000
null
566
D
Restructuring Company
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company. There are $n$ people working for the Large Software Company. Each person ...
This problem allows a lot of solution with different time asymptotic. Let's describe a solution in $O(q\log n)$. Let's first consider a problem with only a queries of second and third type. It can be solved in a following manner. Consider a line consisting of all employees from $1$ to $n$. An observation: any departmen...
[ "data structures", "dsu" ]
1,900
null
566
E
Restoring Map
Archaeologists found some information about an ancient land of Treeland. We know for sure that the Treeland consisted of $n$ cities connected by the $n - 1$ road, such that you can get from each city to any other one along the roads. However, the information about the specific design of roads in Treeland has been lost....
Let's call a neighborhood of a vertex - the set consisting of it and all vertices near to it. So, we know the set of all neighborhoods of all vertices in some arbitrary order, and also each neighborhood is shuffled in an arbitrary order. Let's call the tree vertex to be internal if it is not a tree leaf. Similarly, let...
[ "bitmasks", "constructive algorithms", "trees" ]
3,200
null
566
F
Clique in the Divisibility Graph
As you must know, the maximum clique problem in an arbitrary graph is $NP$-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively. Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are conn...
Order numbers in the sought clique in ascending order. Note that set $X = {x_{1}, ..., x_{k}}$ is a clique iff $\mathbb{Z}_{i}\ \mid\mathbb{Z}_{i+1}$ for ($1 \le i \le k - 1$). So, it's easy to formulate a dynamic programming problem: $D[x]$ is equal to the length of a longest suitable increasing subsequence ending...
[ "dp", "math", "number theory" ]
1,500
null
566
G
Max and Min
Two kittens, Max and Min, play with a pair of non-negative integers $x$ and $y$. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, $x$ and $y$ became negative at the same time, and kitten Max tries to prevent ...
Consider a following geometrical interpretation. Both Max and Min have a set of vectors from the first plane quadrant and a point $(x, y)$. During his turn Max may add any of his vectors to a point $(x, y)$, and Min - may subtract any of his vectors. Min wants point $(x, y)$ to be strictly in the third quadrant, Max tr...
[ "geometry" ]
2,500
null
567
A
Lineland Mail
All cities of Lineland are located on the $Ox$ coordinate axis. Thus, each city is associated with its position $x_{i}$ — a coordinate on the $Ox$ axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another ...
One can notice that the maximum cost of sending a letter from $i$'th city is equal to maximum of distances from $i$'th city to first city and from $i$'th city to last ($max(abs(x_{i} - x_{0}), abs(x_{i} - x_{n - 1})$). On the other hand, the minimum cost of sending a letter will be the minimum of distances between neig...
[ "greedy", "implementation" ]
900
null
567
B
Berland National Library
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room. Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed...
To answer the queries correct, we need to know if the person is still in the library. For that purpose we will use $in$ array of type $bool$. Also we will store two variables for the answer and ''current state'' (it will store the current number of people in the library). Let's call them $ans$ and $state$ respectively....
[ "implementation" ]
1,300
null
567
C
Geometric Progression
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer $k$ and a sequence $a$, consisting of $n$ integers. He wants to know how many subsequences of length three can be selected from $a$, so that they form a geo...
Let's solve this problem for fixed middle element of progression. This means that if we fix element $a_{i}$ then the progression must consist of $a_{i} / k$ and $a_{i} \cdot k$ elements. It could not be possible, for example, if $a_{i}$ is not divisible by $k$ ($a_{i}\ \mathrm{mod}\ k\not=0$). For fixed middle element ...
[ "binary search", "data structures", "dp" ]
1,700
null
567
D
One-Dimensional Battle Ships
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of $n$ square cells (that is, on a $1 × n$ table). At the beginning of the game Alice puts $k$ ships on the field without telling their positions to Bob. Each ship looks as a $1 × a$ rectangle (that is, it ...
First, we should understand when the game ends. It will happen when on the $n$-sized board it will be impossible to place $k$ ships of size $a$. For segment with length $len$ we could count the maximum number of ships with size $a$ that could be placed on it. Each ship occupies $a + 1$ cells, except the last ship. Thus...
[ "binary search", "data structures", "greedy", "sortings" ]
1,700
null
567
E
President and Roads
Berland has $n$ cities, the capital is located in city $s$, and the historic home town of the President is in city $t$ ($s ≠ t$). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town $t$, for which his motorcade ...
At first, let's find edges that do not belong to any shortest paths from $s$ to $t$. Let's find two shortest path arrays $d1$ and $d2$ with any shortest-path-finding algorithm. First array stores shortest path length from $s$, and the second - from $t$. Edge $(u, v)$ then will be on at least one shortest path from $s$ ...
[ "dfs and similar", "graphs", "hashing", "shortest paths" ]
2,200
null
567
F
Mausoleum
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from $2n$ blocks, each of them has the shape of a cuboid. Each block has ...
Consider that we are placing blocks by pairs, one pair by one, starting from leftmost and rightmost places. Thus, for example, two blocks of height 1 we could place in positions 1 and 2, 1 and $2n$, or $2n - 1$ and $2n$. The segment of unused positions will be changed that way and the next block pairs should be placed ...
[ "dp" ]
2,400
null
568
A
Primes or Palindromes?
Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this! Let us remind you...
It is known that amount of prime numbers non greater than $n$ is about $\frac{J h}{\log n}$. We can also found the amount of palindrome numbers with fixed length $k$ - it is about $10^{\lfloor{\frac{k+1}{2}}\rfloor}$ which is $O({\sqrt{n}})$. Therefore the number of primes asymptotically bigger than the number of palin...
[ "brute force", "implementation", "math", "number theory" ]
1,600
null
568
B
Symmetric and Transitive
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation. A set $ρ$ of pairs $(a, b)$ of eleme...
Let's find Johnny's mistake. It is all right in his proof except ``If $a\stackrel{\rho}{\sim}b$'' part. What if there is no such $b$ for an given $a$? Then obviously $a\stackrel{p}{\sim}a$ otherwise we'll take $b = a$. We can see that our binary relation is some equivalence relation which was expanded by some "empty" e...
[ "combinatorics", "dp", "math" ]
1,900
null
568
C
New Language
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed. After some time, the wise men ...
Suppose we have fixed letters on some positions, how can we check is there a way to select letters on other positions to build a word from the language? The answer is 2-SAT. Let's see: for every position there is two mutually exclusive options (vowel or consonant) and the rules are consequences. Therefore we can do thi...
[ "2-sat", "greedy" ]
2,600
null
568
D
Sign Posts
One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities. The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he...
Suppose, that solution exist. In case $n \le k$ we can put one signpost on each road. In other case let's choose any $k + 1$ roads. By the Dirichlet's principle there are at least two roads among selected, which have common signpost. Let's simple iterate over all variants with different two roads. After choosing road...
[ "brute force", "geometry", "math" ]
2,800
null
568
E
Longest Increasing Subsequence
Note that the memory limit in this problem is less than usual. Let's consider an array consisting of positive integers, some positions of which contain gaps. We have a collection of numbers that can be used to fill the gaps. Each number from the given collection can be used at most once. Your task is to determine su...
Let's calculate array $c$: $c[len]$ - minimal number that can complete increasing subsequence of length $len$. (This is one of the common solution for LIS problem). Elements of this array are increasing and we can add new element $v$ to processed part of sequence as follows: find such index $i$ that $c[i] \le v$ and ...
[ "data structures", "dp" ]
3,000
null
569
A
Music
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk. Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite ...
Suppose we have downloaded $S$ seconds of the song and press the 'play' button. Let's find how many seconds will be downloaded when we will be forced to play the song once more. ${\frac{x}{q}}={\frac{x-S}{q-1}}$. Hence $x = qS$. Solution: let's multiply $S$ by $q$ while $S < T$. The answer is the amount of operations. ...
[ "implementation", "math" ]
1,500
null
569
B
Inventory
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the...
Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from $1$ to $n$ and they are must be pairwise distinct. This condition is necessary and sufficient. This problem can be solved with greedy algorithm. If me meet the number we hav...
[ "greedy", "math" ]
1,200
null
570
A
Elections
The country of Byalechinsk is running elections involving $n$ candidates. The country consists of $m$ cities. We know how many people in each city voted for each candidate. The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in ...
We need to determine choice for each city. Then sum it for each candidate and determine the winner. $O(n * m)$
[ "implementation" ]
1,100
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #inclu...
570
B
Simple Game
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from $1$ to $n$. Let's assume that Misha chose number $m$, and Andrew chose number $a$. Then, by using a random generator they choose a random integer $c$ in the range between $1$ and $n$ (any integer from $1$ ...
Lets find which variant is interesting. For Andrew is no need a variant wherein $|a - m| > 1$ because we can increase probability of victory if we will be closer to m. Then we consider two variants, $a = c - 1$ and $a = c + 1$. Probability of victory will be $c / n$ for first variant and $(n - c + 1) / n$ for second. W...
[ "constructive algorithms", "games", "greedy", "implementation", "math" ]
1,300
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #inclu...
570
C
Replacement
Daniel has a string $s$, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string $s$, of all occurrences of the substring let's choose the first one, and replace thi...
Lets find how replacements occur. If we have segment of points with length $l$,we need $l - 1$ operations and stop replacements for this segment. If we sum lenghts of all segments and its quantity then answer will be = total length of segments - quantity of segments. After change of one symbol length changes by 1. Quan...
[ "constructive algorithms", "data structures", "implementation" ]
1,600
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #inclu...
570
D
Tree Requests
Roman planted a tree consisting of $n$ vertices. Each vertex contains a lowercase English letter. Vertex $1$ is the root of the tree, each of the $n - 1$ remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex $i$ is vertex $p_{i}$, the parent index is always le...
We need to write vertices in DFS order and store time of enter/exit of vertices in DFS. All vertices in subtree represent a segment. Now we can get all vertices in subtree v on height h as a segment, making two binary searches. We can make a palindrome if quantity of uneven entries of each letter is less than 2. This f...
[ "binary search", "bitmasks", "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,200
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #inclu...
570
E
Pig and Palindromes
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of $n$ rows and $m$ columns. We enumerate the rows of the rectangle from top to bottom with numbers from $1$ to $n$, and the columns — from left to right with numbers from $1$ to $m$. Le...
We need palindrome paths. Palindrome is word which reads the same backward or forward. We can use it. Count the dynamic from coordinates of 2 cells, first and latest in palindrome. From each state exists 4 transitions (combinations: first cell down/to the right and second cell up/to the left). We need only transitions ...
[ "combinatorics", "dp" ]
2,300
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #inclu...
571
A
Lengthening Sticks
You are given three sticks with positive integer lengths of $a, b$, and $c$ centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most $l$ centimeters. In particular, it is allowed not to increase...
Let's count the number of ways to form a triple which can't represent triangle sides, and then we subtract this value from $C_{l+3}^{3}={\stackrel{(l+1)(l+2)(l+3)}{6}}$ - the total number of ways to increase the sticks not more than $l$ in total. This number is obtained from partition of $l$ into 4 summands ($l_{a} + l...
[ "combinatorics", "implementation", "math" ]
2,100
#pragma comment (linker, "/STACK:1280000000") #define _CRT_SECURE_NO_WARNINGS //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> #include <deque> //#...
571
B
Minimization
You've got array $A$, consisting of $n$ integers and a positive integer $k$. Array $A$ is indexed by integers from $1$ to $n$. You need to permute the array elements so that value \[ \sum_{i=1}^{n-k}|A[i]-A[i+k]| \] became minimal possible. In particular, it is allowed not to change order of elements at all.
We can divide all indices $[1;n]$ into groups by their remainder modulo $k$. While counting $\sum_{i=1}^{n-k}|a_{i}-a_{i+k}|$, we can consider each group separately and sum the distances between neighbouring numbers in each group. Consider one group, corresponding to some remainder $i$ modulo $k$, i.e. containing $a_{j...
[ "dp", "greedy", "sortings" ]
2,000
#define _CRT_SECURE_NO_WARNINGS #pragma comment (linker, "/STACK:128000000") #include <stdio.h> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> #include <queue> #include <deque> #include <cmath> #include <ctime> #include <stack> #include <set> #include <map> #include <...
571
C
CNF 2
'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form) In the other words, CNF is a formula of type $\left(v_{11}\mid v_{12}\mid\cdot\cdot\...
Firstly let's assign values to variables occurring in our fomula only with negation or only without negation. After that we can throw away the disjuncts which contained them, since they are already true, and continue the process until it is possible. To make it run in time limit, one should use dfs or bfs algorithm to ...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
2,500
#pragma comment (linker, "/STACK:128000000") //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> //#include <unordered_map> //#include <...
571
D
Campus
Oscolcovo city has a campus consisting of $n$ student dormitories, $n$ universities and $n$ military offices. Initially, the $i$-th dormitory belongs to the $i$-th university and is assigned to the $i$-th military office. Life goes on and the campus is continuously going through some changes. The changes can be of fou...
Let's suppose for each dormitory from $Q$ query we already know the last raid moment. When task will be much easier: we can throw away $M$ and $Z$ queries and to get right answer we should subtract two values: people count in dormitory right now and same count in a last raid moment. On this basis, we have such plan: Fo...
[ "binary search", "data structures", "dsu", "trees" ]
3,100
#pragma comment (linker, "/STACK:128000000") //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> //#include <unordered_map> //#include <...
571
E
Geometric Progressions
Geometric progression with the first element $a$ and common ratio $b$ is a sequence of numbers $a, ab, ab^{2}, ab^{3}, ...$. You are given $n$ integer geometric progressions. Your task is to find the smallest integer $x$, that is the element of all the given progressions, or else state that such integer does not exist...
If intersection of two geometric progressions is not empty, set of common elements indexes forms arithmetic progression in each progression or consists of not more than one element. Let's intersect first progression with each other progression. If any of these intersections are empty then total intersection is empty. I...
[ "math" ]
3,200
#include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <set> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <complex> #include <map> #include <queue> #include <time.h> using namespace std; typedef long long ll; typed...
572
A
Arrays
You are given two arrays $A$ and $B$ consisting of integers, \textbf{sorted in non-decreasing order}. Check whether it is possible to choose $k$ numbers in array $A$ and choose $m$ numbers in array $B$ so that any number chosen in the first array is strictly less than any number chosen in the second array.
In this problem one need to check whether it's possible to choose $k$ elements from array $A$ and $m$ elements from array $B$ so that each of chosen element in $A$ is less than each of chosen elements in $B$. If it's possible then it's possible to choose $k$ smallest elements in $A$ and $m$ largest elements in $B$. Tha...
[ "sortings" ]
900
#include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <set> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <complex> #include <map> #include <queue> using namespace std; typedef long long ll; typedef vector<int> vi;...
572
B
Order Book
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number $i$ has price $p_{i}$, direction $d_{i}$ — buy or sell, and integer $q_{i}$. This means that the participant is rea...
First of all the problem may be solved for buy orders and sell orders separately. The easiest soultion is to use structure like std::map or java.lang.TreeMap. To aggregate orders we just add volume to the corresponding map element: aggregated[price] += volume. After that we should extract lowest (or largest) element fr...
[ "data structures", "greedy", "implementation", "sortings" ]
1,300
/** * code generated by JHelper * More info: https://github.com/AlexeyDmitriev/JHelper * @author RiaD */ #include <iostream> #include <fstream> #include <iostream> #include <bits/stdc++.h> #include <iterator> #include <string> #include <stdexcept> #ifdef SPCPPL_DEBUG #define SPCPPL_ASSERT(condition) \ ...
573
A
Bear and Poker
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are $n$ players (including Limak himself) and right now all of them have bids on the table. $i$-th of them has bid with size $a_{i}$ dollars. Each player can double his bid any number of times and triple his bid any n...
Any positive integer number can be factorized and written as $2^{a} \cdot 3^{b} \cdot 5^{c} \cdot 7^{d} \cdot ...$. We can multiply given numbers by $2$ and $3$ so we can increase $a$ and $b$ for them. So we can make all $a$ and $b$ equal by increasing them to the same big value (e.g. $100$). But we can't change powers...
[ "implementation", "math", "number theory" ]
1,300
#include<bits/stdc++.h> using namespace std; int t[1005*1005]; int main() { int n; scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d", &t[i]); } int x = t[1]; for(int i = 2; i <= n; ++i) x = __gcd(x, t[i]); while(x % 2 == 0) x /= 2; while(x % 3 == 0) x /= 3; for(int i = 1; i <= n; ++i) { int t...
573
B
Bear and Blocks
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built $n$ towers in a row. The $i$-th tower is made of $h_{i}$ identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called inte...
In one operation the highest block in each tower disappears. So do all blocks above heights of neighbour towers. And all other blocks remain. It means that in one operation all heights change according to formula $h_{i} = min(h_{i - 1}, h_{i} - 1, h_{i + 1})$ where $h_{0} = h_{n + 1} = 0$. By using this formula two tim...
[ "binary search", "data structures", "dp", "math" ]
1,600
#include<bits/stdc++.h> using namespace std; const int nax = 1e5 + 5; vector<int> w[nax]; // leg is single/simple path ending with a leaf bool del[nax]; // vertices in legs are marked as deleted int legs[nax]; // numbers of legs starting in a vertex void dfs(int a, int par = 0) { if(w[a].size() <= 2) { del[a] = tr...
573
D
Bear and Cavalry
Would you want to fight against bears riding horses? Me neither. Limak is a grizzly bear. He is general of the dreadful army of Bearland. The most important part of an army is cavalry of course. Cavalry of Bearland consists of $n$ warriors and $n$ horses. $i$-th warrior has strength $w_{i}$ and $i$-th horse has stren...
Let's sort warriors and horses separately (by strength). For a moment we forget about forbidden assignments. Inversion is a pair of warriors that stronger one is assigned to weaker horse. We don't like inversions because it's not worse to assign strong warriors to strong horses: $A \cdot B + a \cdot b \ge A \cdot b +...
[ "data structures", "divide and conquer", "dp" ]
3,000
null
573
E
Bear and Bowling
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record! For rolling a ball one gets a score — an integer (maybe negative) number of points. Score for $i$-th roll is multiplied by $i$ and scores are summed up. So, for $k$ rolls with scores $s_{1},...
FIRST PART - greedy works We will add (take) elements to a subsequence one by one. Adding number $x$, when we have $k - 1$ taken numbers on the left, increases result by $k \cdot x + suf$ where $suf$ is sum of taken numbers on the right. Let's call this added value as the Quality of element $x$. We will prove correctne...
[ "data structures", "greedy" ]
3,200
#include<bits/stdc++.h> using namespace std; typedef long long ll; struct line { int a, id; ll b; line(int aa, ll bb, int idd) : a(aa), id(idd), b(bb) {} // does (this,B) intersect before (B,C) bool before(const line & B, const line & C) { // a*x + b = B.a*x + B.b // x * (a-B.a) = B.b-b // x * q1 = p1 ll...
574
B
Bear and Three Musketeers
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are $n$ warriors. Richelimakieu wants to choose thre...
Warriors are vertices and "knowing each other" is an edge. We want to find connected triple of vertices with the lowest sum of degrees (and print $sum - 6$ because we don't want to count edges from one chosen vertex to another). Brute force is $O(n^{3})$. We iterate over all triples $a, b, c$ and consider them as muske...
[ "brute force", "dfs and similar", "graphs", "hashing" ]
1,500
#include<bits/stdc++.h> using namespace std; const int inf = 100000005; const int nax = 5005; int degree[nax]; bool t[nax][nax]; int main() { int n, m; scanf("%d%d", &n, &m); for(int i = 0; i < m; ++i) { int a, b; scanf("%d%d", &a, &b); t[a][b] = t[b][a] = true; degree[a]++; degree[b]++; } int result...
576
A
Vasya and Petya's Game
Vasya and Petya are playing a simple game. Vasya thought of number $x$ between $1$ and $n$, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number $y$?". The game is played by the following rules: first Petya asks \textbf{all} the questions that interest him (als...
If Petya didn't ask $p^{k}$, where $p$ is prime and $k \ge 1$, he would not be able to distinguish $p^{k - 1}$ and $p^{k}$. That means, he should ask all the numbers $p^{k}$. It's easy to prove that this sequence actually guesses all the numbers from $1$ to $n$ The complexity is $O(N^{1.5})$ or $O(NloglogN)$ dependin...
[ "math", "number theory" ]
1,500
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
576
B
Invariance of Tree
A tree of size $n$ is an undirected connected graph consisting of $n$ vertices without cycles. Consider some tree with $n$ vertices. We call a tree invariant relative to permutation $p = p_{1}p_{2}... p_{n}$, if for any two vertices of the tree $u$ and $v$ the condition holds: "vertices $u$ and $v$ are connected by an...
Let's look at the answer. It's easy to notice, that centers of that tree must turn into centers after applying the permutation. That means, permutation must have cycle with length $1$ or $2$ since there're at most two centers. If permutation has cycle with length $1$, we can connect all the other vertices to it. For ex...
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
2,100
"#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include <algorithm>\n#include <numeric>\n\n#include <vector>\n#include <set>\n#include <map>\n#include <bitset>\n#include <deque>\n\n#include <ctime>\n#include <cmath>\n#include <cstdlib>\n#include <cstdio>\n#include <cassert>\n\n#define pb push_back\n#de...
576
C
Points on Plane
On a plane are $n$ points ($x_{i}$, $y_{i}$) with integer coordinates between $0$ and $10^{6}$. The distance between the two points with numbers $a$ and $b$ is said to be the following value: $\operatorname{dist}(a,b)=|x_{a}-x_{b}|+|y_{a}-y_{b}|$ (the distance calculated by such formula is called Manhattan distance). ...
Let's split rectangle $10^{6} \times 10^{6}$ by vertical lines into $1000$ rectangles $10^{3} \times 10^{6}$. Let's number them from left to right. We're going to pass through points rectangle by rectangle. Inside the rectangle we're going to pass the points in increasing order of $y$-coordinate if the number of re...
[ "constructive algorithms", "divide and conquer", "geometry", "greedy", "sortings" ]
2,100
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
576
D
Flights for Regular Customers
In the country there are exactly $n$ cities numbered with positive integers from $1$ to $n$. In each city there is an airport is located. Also, there is the only one airline, which makes $m$ flights. Unfortunately, to use them, you need to be a regular customer of this company, namely, you have the opportunity to enjo...
Let's optimize the first solution that comes to mind: $O(m * d_{max})$, let's calculate $can[t][v]$ - can we get to the vertice $v$, while passing exactly $t$ edges. Now, it's easy to find out that the set of edges we are able to go through changed only $m$ times. Let's sort these edges in increasing order of $d_{i}$, ...
[ "dp", "matrices" ]
2,700
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
576
E
Painting Edges
Note the unusual memory limit for this problem. You are given an undirected graph consisting of $n$ vertices and $m$ edges. The vertices are numbered with integers from $1$ to $n$, the edges are numbered with integers from $1$ to $m$. Each edge can be unpainted or be painted in one of the $k$ colors, which are numbere...
Let's solve an easier task first: independent of bipartivity, the color of edge changes. Then we could write a solution, which is pretty similar to solution of Dynamic Connectivity Offline task in $O(nlog^{2n})$. Let's consider only cases, where edges are not being deleted from the color graph. Then, we could use DSU w...
[ "binary search", "data structures" ]
3,300
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
577
A
Multiplication Table
Let's consider a table consisting of $n$ rows and $n$ columns. The cell located at the intersection of $i$-th row and $j$-th column contains number $i × j$. The rows and columns are numbered starting from 1. You are given a positive integer $x$. Your task is to count the number of cells in a table that contain number ...
It's easy to see that number $x$ can appear in column $i$ only once - in row $x / i$. For every column $i$, let's check that $x$ divides $i$ and $x / i \le n$. If all requirements are met, we'll update the answer. The complexity is $O(n)$
[ "implementation", "number theory" ]
1,000
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
577
B
Modulo Sum
You are given a sequence of numbers $a_{1}, a_{2}, ..., a_{n}$, and a number $m$. Check if it is possible to choose a non-empty subsequence $a_{ij}$ such that the sum of numbers in this subsequence is divisible by $m$.
Let's consider two cases: $n > m$ and $n \le m$. If $n > m$, let's look at prefix sums. By pigeonhole principle, there are two equals sums modulo $m$. Assume $S_{lmodm} = S_{rmodm}$. Then the sum on segment $[l + 1, r]$ equals zero modulo $m$, that means the answer is definitely "YES". If $n \le m$, we'll solve thi...
[ "combinatorics", "data structures", "dp", "two pointers" ]
1,900
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#inclu...
578
A
A Problem about Polyline
There is a polyline going through points $(0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ...$. We know that the polyline passes through the point $(a, b)$. Find minimum positive value $x$ such that it is true or determine that there is no such $x$.
If point ($a$,$b$) is located on the up slope/ down slope of this polyline. Then the polyline will pass the point ($a - b$,$0$)/($a + b$,$0$).(we call $(a - b)$ or $(a + b)$ as $c$ afterwards) And we can derive that $c / (2 * x)$ should be a positive integer. Another condition we need to satisfy is that $x$ must be lar...
[ "geometry", "math" ]
1,700
#include <bits/stdc++.h> typedef long long LL; using namespace std; int main(){ LL a,b; cin>>a>>b; if(a<b)puts("-1"); else printf("%.12f\n",(a+b)/(2.*((a+b)/(2*b)))); return 0; }
578
B
"Or" Game
You are given $n$ numbers $a_{1}, a_{2}, ..., a_{n}$. You can perform at most $k$ operations. For each operation you can multiply one of the numbers by $x$. We want to make $a_{1}\mid a_{2}\mid\dots\mid a_{n}$ as large as possible, where denotes the bitwise OR. Find the maximum possible value of $a_{1}\mid a_{2}\mid\l...
We can describe a strategy as multiplying $a_{i}$ by $x$ $t_{i}$ times so $a_{i}$ will become $b_{i} = a_{i} * x^{ti}$ and sum of all $t_{i}$ will be equals to $k$. The fact is there must be a $t_{i}$ equal to $k$ and all other $t_{i}$ equals to $0$. If not, we can choose the largest number $b_{j}$ in sequence $b$, and...
[ "brute force", "greedy" ]
1,700
#include<cstdio> #include<algorithm> using namespace std; const int SIZE = 2e5+2; long long a[SIZE],prefix[SIZE],suffix[SIZE]; int main(){ int n,k,x; scanf("%d%d%d", &n, &k, &x); long long mul=1; while(k--) mul *= x; for(int i = 1; i <= n; i++) scanf("%I64d", &a[i]); for(int i = ...
578
C
Weakness and Poorness
You are given a sequence of n integers $a_{1}, a_{2}, ..., a_{n}$. Determine a real number $x$ such that the weakness of the sequence $a_{1} - x, a_{2} - x, ..., a_{n} - x$ is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) o...
Let $s(i,j)=\sum_{k=i}^{j}(a_{k}-x)$, we can write down the definition of poorness formally as . It's easy to see that $A$ is a strictly decreasing function of $x$, and $B$ is a strictly increasing function of x. Thus the minimum of $max(A, B)$ can be found using binary or ternary search. The time complexity is $O(n\lo...
[ "ternary search" ]
2,000
#include <bits/stdc++.h> typedef long long LL; using namespace std; const int SIZE = 2e5+10; int a[SIZE]; int up_stk[SIZE],down_stk[SIZE]; int Un=1,Dn=1; LL compare(LL x,LL y,LL z,LL w){return (a[x]-a[y])*(w-z)-(a[z]-a[w])*(y-x);} double get_x(int x,int y){return (a[x]-a[y])*1./(y-x);} double get_y(double v,int x){retu...
578
D
LCS Again
You are given a string $S$ of length $n$ with each character being one of the first $m$ lowercase English letters. Calculate how many different strings $T$ of length $n$ composed from the first $m$ lowercase English letters exist such that the length of LCS (longest common subsequence) between $S$ and $T$ is $n - 1$. ...
Followings are solution in short. Considering the LCS dp table $lcs[x][y]$ which denotes the LCS value of first $x$ characters of $S$ and first $y$ characters of $T$. If we know $lcs[n][n] = n - 1$, then we only concern values in the table which $abs(x - y) \le 1$ and all value of $lcs[x][y]$ must be $min(x, y)$ or $...
[ "dp", "greedy" ]
2,700
#include <bits/stdc++.h> #define SZ(X) ((int)(X).size()) #define ALL(X) (X).begin(), (X).end() #define REP(I, N) for (int I = 0; I < (N); ++I) #define REPP(I, A, B) for (int I = (A); I < (B); ++I) #define RI(X) scanf("%d", &(X)) #define RII(X, Y) scanf("%d%d", &(X), &(Y)) #define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y...
578
E
Walking!
There is a sand trail in front of Alice's home. In daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walkin...
Since there is only one person, it's not hard to show the difference between the number of left footprints and the number of right footprints is at most one. For a particular possible time order of a sequence of footprints, if there are $k$ backward steps, we can easily divide all footprints into at most $k + 1$ subseq...
[ "constructive algorithms", "greedy" ]
2,700
#include<bits/stdc++.h> #define SZ(X) ((int)(X).size()) #define MP(X,Y) make_pair((X),(Y)) using namespace std; const int SIZE = 100010; char s[SIZE+5]; int nxt[SIZE],lat[SIZE]; bool pointed[SIZE]; int footprint_type(char c){return c=='R'?1:0;} vector<int>seq[2][2]; vector<int>an[SIZE]; int pn; void connect(int x,int y...
578
F
Mirror Box
You are given a box full of mirrors. Box consists of grid of size $n × m$. Each cell of the grid contains a mirror put in the shape of '$\$' or '$ / $' ($45$ degree to the horizontal or vertical line). But mirrors in some cells have been destroyed. You want to put new mirrors into these grids so that the following two ...
If we view the grid intersections alternatively colored by blue and red like this: Then we know that the two conditions in the description are equivalent to a spanning tree in either entire red intersections or entire blue dots. So we can consider a red spanning tree and blue spanning tree one at a time. We can use dis...
[ "matrices", "trees" ]
3,200
#include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <cassert> #define SZ(x) ((int)(x).size()) #define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef long...
579
A
Raising Bacteria
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly $x$ bacteria in the box at some moment. What is the minimu...
Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n + 1 - i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$.
[ "bitmasks" ]
1,000
#include<cstdio> int main(){ int n,an=0; scanf("%d",&n); while(n){ if(n&1)an++; n>>=1; } printf("%d\n",an); return 0; }
579
B
Finding Team Member
There is a programing contest named SnakeUp, $2n$ people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are \textbf{distinct}. Every contestant hopes that he...
Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team.
[ "brute force", "implementation", "sortings" ]
1,300
#include<cstdio> int person[1000001][2],an[1001]; bool used[1001]; int main(){ int n; scanf("%d",&n); n*=2; for(int i=1;i<=n;i++) for(int j=1;j<i;j++){ int x; scanf("%d",&x); person[x][0]=i; person[x][1]=j; } used[0]=1; for(int i=10...
580
A
Kefa and First Steps
Kefa decided to make some money doing business on the Internet for exactly $n$ days. He knows that on the $i$-th day ($1 ≤ i ≤ n$) he makes $a_{i}$ money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence $a_{i}$. Let us remind you that the subsegment of th...
Note, that if the array has two intersecting continuous non-decreasing subsequence, they can be combined into one. Therefore, you can just pass the array from left to right. If the current subsequence can be continued using the $i$-th element, then we do it, otherwise we start a new one. The answer is the maximum subse...
[ "brute force", "dp", "implementation" ]
900
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228...
580
B
Kefa and Company
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has $n$ friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend ...
At first we sort all friends in money ascending order. Now the answer is some array subsegment. Next, we use the method of two pointers for finding the required subsegment. Asymptotics - $O(n$ $log$ $n)$.
[ "binary search", "sortings", "two pointers" ]
1,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228...
580
C
Kefa and Park
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of $n$ vertices with the root at vertex $1$. Vertex $1$ also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are th...
Let's go down the tree from the root, supporting additional parameter $k$ - the number of vertices in a row met with cats. If $k$ exceeds $m$, then leave. Then the answer is the number of leaves, which we were able to reach. Asymptotics - $O(n)$.
[ "dfs and similar", "graphs", "trees" ]
1,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228...
580
D
Kefa and Dishes
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were $n$ dishes. Kefa knows that he needs exactly $m$ dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the $i$-th dish gives him $a_{i}$ units of...
A two-dimensional DP will be used to solve the problem. The first dimention is the mask of already taken dishes, and the second - the number of the last taken dish. We will go through all the zero bits of the current mask for the transitions. We will try to put the one in them, and then update the answer for a new mask...
[ "bitmasks", "dp" ]
1,800
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=122822...
580
E
Kefa and Watch
One day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money. The pawnbroker said that each watch contains a serial number r...
At first, we calculate the hash for all line elements depending on their positions. That is, the hash of the number $k$, standing on the $i$-th position will be equal to $g_{i}$ * $k$, where $g$ is the base of the hash. We construct the segment tree of sums, which support a group modification, for all hashes. Thus, we ...
[ "data structures", "hashing", "strings" ]
2,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\n\nconst long long A=100000000000000LL,N=2282...
581
A
Vasya the Hipster
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had $a$ red socks and $b$ blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning ...
The first number in answer (number of days which Vasya can dress fashionably) is $min(a, b)$ because every from this day he will dress one red sock and one blue sock. After this Vasya will have either only red socks or only blue socks or socks do not remain at all. Because of that the second number in answer is $max((a...
[ "implementation", "math" ]
800
null
581
B
Luxurious Houses
The capital of Berland has $n$ multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in a...
This problem can be solved in the following way. Let's iterate on given array from the right to the left and will store in variable $maxH$ the maximal height if house which we have already considered.Then the answer to house number $i$ is number $max(0, maxH + 1 - h_{i})$, where $h_{i}$ number of floors in house number...
[ "implementation", "math" ]
1,100
null
581
C
Developing Skills
Petya loves computer games. Finally a game that he's been waiting for so long came out! The main character of this game has $n$ different skills, each of which is characterized by an integer $a_{i}$ from 0 to 100. The higher the number $a_{i}$ is, the higher is the $i$-th skill of the character. The total rating of th...
This problem can be solved in many ways. Let's consider the most intuitive way that fits in the given time. In the beginning we need to sort given array in the following way - from two numbers to the left should be the number to which must be added fewer units of improvements to make it a multiple of 10. You must add a...
[ "implementation", "math", "sortings" ]
1,400
null
581
D
Three Logos
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no em...
This problem can be solved in many ways, let's consider one of them. The first step is to calculate sum of squares $s$ of given rectangles. Then the side of a answer square is $sqrt(s)$. If $sqrt(s)$ is not integer print -1. Else we need to make the following. We brute the order in which we will add given rectangles in...
[ "bitmasks", "brute force", "constructive algorithms", "geometry", "implementation", "math" ]
1,700
null
581
E
Kojiro and Furrari
Motorist Kojiro spent $10$ years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her. Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro ...
Let's $f$ - the position of start, and $e$ - the position of finish. For convenience of implementation we add the gas-station in point $e$ with type equals to $3$. Note: there is never a sense go to the left of the starting point because we already stand with a full tank of the besr petrol. It is correct for every gas-...
[ "dp", "greedy" ]
2,800
null
581
F
Zublicanes and Mumocrates
It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on $n$ main squares of the capital of Berland. Each of the $n$ squares certainly can have demonstrations of only one party, otherwise it could lead to r...
Let the number of leavs in tree (vertices with degree 1) is equal to $c$. It said in statement that $c$ is even. If in given graph only 2 vertices the answer is equal to $1$. Else we have vertex in graph which do not a leaf - we hang the three on this vertex. Now we need to count 2 dynamics. The first $z1[v][cnt][col]$...
[ "dp", "trees", "two pointers" ]
2,400
null
582
A
GCD Table
The GCD table $G$ of size $n × n$ for an array of positive integers $a$ of length $n$ is defined by formula \begin{center} $g_{i j}=\operatorname*{gcd}(a_{i},a_{j}).$ \end{center} Let us remind you that the greatest common divisor (GCD) of two positive integers $x$ and $y$ is the greatest integer that is divisor of b...
Let the answer be $a_{1} \le a_{2} \le ... \le a_{n}$. We will use the fact that $gcd(a_{i}, a_{j}) \le a_{min(i, j)}$. It is true that $gcd(a_{n}, a_{n}) = a_{n} \ge a_{i} \ge gcd(a_{i}, a_{j})$ for every $1 \le i, j \le n$. That means that $a_{n}$ is equal to maximum element in the table. Let set $a_{...
[ "constructive algorithms", "greedy", "number theory" ]
1,700
#include <cstdio> #include <map> #include <cassert> #define forn(i, n) for (int i = 0; i < int(n); ++i) using namespace std; const int N = 1000; map <int, int> cnt; int ans[N]; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { int n; scanf("%d", &n); forn(i, n * n) ...
582
B
Once Again...
You are given an array of positive integers $a_{1}, a_{2}, ..., a_{n × T}$ of length $n × T$. We know that for any $i > n$ it is true that $a_{i} = a_{i - n}$. Find the length of the longest non-decreasing sequence of the given array.
One could calculate matrix sized $n \times n$ $mt[i][j]$ - the length of the longest non-decreasing subsequence in array $a_{1}, a_{2}, ..., a_{n}$, starting at element, greater-or-equal to $a_{i}$ and ending strictly in $a_{j}$ element with $j$-th index. One could prove that if we have two matrices sized $n \times ...
[ "constructive algorithms", "dp", "matrices" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 100 + 5; int n, T, a[N]; vector <int> build(int t) { vector <int> res(n * t); for (int i = 0; i < n * t; ++i) res[i] = (i < n) ? a[i] : res[i - n]; return res; } vector <int> calc_lis(vector <int> a) { int n = a.size(); vector...
582
C
Superior Periodic Subarrays
You are given an infinite periodic array $a_{0}, a_{1}, ..., a_{n - 1}, ...$ with the period of length $n$. Formally, $a_{i}=a_{i}{\bmod{n}}$. A periodic subarray $(l, s)$ ($0 ≤ l < n$, $1 ≤ s < n$) of array $a$ is an infinite periodic array with a period of length $s$ that is a subsegment of array $a$, starting with p...
Let's fix $s$ for every $(l, s)$ pair. One could easily prove, that if subarray contains $a_{i}$ element, than $a_{i}$ must be greater-or-equal than $a_{j}$ for every $j$ such that $i\equiv j\mathrm{\mod\}g c d(n,s)$. Let's use this idea and fix $g = gcd(n, s)$ (it must be a divisor of $n$). To check if $a_{i}$ can be ...
[ "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 1000 * 1000 + 5; int a[N], n, c[N], gg[N]; bool u[N]; inline int inc(int v) { return (v + 1 == n) ? 0 : (v + 1); } inline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int main() { assert(scanf("%d", &n) == 1); for (int i = 0; i < n; ...
582
D
Number of Binominal Coefficients
For a given prime integer $p$ and integers $α, A$ calculate the number of pairs of integers $(n, k)$, such that $0 ≤ k ≤ n ≤ A$ and $\textstyle{\binom{n}{k}}$ is divisible by $p^{α}$. As the answer can be rather large, print the remainder of the answer moduly $10^{9} + 7$. Let us remind you that $\textstyle{\binom{n}...
It is a common fact that for a prime $p$ and integer $n$ maximum $ \alpha $, such that $p^{ \alpha }|n!$ is calculated as $\alpha=\left.\left\{{\frac{n}{p}}\right\}+\left[{\frac{n}{p^{2}}}\right\}+\cdot\cdot\cdot+\left.\right.\left\{{\frac{n}{p^{w}}}\right\}$, where $p^{w} \le n < p^{w + 1}$. As soon as ${\binom{n}{k...
[ "dp", "math", "number theory" ]
3,300
#include <bits/stdc++.h> using namespace std; const int N = 3400; const int MOD = int(1e9) + 7; inline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); } inline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); } inline void inc(int &a, int b) { a = add(a, b); } inline ...
582
E
Boolean Function
In this problem we consider Boolean functions of four variables $A, B, C, D$. Variables $A, B, C$ and $D$ are logical and can take values 0 or 1. We will define a function using the following grammar: <expression> ::= <variable> | (<expression>) <operator> (<expression>) <variable> ::= 'A' | 'B' | 'C' | 'D' | 'a' | '...
One could prove that the number of binary functions on 4 variables is equal to $2^{24}$, and can be coded by storing a $2^{4}$-bit binary mask, in which every bit is storing function value for corresponding variable set. It is true, that if $mask_{f}$ and $mask_{g}$ are correspond to functions $f(A, B, C, D)$ and $g(A,...
[ "bitmasks", "dp", "expression parsing" ]
3,000
#include <bits/stdc++.h> using namespace std; const int MOD = int(1e9) + 7; inline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); } inline void inc(int &a, int b) { a = add(a, b); } inline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); } inline void dec(int &a, int...
583
A
Asphalting Roads
City X consists of $n$ vertical and $n$ horizontal infinite roads, forming $n × n$ intersections. Roads (both vertical and horizontal) are numbered from $1$ to $n$, and the intersections are indicated by the numbers of the roads that form them. Sand roads have long been recognized out of date, so the decision was made...
To solve the problem one could just store two arrays $hused[j]$ and $vused[j]$ sized $n$ and filled with false initially. Then process intersections one by one from $1$ to $n$, and if for $i$-th intersections both $hused[h_{i}]$ and $vused[v_{i}]$ are false, add $i$ to answer and set both $hused[h_{i}]$ and $vused[v_{i...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; const int N = 100; bool u[2][N]; int n; int main() { cin >> n; for (int i = 0; i < n * n; ++i) { int h, v; cin >> h >> v; --h, --v; if (!u[0][h] && !u[1][v]) { u[0][h] = true; u[1][v] = true; co...