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
⌀ |
|---|---|---|---|---|---|---|---|
630
|
C
|
Lucky Numbers
|
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits $7$ and $8$ only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than $n$ digits.
|
There are $2$ lucky numbers of the length $1$. They are $7$ and $8$. There are $4$ lucky numbers of the length $2$. They are $77$, $78$, $87$ and $88$. There are $8$ lucky numbers of the length $3$. They are $777$, $778$, $787$, $788$, $877$, $878$, $887$, $888$. For each addition of $1$ to the length the number of lucky numbers is increased times $2$. It is easy to prove: to any number of the previous length one can append $7$ or $8$, so one number of the prevous length creates two numbers of the next length. So for the length $n$ the amount of lucky numbers of the length exactly $n$ is $2^{n}$. But in the problem we need the amount of lucky numbers of length not greater than $n$. Let's sum up them. $2^{1} = 2$, $2^{1} + 2^{2} = 2 + 4 = 6$, $2^{1} + 2^{2} + 2^{3} = 2 + 4 + 8 = 14$, $2^{1} + 2^{2} + 2^{3} + 2^{4} = 2 + 4 + 8 + 16 = 30$. One can notice that the sum of all previous powers of two is equal to the next power of two minus the first power of two. So the answer to the problem is $2^{n + 1} - 2$. One of the possible implementations of $2^{n + 1}$ in a programming language is to shift $1$ bitwise to the left for $n + 1$ binary digits or to shift $2$ bitwise to the left for $n$ binary digits. For example, in Java the problem answer formula is (2L << n) - 2, in C++ is (2LL << n) - 2. Suffixes L and LL correspondingly are required so that result of the shift expression have 64-bit integer type (long in Java and long long in C++). Type of the second operand does not matter for the type of shift expression, only the type of the first operand. Also parenthesis are required because without them subtraction is performed first and only then bitwise shift.
|
[
"combinatorics",
"math"
] | 1,100
| null |
630
|
D
|
Hexagons!
|
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.
Some of magic effects are able to affect several field cells at once, cells that are situated not farther than $n$ cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.
It is easy to see that the number of cells affected by a magic effect grows rapidly when $n$ increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given $n$, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than $n$ cells away from a given cell.
|
Let's count the number of cells having the distance of exactly $n$. For $n = 0$ it is $1$, for $n = 1$ it is $6$, for $n = 2$ it is $12$, for $n = 3$ it is $18$ and so on. One can notice that $n = 0$ is a special case, and then the amount increases by addition of $6$. These numbers form an arithmetic progression. In the problem we need to sum these numbers. The formula of the sum of an arithmetic progression is $(first + last) \cdot amount / 2$. The first is $6$, the last is $6n$, the amount is $n$. So the sum is $(6 + 6n)n / 2 = 3(n + 1)n$. And plus $1$ that is not in the arithmetic progression. So the final formula is $1 + 3n(n + 1)$. To avoid overflow, multiplication in the formula should be performed in 64-bit integer type. For this either $3$ or $1$ or $n$ should have 64-bit integer type. The literals are 64-bit integer when they have suffix L in Java or LL in C++.
|
[
"math"
] | 1,100
| null |
630
|
E
|
A rectangle
|
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.
More formally, if a game designer selected cells having coordinates $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$, where $x_{1} ≤ x_{2}$ and $y_{1} ≤ y_{2}$, then all cells having center coordinates $(x, y)$ such that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$ will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to $OX$ axis, all hexagon centers have integer coordinates and for each integer $x$ there are cells having center with such $x$ coordinate and for each integer $y$ there are cells having center with such $y$ coordinate. It is guaranteed that difference $x_{2} - x_{1}$ is divisible by $2$.
Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.
Help him implement counting of these units before painting.
|
Let's see how the number of affected cells changes depending on the column. For example $3, 2, 3, 2, 3$. That is it alternates between the size of the first column and the size of the first column minus one. The amount of "minus ones" is the amount of columns divided by 2 rounded down. Without "minus ones" all columns have equal size and the total amount of cells is equal to size of the first column multiplied by the number of the columns. The first column size is $(y_{2} - y_{1}) / 2 + 1$. The columns amount is $x_{2} - x_{1} + 1$. So the final formula is $((y_{2} - y_{1}) / 2 + 1) \cdot (x_{2} - x_{1} + 1) - (x_{2} - x_{1}) / 2$. To avoid overflow, multiplication should be computed in 64-bit integer type.
|
[
"math"
] | 1,900
| null |
630
|
F
|
Selection of Personnel
|
One company of IT City decided to create a group of innovative developments consisting from $5$ to $7$ people and hire new employees for it. After placing an advertisment the company received $n$ resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
|
The amount of ways to choose a group of $5$ people from $n$ candidates is equal to the number of combinations $\textstyle{\binom{n}{5}}$, the amount of ways to choose a group of $6$ people from $n$ candidates is $\textstyle{\binom{n}{6}}$, the amount of ways to choose a group of $7$ people from $n$ candidates is $\textstyle{\binom{n}{\tau}}$, the amount of ways to choose a group of $5$, $6$ or $7$ people from $n$ candidates is ${\binom{n}{5}}+{\binom{n}{6}}+{\binom{n}{7}}={\frac{n!}{(n-5)!5!}}+{\frac{n!}{(n-6)!6!}}+{\frac{n!}{(n-7)!7!}}$. To avoid 64-bit integer overflow $\frac{n!}{(n-7)!7!}$ can be calculated in the following way: n / 1 * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6 * (n - 6) / 7. Each division returns an integer because each prefix of this formula after division is also the number of combinations $\textstyle{\binom{n}{i}}$.
|
[
"combinatorics",
"math"
] | 1,300
| null |
630
|
G
|
Challenge Pennants
|
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.
Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.
Because of the limited budget of the new reward system only $5$ "I fixed a critical bug" pennants and $3$ "I suggested a new feature" pennants were bought.
In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.
One man can have several pennants of one type and of course he can have pennants of both types on his table. There are $n$ tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.
|
First of all, ways to place both types of the pennants are independent. So each way to place "I fixed a critical bug" pennants on $n$ tables is compatible to each way to place "I suggested a new feature" pennants on $n$ tables. Therefore the answer of the problem is equal to the number of ways to place "I fixed a critical bug" pennants multiplied by the number of ways to place "I suggested a new feature" pennant. The number of ways to place $k$ identical items into $n$ different places when any place can contain any amount of items is the definition of the number of $k$-combinations with repetitions or $k$-multicombinations. The formula for the number is $\frac{(n+k-1)!}{(n-1)!!}$. So the whole formula for the problem is ${\frac{(n+4)!}{(n-1)!5!}}\cdot\;{\frac{(n+2)!}{(n-1)!3!}}$. To avoid overflow of 64-bit integer type recommended formulas for computation are (n + 2) / 1 * (n + 1) / 2 * n / 3 and (n + 4) / 1 * (n + 3) / 2 * (n + 2) / 3 * (n + 1) / 4 * n / 5.
|
[
"combinatorics",
"math"
] | 1,600
| null |
630
|
H
|
Benches
|
The city park of IT City contains $n$ east to west paths and $n$ north to south paths. Each east to west path crosses each north to south path, so there are $n^{2}$ intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.
Help the park administration count the number of ways to place the benches.
|
The number of ways to choose $5$ east to west paths that will have benches from $n$ is ${\binom{n}{5}}={\frac{n!}{i n-5!!5!}}={\frac{n(n-1)(n-2)(n-3)(n-4)}{5!}}$. There are $n$ ways to place a bench on the first of these paths. Given the place of the first bench there are $n - 1$ ways to place a bench on the second of these paths because one of north to south paths is already taken. Given the places of the first and second benches there are $n - 2$ ways to place a bench on the third of these paths because two of north to south paths are already taken. And the same way $n - 3$ and $n - 4$ for the fourth and the fifth benches. Total number of ways to place benches on selected $5$ east to west path is $n(n - 1)(n - 2)(n - 3)(n - 4)$. So the formula for the problem is ${\frac{n(n-1)(n-2)(n-3)(n-4)}{5!}}\cdot n(n-1)(n-2)(n-3)(n-4)$. To avoid 64-bit integer overflow recommended order of computation is exactly as in the formula above, division should not be the last operation.
|
[
"combinatorics",
"math"
] | 1,400
| null |
630
|
I
|
Parking Lot
|
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.
The parking lot before the office consists of one line of $(2n - 2)$ parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.
Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly $n$ successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.
|
There are the following ways to place $n$ cars of the same make. They can be the first $n$, the last $n$, or they can be somewhere in the middle of the parking lot. When $n$ cars of the same make are the first or the last, there are $4$ ways to choose the make of these $n$ cars, then there are $3$ ways to choose the make of one car adjacent to them (the make should be different from the make of $n$ cars) and there are $4$ ways to choose the make of each of the remaining $n - 3$ cars. So the formula for the case of $n$ cars of the same make on either end of the parking lot is $4 \cdot 3 \cdot 4^{n - 3}$. When $n$ cars of the same make are situated somewhere in the middle, there are $4$ ways to choose the make of these $n$ cars, then there are $3$ ways to choose the make of each of two cars adjacent to them (the makes of these two cars should be different from the make of $n$ cars) and there are $4$ ways to choose the make of each of the remaining $n - 4$ cars. So the formula for the case of $n$ cars of the same make on a given position somewhere in the middle of the parking lot is $4 \cdot 3^{2} \cdot 4^{n - 4}$. There are $2$ positions of $n$ cars of the same make in the end of the parking lot and there are $n - 3$ positions of $n$ cars of the same make somewhere in the middle of the parking lot. So the final formula is $2 \cdot 4 \cdot 3 \cdot 4^{n - 3} + (n - 3) \cdot 4 \cdot 3^{2} \cdot 4^{n - 4}$.
|
[
"combinatorics",
"math"
] | 1,700
| null |
630
|
J
|
Divisibility
|
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from $2$ to $10$ every developer of this game gets a small bonus.
A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that $n$ people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.
|
Let's factorize numbers from $2$ to $10$. $2 = 2, 3 = 3, 4 = 2^{2}, 5 = 5, 6 = 2 \cdot 3, 7 = 7, 8 = 2^{3}, 9 = 3^{2}, 10 = 2 \cdot 5$. If a number is divisible by all numbers from $2$ to $10$, its factorization should contain $2$ at least in the power of $3$, $3$ at least in the power of $2$, $5$ and $7$ at least in the power of $1$. So it can be written as $x \cdot 2^{3} \cdot 3^{2} \cdot 5 \cdot 7 = x \cdot 2520$. So any number divisible by $2520$ is divisible by all numbers from $2$ to $10$. There are $\lfloor n/2520\rfloor$ numbers from $1$ to $n$ divisible by all numbers from $2$ to $10$. In a programming language it is usually implemented as simple integer division.
|
[
"math",
"number theory"
] | 1,100
| null |
630
|
K
|
Indivisibility
|
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from $2$ to $10$ every developer of this game gets a small bonus.
A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that $n$ people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.
|
The amount of numbers from $1$ to $n$ not divisible by any number from $2$ to $10$ is equal to the amount of all numbers from $1$ to $n$ (that is $n$) minus the amount of numbers from $1$ to $n$ divisible by some number from $2$ to $10$. The set of numbers from $1$ to $n$ divisible by some number from $2$ to $10$ can be found as union of the set of numbers from $1$ to $n$ divisible by $2$, the set of numbers from $1$ to $n$ divisible by $3$ and so on till $10$. Note that sets of numbers divisible by $4$ or $6$ or $8$ are subsets of the set of numbers divisible by $2$, and sets of numbers divisible by $6$ or $9$ are subsets of the set of numbers divisible by $3$. So there is no need to unite $9$ sets, it is enough to unite sets for $2, 3, 5, 7$ only. The size of set of numbers from $1$ to $n$ divisible by some of $2, 3, 5, 7$ can be calculated using inclusion-exclusion principle that says that size of each single set should be added, size of pairwise intersections should be subtracted, size of all intersections of three sets should be added and so on. The size of set of numbers from $1$ to $n$ divisible by $2$ is equal to $\left\lfloor{\frac{n}{2}}\right\rfloor$, the size of set of numbers from $1$ to $n$ divisible by $2$ and $3$ is equal to $\left\lfloor{\frac{n}{23}}\right\rfloor$ and so on. The final formula is $\begin{array}{c}{{n-\left[{\frac{n}{2}}\right]-\left[{\frac{n}{2}}\right]-\left[{\frac{n}{3}}\right]-\left[{\frac{n}{25}}\right]-\left[{\frac{n}{7}}\right]+\left[{\frac{n}{25}}\right]+\left[{\frac{n}{35}}\right]+\left[{\frac{n}{35}}\right]+\left[{\frac{n}{377}}\right]+\left[{\frac{n}{37}}\right]+\frac{n}{57}\right]+\left[{\frac{n}{357}}\right]+\frac{n}{527}}\right]+\left[{\frac{n}{152}}\right]-\right]}}\\ {{\left[{\frac{n}{23.5}}\right]-\left[{\frac{n}{23.57}}\right]-\left[{\frac{n}{357}}\right]-\left[{\frac{n}{2357}}\right]-\frac{n}{35557}}\right]}\end{array}$ Division with rounding down in the formula in a programming language is usually just integer division.
|
[
"math",
"number theory"
] | 1,500
| null |
630
|
L
|
Cracking the Code
|
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.
The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of $12345$ should lead to $13542$. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number $12345$ is $455 422 043 125 550 171 232$. The answer is the $5$ last digits of this result. For the number $12345$ the answer should be $71232$.
Vasya is going to write a keygen program implementing this algorithm. Can you do the same?
|
In this problem just implementation of the actions described in the statement is required. However there are two catches in this problem. The first catch is that the fifth power of five-digit number cannot be represented by a 64-bit integer. But we need not the fifth power, we need the fifth power modulo $10^{5}$. And $mod$ operation can be applied after each multiplication (see problem A above). The second catch is that you need to output five digits, not the fifth power modulo $10^{5}$. The difference is when fifth digit from the end is zero. To output a number with the leading zero one can either use corresponding formatting (%05d in printf) or extract digits and output them one by one.
|
[
"implementation",
"math"
] | 1,400
| null |
630
|
M
|
Turn
|
Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.
One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?
But not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.
Vasya was entrusted to correct the situation — to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.
Help Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.
The next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to "true up".
The next figure shows 90 degrees clockwise turn by FPGA hardware.
|
First of all, let's reduce camera rotation angle to $[0, 359]$ degrees range. It is accomplished by the following C++/Java code: angle = (angle % 360 + 360) % 360; Then there are the following cases: $[0, 44]$ degrees - no need to rotate, $45$ degrees - $0$ or $1$ turn to minimum deviation, minimum is $0$, $[46, 134]$ degrees - one turn required, $135$ degrees - $1$ or $2$ turns to minimum deviation, minimum is $1$, $[136, 224]$ degrees - two turns required, $225$ degrees - $2$ or $3$ turns to minimum deviation, minimum is $2$, $[226, 314]$ degrees - three turns required, $315$ degrees - $3$ or $0$ turns to minimum deviation, minimum is $0$, $[316, 359]$ degrees - no need to rotate. Let's add $44$ degrees to the angle from the range $[0, 359]$. C++/Java code is angle = (angle + 44) % 360; Then the ranges will be: $[0, 89]$ degrees - $0$ turns, $[90, 179]$ degrees - $1$ turn, $[180, 269]$ degrees - $2$ turns, $[270, 358]$ degrees - $3$ turns, $359$ degrees - $0$ turns. One special case of $359$ degrees can be eliminated by taking angle modulo $359$. Then just integer division by $90$ is required to get the answer. C++/Java code is answer = (angle % 359) / 90;
|
[
"geometry",
"math"
] | 1,800
| null |
630
|
N
|
Forecast
|
The Department of economic development of IT City created a model of city development till year 2100.
To prepare report about growth perspectives it is required to get growth estimates from the model.
To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.
The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.
|
There is nothing special in solving a quadratic equation but the problem has one catch. You should output the greater root first. The simplest approach is to output $max(x_{1}, x_{2})$ first, then $min(x_{1}, x_{2})$. Another approach is based upon the sign of $a$. $\frac{-b-\sqrt{b^{2}-4a c}}{2a}\ <\ \frac{-b+\sqrt{b^{2}-4a c}}{2a}$ for $a > 0$ and $\frac{-b-\sqrt{b^{2}-4a c}}{2a}~\gg~\frac{-b+\sqrt{b^{2}-4a c}}{2a}$ for $a < 0$. We can divide all coefficients by $a$, and then the first coefficient will be positive. But notice that division should be done in a floating point type and $a$ should be divided last otherwise resulting $a / a = 1$ would not be able to divide $b$ and $c$.
|
[
"math"
] | 1,300
| null |
630
|
O
|
Arrow
|
Petya has recently started working as a programmer in the IT city company that develops computer games.
Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.
A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates $(px, py)$, a nonzero vector with coordinates $(vx, vy)$, positive scalars $a, b, c, d, a > c$.
The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length $a$ and altitude of length $b$ perpendicular to the base. The rectangle sides lengths are $c$ and $d$. Point $(px, py)$ is situated in the middle of the triangle base and in the middle of side of rectangle that has length $c$. Area of intersection of the triangle and the rectangle is zero. The direction from $(px, py)$ point to the triangle vertex opposite to base containing the point coincides with direction of $(vx, vy)$ vector.
Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
|
To get a vector of the given length $b$ in the direction of the given vector $(vx, vy)$ it is just required to normalize the given vector (divide it by its length) and then multiply by $b$. Let's denote $l e n={\sqrt{v x^{2}+v y^{2}}}$, $vnx = vx / len$, $vny = vy / len$. Then $(vnx, vny)$ is the normalized vector, and the first point of the arrow is $(px + vnx \cdot b, py + vny \cdot b)$. To get the second point of the arrow one needs to rotate the normalized vector $90$ degrees counter-clockwise and then multiply by the half of the triangle base $a / 2$. Let's denote $vlx = - vny, vly = vnx$. Then $(vlx, vly)$ is the normalized vector $90$ degrees counter-clockwise to $(vnx, vny)$. So the second point of the arrow is $(px + vlx \cdot a / 2, py + vly \cdot a / 2)$. The third point can be found the same way as the second point but the length of the vector to it is $c / 2$. So the third point of the arrow is $(px + vlx \cdot c / 2, py + vly \cdot c / 2)$. The fourth point can be found by adding the vector of the length $c / 2$ to the left of the given and the vector of the length $d$ reverse to the given. So the fourth point of the arrow is $(px + vlx \cdot c / 2 - vnx \cdot d, py + vly \cdot c / 2 - vny \cdot d)$. The remaining points are symmetrical to the points discussed above so they can be obtained the same way, just using minus for $(vlx, vly)$ instead of plus. So the next points are $(px - vlx \cdot c / 2 - vnx \cdot d, py - vly \cdot c / 2 - vny \cdot d)$, $(px - vlx \cdot c / 2, py - vly \cdot c / 2)$, $(px - vlx \cdot a / 2, py - vly \cdot a / 2)$.
|
[
"geometry"
] | 2,000
| null |
630
|
P
|
Area of a Star
|
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.
A "star" figure having $n ≥ 5$ corners where $n$ is a prime number is constructed the following way. On the circle of radius $r$ $n$ points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.
|
$\angle C O E={\frac{2\pi}{n}}$ where $n$ in the number of the star corners because in a regular star all angles between corners are equal. $\angle B O A=\angle C O D={\frac{\angle G D}{2}}={\frac{\pi}{n}}$ because of symmetry. $\angle A E={\frac{\angle C O E}{2}}={\frac{\pi}{n}}$ because it is an inscribed angle. $\angle C A O=\angle E A O={\frac{\angle C A E}{2}}={\frac{\pi}{2n}}$ because of symmetry. So we know $OA = r$ and $\angle B A O=\angle C A O={\frac{\pi}{2n}}$ and $\angle B O A={\frac{\pi}{n}}$. We can calculate the area of $AOB$ triangle knowing the length of a side and two angles adjacent to it using formula ${\frac{O A^{2}}{2({\frac{1}{\tan2B A O}}+{\frac{1}{\tan2B O A}})}}={\frac{{r}^{2}}{2({\frac{1}{\tan2}}{\frac{1}{\pi n}}+{\frac{1}{\tan}}{\frac{\pi}{n}})}}$. The whole star area is equal to $2n$ areas of $AOB$ triangle because of symmetry. $2n\frac{r^{2}}{2(\frac{1}{\tan\frac{\pi}{2n}+\frac{1}{\tan\frac{\pi}{n}})}=\frac{n r^{2}}{(\frac{1}{\tan\frac{\pi}{2n}+\frac{1}{\tan\frac{\pi}{n}})}}{\mathrm{~}}$.
|
[
"geometry"
] | 2,100
| null |
630
|
Q
|
Pyramids
|
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.
The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.
|
The volume of a pyramid can be calculated as $v={\frac{1}{3}}s h$ where $v$ is the volume, $s$ is the area of the base and $h$ is the height from the base to the apex. Let's calculate $s$ and $h$. The area of a regular polygon having $n$ sides of length $l_{n}$ can be found the following way. On the figure above a regular polygon is shown. $O$ is the center of the polygon, all sides are equal to $l_{n}$, $OB$ is the altitude of $AOC$ triangle. As the polygon is a regular one $OA = OC$, $AOC$ triangle is a isosceles one and then $\angle A O B=\angle C O B$ and $AB = BC$, also $AOB$ and $COB$ triangles are right-angled ones. Also because the polygon is a regular one and can be seen as a union of $2n$ triangles equal to $AOB$ triangle then $\angle A O B={\frac{2\pi}{2n}}={\frac{\pi}{n}}$. $AOB$ triangle is right-angled one, so $\tan\angle A O B={\frac{A B}{O B}}$, $\sin\angle A O B={\frac{A B}{O A}}$. Also $A B={\frac{l_{n}}{2}}$. So $O B={\frac{l_{\mathrm{in}}}{2\tan{\frac{\pi}{n}}}}$ and $O A={\frac{l_{n}}{2\sin{\frac{\pi}{n}}}}$. The area of $AOB$ is equal to ${\textstyle\frac{1}{2}}A B\cdot O B={\textstyle\frac{1}{2}}\cdot{\textstyle\frac{l_{n}}{2}}\cdot{\frac{l_{n}}{2\tan{\frac{\pi}{c}}}}={\textstyle\frac{l_{n}^{2}}{8\tan{\frac{1}{2}}}}$. The area of the polygon is $s=2n{\frac{l_{\mathrm{\small~a}}^{2}}{\sin\frac{\pi}{n}}}=\frac{l_{\mathrm{\small~a}\cdot n}^{2}}{4\tan\frac{\pi}{n}}$. On the figure above a triangle formed by the pyramid apex $H$, the center of the base $O$ and some vertex of the base $A$ is shown. It is a right-angled one. As all edges of the pyramid are equal, $AH = l_{n}$ and from calculations above $O A={\frac{l_{n}}{2\sin{\frac{\pi}{n}}}}$. According to Pythagorean theorem $OA^{2} + OH^{2} = AH^{2}$. So $O H={\sqrt{A H^{2}-O A^{2}}}={\sqrt{l_{n}^{2}-{\frac{l_{n}^{2}}{4\sin^{2}{\frac{\pi}{n}}}}}}=l_{n}{\sqrt{1-{\frac{1}{4\sin^{2}{\frac{\pi}{n}}}}}}$. The volume of one piramid is $\frac{1}{3}\cdot\frac{l_{n}^{2}.n}{4\tan\frac{\pi}{n}}\cdot l_{n}\sqrt{1-\frac{1}{4\sin^{2}\frac{\pi}{n}}}=\frac{l_{n}^{3}.n}{12\tan\frac{\pi}{n}}\sqrt{1-\frac{1}{4\sin^{2}\frac{\pi}{n}}}$. And the final formula is ${\frac{l_{3}^{3}.3}{12\tan{\frac{\pi}{3}}}}\sqrt{1-{\frac{1}{4\sin^{2}{\frac{\pi}{3}}}}}+{\frac{l_{4}^{3}.4}{12\tan{\frac{\pi}{4}}}}\sqrt{1-{\frac{1}{4\sin^{2}{\frac{\pi}{4}}}}}+{\frac{l_{3}^{3}.5}{12\tan{\frac{\pi}{5}}}}\sqrt{1-{\frac{1}{4\sin^{2}{\frac{\pi}{5}}}}}$.
|
[
"geometry",
"math"
] | 1,700
| null |
630
|
R
|
Game
|
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.
The game is played on a square field consisting of $n × n$ cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.
The professor have chosen the field size $n$ and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.
|
For the field of an even size there is a winning strategy for the second player. Namely, to paint a cell that is symmetrical with respect to the center of the field to the cell painted by the first player on the previous turn. After each turn of the second player the field is centrosymmetrical and so there is always a cell that can be painted that is symmetrical with respect to the center of the field to any cell that the first player can choose to paint. For the field of an odd size there is a winning strategy for the first player. Namely, on the first turn to paint the central cell, then to paint a cell that is symmetrical with respect to the center of the field to the cell painted by the second player on the previous turn. After each turn of the first player the field is centrosymmetrical and so there is always a cell that can be painted that is symmetrical with respect to the center of the field to any cell that the second player can choose to paint. So for even $n$ the answer is 2, for odd $n$ the answer is 1. One of the possible formulas for the problem is $2-(n\mod2)$. $n$ can be up to $10^{18}$ so at least 64-bit integer type should be used to input it.
|
[
"games",
"math"
] | 1,200
| null |
631
|
A
|
Interview
|
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function $f(x, l, r)$ as a bitwise OR of integers $x_{l}, x_{l + 1}, ..., x_{r}$, where $x_{i}$ is the $i$-th element of the array $x$. You are given two arrays $a$ and $b$ of length $n$. You need to determine the maximum value of sum $f(a, l, r) + f(b, l, r)$ among all possible $1 ≤ l ≤ r ≤ n$.
|
You should know only one fact to solve this task: $X\vee Y\geq X$. This fact can be proved by the truth table. Let's use this fact: $f(a,1,i-1)\vee f(a,i,j)\vee f(a,j+1,N)\ge f(a,i,j)$. Also $f(a,1,i-1)\vee f(a,i,j)\vee f(a,j+1,n)=f(a,1,n)$. According two previous formulas we can get that $f(a, 1, n) \ge f(a, i, j)$. Finally we can get the answer. It's equal to $f(a, 1, N) + f(b, 1, N)$. Time: ${\mathcal{O}}(n)$ Memory: ${\cal O}(n)$
|
[
"brute force",
"implementation"
] | 900
|
from functools import reduce
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
print(reduce(lambda x, y: x | y, a) + reduce(lambda x, y: x | y, b))
|
631
|
B
|
Print Check
|
Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.
Printer works with a rectangular sheet of paper of size $n × m$. Consider the list as a table consisting of $n$ rows and $m$ columns. Rows are numbered from top to bottom with integers from $1$ to $n$, while columns are numbered from left to right with integers from $1$ to $m$. Initially, all cells are painted in color $0$.
Your program has to support two operations:
- Paint all cells in row $r_{i}$ in color $a_{i}$;
- Paint all cells in column $c_{i}$ in color $a_{i}$.
If during some operation $i$ there is a cell that have already been painted, the color of this cell also changes to $a_{i}$.
Your program has to print the resulting table after $k$ operation.
|
Let's define $timeR_{i}$ as a number of last query, wich repaint row with number $i$, $timeC_{j}$ - as number of last query, wich repaint column with number $j$. The value in cell $(i, j)$ is equal $a_{max(timeRi, timeCj)}$. Time: $O(n\cdot m+k)$ Memory: $O(n+m+k)$
|
[
"constructive algorithms",
"implementation"
] | 1,200
|
n, m, q = map(int,input().split())
timeR, timeC, color = [0] * n, [0] * m, [0] * (q + 1)
for query in range(1, q + 1):
typeQ, posQ, color[query] = map(int, input().split())
if typeQ == 1:
timeR[posQ - 1] = query
else:
timeC[posQ - 1] = query
for i in range(n):
out = str()
for j in range(m):
out += str(color[max(timeR[i], timeC[j])])
out += " "
print(out)
|
631
|
C
|
Report
|
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are $n$ commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of $m$ managers. Each of them may reorder the elements in some order. Namely, the $i$-th manager either sorts first $r_{i}$ numbers in non-descending or non-ascending order and then passes the report to the manager $i + 1$, or directly to Blake (if this manager has number $i = m$).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence $a_{i}$ of length $n$ and the description of each manager, that is value $r_{i}$ and his favourite order. You are asked to speed up the process and determine how the final report will look like.
|
If we have some pair of queries that $r_{i} \ge r_{j}$, $i > j$, then we can skip query with number $j$. Let's skip such queries. After that we get an array of sorted queries ($r_{i} \le r_{j}$, $i > j$). Let's sort subarray $a_{1..max(ri)}$ and copy it to $b$. For proccessing query with number $i$ we should record to $a_{ri - 1..ri}$ first or last(it depends on $t_{i - 1}$) $r_{i - 1} - r_{i} + 1$ elementes of $b$. After that this elements should be extract from $b$. You should remember that you need to sort subarray $a_{1..rn}$, after last query. Time: $O(n\cdot l o g(n)+m)$ Memeory: $O(n+m)$
|
[
"data structures",
"sortings"
] | 1,700
|
n, m = map(int,input().split())
a = list(map(int,input().split()))
t = list()
b = list()
for i in range(m):
x, y = map(int,input().split())
while len(t) > 0 and y >= t[-1][1]:
t.pop()
t.append([x, y])
x, y = 0, t[0][1] - 1
t.append([0, 0])
b = sorted(a[: y + 1])
for i in range(1, len(t)):
for j in range(t[i - 1][1], t[i][1], -1):
if t[i - 1][0] == 1:
a[j - 1] = b[y]
y -= 1
else:
a[j - 1] = b[x]
x += 1
print (" ".join(list(str(i) for i in a)))
|
631
|
D
|
Messenger
|
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.
All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of $n$ blocks, each block containing only equal characters. One block may be described as a pair $(l_{i}, c_{i})$, where $l_{i}$ is the length of the $i$-th block and $c_{i}$ is the corresponding letter. Thus, the string $s$ may be written as the sequence of pairs $\langle\left(l_{1},c_{1}\right),\left(l_{2},c_{2}\right),...,\left(l_{n},c_{n}\right)\rangle$.
Your task is to write the program, that given two compressed string $t$ and $s$ finds all occurrences of $s$ in $t$. Developers know that there may be many such occurrences, so they only ask you to find the \textbf{number} of them. Note that $p$ is the starting position of some occurrence of $s$ in $t$ if and only if $t_{p}t_{p + 1}...t_{p + |s| - 1} = s$, where $t_{i}$ is the $i$-th character of string $t$.
Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as $\langle\!\langle(4,a)\rangle$, $\langle(3,a),(1,a)\rangle$, $\langle(2,a),(2,a)\rangle$...
|
Let's define $S_{}[i]$ as $i - th$ block of $S$, $T_{}[i]$ - as $i - th$ block of $T$.Also $S_{}[l..r] = S_{}[l]S_{}[l + 1]...S_{}[r]$ and $T_{}[l..r] = T_{}[l]T_{}[l + 1]...T_{}[r]$. $T$ is substring of $S$, if $S_{}[l + 1..r - 1] = T_{}[2..m - 1]$ and $S_{}[l].l = T_{}[1].l$ and $S_{}[l].c \ge T_{}[1].c$ and $S_{}[r].l = T_{}[m].l$ and $S_{}[r].c \ge T_{}[m].c$. Let's find all matches of $T_{}[l + 1..r - 1]$ in $S$ and chose from this matches, witch is equal $T$.You can do this by Knuth-Morris-Pratt algorithm. This task has a some tricky test cases: $S=10^{6}-a\quad10^{6}-a\quad\ldots\quad10^{6}-a$ and $T=1-a$. Answer for this test should be stored at long long. Time: $O(n+m)$ Memory: $O(n+m)$
|
[
"data structures",
"hashing",
"implementation",
"string suffix structures",
"strings"
] | 2,100
|
def ziped(a):
p = []
for i in a:
x = int(i.split('-')[0])
y = i.split('-')[1]
if len(p) > 0 and p[-1][1] == y:
p[-1][0] += x
else:
p.append([x, y])
return p
def solve(a, b , c):
ans = 0
if len(b) == 1:
for token in a:
if c(token, b[0]):
ans += token[0] - b[0][0] + 1
return ans
if len(b) == 2:
for i in range(len(a) - 1):
if c(a[i], b[0]) and c(a[i + 1], b[-1]):
ans += 1
return ans
v = b[1 : -1] + [[100500, '#']] + a
p = [0] * len(v)
for i in range(1, len(v)):
j = p[i - 1]
while j > 0 and v[i] != v[j]:
j = p[j - 1]
if v[i] == v[j]:
j += 1
p[i] = j
for i in range(len(v) - 1):
if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]):
ans += 1
return ans
n, m = map(int, input().split())
a = ziped(input().split())
b = ziped(input().split())
print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0]))
|
631
|
E
|
Product Sum
|
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array $a$ of length $n$. The characteristic of this array is the value $c=\sum_{i=1}^{n}a_{i}\cdot i$ — the sum of the products of the values $a_{i}$ by $i$. One may perform the following operation \textbf{exactly once}: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
|
$O(n^{2}):$ The operation, which has been described in the statement, is cyclic shift of some subarray. Let's try to solve this problem separately for left cyclic shift and for right cyclic shift. Let's define $a n s^{\prime}=\sum_{i=1}^{n}a_{i}\cdot i$ as answer before(or without) cyclic shift, $ \Delta ans = ans - ans'$ - difference between answer after cyclic shift and before. This difference can be found by next formulas: For left cyclic shift: $ \Delta _{l, r} = (a_{l} \cdot r + a_{l + 1} \cdot l + ... + a_{r} \cdot (r - 1)) - (a_{l} \cdot l + a_{l + 1} \cdot (l + 1) + ... + a_{r} \cdot r) = a_{l} \cdot (r - l) - (a_{l + 1} + a_{l + 2} + ... + a_{r})$ For right cyclic shift: $ \Delta '_{l, r} = (a_{l} \cdot (l + 1) + a_{l + 1} \cdot (l + 2) + ... + a_{r} \cdot l) + (a_{l} \cdot l + a_{l + 1} \cdot (l + 1) + ... + a_{r} \cdot r) = (a_{l} + a_{l + 1} + ... + a_{r - 1}) + a_{r} \cdot (l - r)$ You can find this values with complexity $O(1)$, using prefix sums, $s u m_{r}=\sum_{i=1}^{r}a_{i}$. ${\cal O}(n\cdot l o g(n)):$ Let's try to rewrite previous formulas: For left cyclic shift: $ \Delta _{l, r} = (a_{l} \cdot r - sum_{r}) + (sum_{l} - a_{l} \cdot l)$ For right cyclic shift: $ \Delta '_{l, r} = (a_{r} \cdot l - sum_{l - 1}) + (sum_{r - 1} - a_{r} \cdot r)$ You can see, that if you fix $l$ for left shift and $r$ for right shift, you can solve this problem with complexity $O(n\cdot l o g(n))$ using Convex Hull Trick. Time: $O(n\cdot l o g(n))$ Memory: ${\cal O}(n)$
|
[
"data structures",
"dp",
"geometry"
] | 2,600
|
#include <cstdio>
#include <algorithm>
typedef long long Long;
struct Line {
Long a, b, get(Long x) { return a * x + b; }
};
struct ConvexHull {
int size;
Line *hull;
ConvexHull(int maxSize) {
hull = new Line[++maxSize], size = 0;
}
bool is_bad(Long curr, Long prev, Long next) {
Line c = hull[curr], p = hull[prev], n = hull[next];
return (c.b - n.b) * (c.a - p.a) <= (p.b - c.b) * (n.a - c.a);
}
void add_line(Long a, Long b) {
hull[size++] = (Line){a, b};
while (size > 2 && is_bad(size - 2, size - 3, size - 1))
hull[size - 2] = hull[size - 1], size--;
}
Long query(Long x) {
int l = -1, r = size - 1;
while (r - l > 1) {
int m = (l + r) / 2;
if (hull[m].get(x) <= hull[m + 1].get(x))
l = m;
else
r = m;
}
return hull[r].get(x);
}
};
const int N = (int)2e5 + 1;
int n, a[N];
Long sum[N];
Long ans, dans;
ConvexHull *hull;
int main() {
scanf("%d", &n);
hull = new ConvexHull(n);
sum[0] = ans = dans = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
sum[i] = sum[i - 1] + a[i];
ans += a[i] * (long long)i;
}
hull->size = 0;
for (int r = 2; r <= n; r++) {
hull->add_line(r - 1, -sum[r - 2]);
dans = std::max(dans, hull->query(a[r]) + sum[r - 1] - a[r] * (long long)r);
}
hull->size = 0;
for (int l = n - 1; l >= 1; l--) {
hull->add_line(-(l + 1), -sum[l + 1]);
dans = std::max(dans, hull->query(-a[l]) + sum[l] - a[l] * (long long)l);
}
printf("%I64d", ans + dans);
return 0;
}
|
632
|
A
|
Grandma Laura and Apples
|
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had $n$ buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.
So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).
For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is $p$ (the number $p$ is even).
Print the total money grandma should have at the end of the day to check if some buyers cheated her.
|
Consider the process from the end. The last buyer will always buy a half of an apple and get a half for free (so the last string always is halfplus). After that each buyer increases the number of apples twice and also maybe by one. So we simply have the binary presentation of the number of apples from the end. To calculate the answer we should simply restore that value from the end and also calculate the total money grandma should have. Complexity: $O(p)$.
|
[] | 1,200
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\n\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 44;\n\nint n, p;\narray<string, N> a;\n\ninline bool read() {\n\tif (!(cin >> n >> p)) return false;\n\tforn(i, n) assert(cin >> a[i]);\n\treturn true;\n}\n\ninline void solve() {\n\treverse(a.begin(), a.begin() + n);\n\tli ans = 0, k = 0;\n\tforn(i, n) {\n\t\tk *= 2;\n\t\tif (a[i] == \"halfplus\") k++;\n\t\tans += k * p / 2;\n\t}\n\tcerr << \"cnt=\" << k << endl;\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
632
|
B
|
Alice, Bob, Two Teams
|
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are $n$ pieces, and the $i$-th piece has a strength $p_{i}$.
The way to split up game pieces is split into several steps:
- First, Alice will split the pieces into two different groups $A$ and $B$. This can be seen as writing the assignment of teams of a piece in an $n$ character string, where each character is $A$ or $B$.
- Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change $A$ to $B$ and $B$ to $A$). He can do this step at most once.
- Alice will get all the pieces marked $A$ and Bob will get all the pieces marked $B$.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
|
Let's calculate the prefix sums for all numbers (and store it in array $s1$) and for numbers with letter B (and store it in array $s2$). Now we can find the sum of all numbers in any segment in $O(1)$ time and the sum of numbers with letter B. Let's iterate over prefix or suffix to flip and calculate the sum in that case by formulas: $sum(s1, 0, n - 1) + sum(s2, 0, i) - 2 \cdot sum(s1, 0, i)$ for prefixes and $sum(s1, 0, n - 1) + sum(s2, i, n - 1) - 2 \cdot sum(s1, i, n - 1)$ for suffixes. Complexity: $O(n)$.
|
[
"brute force",
"constructive algorithms"
] | 1,400
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\n\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 500500;\n\nint n, p[N];\nchar s[N];\n\ninline bool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &p[i]) == 1);\n\tassert(gets(s));\n\tassert(gets(s));\n\treturn true;\n}\n\nli s1[N], s2[N];\n\ninline void solve() {\n\tforn(i, n) s1[i + 1] = s1[i] + (s[i] == 'B' ? p[i] : 0);\n\tforn(i, n) s2[i + 1] = s2[i] + p[i];\n\t\n\tauto sum = [](li* s, int l, int r) { return s[r + 1] - s[l]; };\n\n\tli ans = 0;\n\tforn(i, n) {\n\t\tans = max(ans, sum(s2, 0, i) - 2 * sum(s1, 0, i));\n\t\tans = max(ans, sum(s2, i, n - 1) - 2 * sum(s1, i, n - 1));\n\t}\n\tans += sum(s1, 0, n - 1);\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
632
|
C
|
The Smallest String Concatenation
|
You're given a list of $n$ strings $a_{1}, a_{2}, ..., a_{n}$. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.
Given the list of strings, output the lexicographically smallest concatenation.
|
The proof of the transitivity also belongs to him. Let's sort all the strings by comparator $a + b < b + a$ and concatenate them. Let's prove that it's the optimal answer. Let that operator be transitive (so if $a<n\wedge b<c\Rightarrow a<c$). Consider an optimal answer with two strings in reverse order by that operator. Because of the transitivity of operator we can assume that pair of strings are neighbouring. But then we can swap them and get the better answer. Let's prove the transitivity of operator. Consider the strings as the $26$-base numbers. Then the relation $a + b < b + a$ equivalent to $a\cdot26^{\left[b\right]}+b<b\cdot26^{\left[a\right]}+a\Leftrightarrow\frac{a}{26^{\left[a\right]}-1}<\frac{b}{26^{\left[b\right]}-1}$. The last is simply the relation between real numbers. So we proved the transitivity of the relation $a + b < b + a$. Complexity: $O(nLlogn)$, where $L$ is the maximal string length.
|
[
"sortings",
"strings"
] | 1,700
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\n\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 500500, L = 111;\n\nint n;\nstring a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) {\n\t\tstatic char buf[L];\n\t\tassert(scanf(\"%s\", buf) == 1);\n\t\ta[i] = string(buf);\n\t}\n\treturn true;\n}\n\ninline bool cmp(const string& a, const string& b) {\n\treturn a + b < b + a;\n}\n\nvoid solve() {\n\tsort(a, a + n, cmp);\n\tstring ans = accumulate(a, a + n, string());\n\tputs(ans.c_str());\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
632
|
D
|
Longest Subsequence
|
You are given array $a$ with $n$ elements and the number $m$. Consider some subsequence of $a$ and the value of least common multiple (LCM) of its elements. Denote LCM as $l$. Find any longest subsequence of $a$ with the value $l ≤ m$.
A subsequence of $a$ is an array we can get by erasing some elements of $a$. It is allowed to erase zero or all elements.
The LCM of an empty array equals $1$.
|
Let $cnt_{x}$ be the number of occurences of the number $x$ in the given array (easy to see that we can ignore the numbers greater than $m$). Let's iterate over $x={\overline{{1.m}}}$ and $1 \le k, x \cdot k \le m$ and increase the value in the position $k \cdot x$ in some array $z$ by the value $cnt_{x}$. So the value $z_{l}$ equals the number of numbers in the given array which divide $l$. Let's find the minimal $l$ with the maximum value $z_{l}$ ($1 \le l \le m$). Easy to see that the answer to the problem is the numbers which divide $l$. Let's calculate the complexity of the solution. The number of the pairs $(k, x)$ we can bound with the value $m+{\frac{m}{2}}+{\frac{m}{3}}+\cdot\cdot\cdot{\frac{m}{m}}=O(m l o g m)$. Complexity: $O(n + mlogm)$.
|
[
"brute force",
"math",
"number theory"
] | 2,100
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\n\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 1200300;\n\nint n, m;\narray<int, N> a;\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\narray<int, N> cnt;\narray<int, N> z;\n\ninline void solve() {\n\tforn(i, m + 1) cnt[i] = z[i] = 0;\n\tforn(i, n) if (a[i] < N) cnt[a[i]]++;\n\tfore(i, 1, m + 1)\n\t\tfor (int j = i; j <= m; j += i)\n\t\t\tz[j] += cnt[i];\n\tint ansv = -1, ansl = -1;\n\tfore(l, 1, m + 1)\n\t\tif (ansv < z[l])\n\t\t\tansv = z[l], ansl = l;\n\tassert(ansl != -1);\n\tcout << ansl << ' ' << ansv << endl;\n\tbool f = true;\n\tforn(i, n)\n\t\tif (ansl % a[i] == 0) {\n\t\t\tif (f) f = false;\n\t\t\telse putchar(' ');\n\t\t\tprintf(\"%d\", i + 1);\n\t\t\tansv--;\n\t\t}\n\tputs(\"\");\n\tassert(!ansv);\n\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
632
|
E
|
Thief in a Shop
|
A thief made his way to a shop.
As usual he has his lucky knapsack with him. The knapsack can contain $k$ objects. There are $n$ kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind $i$ is $a_{i}$.
The thief is greedy, so he will take exactly $k$ products (it's possible for some kinds to take several products of that kind).
Find all the possible total costs of products the thief can nick into his knapsack.
|
Let $k = 2$, then it is the standard problem which can be solved by FFT (Fast Fourier Transform). The solution is the following: consider the polynomial which the $i$-th coefficient equals to one if and only if there is the number $i$ in the given array. Let's multiply that polynomial by itself and find $i$ for which the coefficient in square not equals to $0$. Those values $i$ will be in the answer. Easy to modificate the solution for the arbitrary $k$. We should simply calculate the $k$-th degree of the polynomial. The complexity will be $WlogWlogk$, where $W$ is the maximal sum. We can improve that solution. Instead of calculating the $k$-th degree of the polynomial we can calculate the $k$-th degree of the DFT of the polynomial. The only problem is the large values of the $k$-th degrees. We can't use FFT with complex numbers, because of the precision problems. But we can do that with NTT (Number-theoretic transform). But that solution also has a problem. It can happen that some coefficients became equals to zero modulo $p$, but actually they are not equal to zero. To get round that problem we can choose two-three random modules and get the complexity $O(W(logW + logk))$. The main author solution has the complexity $O(WlogWlogk)$ (FFT with complex numbers), the second solution has the same complexity, but uses NTT and the third solution has the improved complexity (but it was already hacked by halyavin). P.S.: To get faster solution you should each time multiply the polynomials of the required degree, but not of the degree $2^{20}$. Complexity: $O(WlogWlogk)$ or $O(W(logW + logk))$, depending the bravery of the coder :-) UPD: It turns out that the first approach also has complexity $O(W(logW + logk))$. See below the comment of halyavin.
|
[
"divide and conquer",
"dp",
"fft",
"math"
] | 2,400
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\n\ninline ld gett() { return ld(clock()) / CLOCKS_PER_SEC; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint n, k;\nvector<int> a;\n\nbool read() {\n\tif (!(cin >> n >> k)) return false;\n\ta.resize(n);\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nstruct base {\n\tld re, im;\n\tbase() { }\n\tbase(ld re, ld im): re(re), im(im) { }\n\tld slen() const { return sqr(re) + sqr(im); }\n\tld real() { return re; }\n};\n\ninline base conj(const base& a) { return base(a.re, -a.im); }\ninline base operator+ (const base& a, const base& b) { return base(a.re + b.re, a.im + b.im); }\ninline base operator- (const base& a, const base& b) { return base(a.re - b.re, a.im - b.im); }\ninline base operator* (const base& a, const base& b) { return base(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re); }\ninline base operator/ (const base& a, const ld& b) { return base(a.re / b, a.im / b); }\ninline base operator/ (const base& a, const base& b) { return base(a.re * b.re + a.im * b.im, a.im * b.re - a.re * b.im) / b.slen(); }\ninline base& operator/= (base& a, const ld& b) { a.re /= b, a.im /= b; return a; }\n\nint reverse(int x, int logn) {\n\tint ans = 0;\n\tforn(i, logn) if (x & (1 << i)) ans |= 1 << (logn - 1 - i);\n\treturn ans;\n}\n\nconst int LOGN = 20, N = (1 << LOGN) + 3;\nvoid fft(base a[N], int n, bool inv) {\n\tstatic base vv[LOGN][N];\n\tstatic bool prepared = false;\n\tif (!prepared) {\n\t\tprepared = true;\n\t\tforn(i, LOGN) {\n\t\t\tld ang = 2 * PI / (1 << (i + 1));\n\t\t\tforn(j, 1 << i) vv[i][j] = base(cos(ang * j), sin(ang * j));\n\t\t}\n\t}\n\tint logn = 0; while ((1 << logn) < n) logn++;\n\tforn(i, n) {\n\t\tint ni = reverse(i, logn);\n\t\tif (i < ni) swap(a[i], a[ni]);\n\t}\n\tfor (int i = 0; (1 << i) < n; i++)\n\t\tfor (int j = 0; j < n; j += (1 << (i + 1)))\n\t\t\tfor (int k = j; k < j + (1 << i); k++) {\n\t\t\t\tbase cur = inv ? conj(vv[i][k - j]) : vv[i][k - j];\n\t\t\t\tbase l = a[k], r = cur * a[k + (1 << i)];\n\t\t\t\ta[k] = l + r;\n\t\t\t\ta[k + (1 << i)] = l - r;\n\t\t\t}\n\tif (inv) forn(i, n) a[i] /= ld(n);\n}\n\nvoid mul(int a[N], int b[N], int ans[N]) {\n\tstatic base fp[N], p1[N], p2[N];\n\tint n = 1 << LOGN, m = 1 << LOGN;\n\twhile (n && !a[n - 1]) n--;\n\twhile (m && !b[m - 1]) m--;\n\tint cnt = n + m;\n\twhile (cnt & (cnt - 1)) cnt++;\n\tif (cnt > (1 << LOGN)) return;\n\t\n\tforn(i, cnt) fp[i] = base(a[i], b[i]);\n\tfft(fp, cnt, false);\n\tforn(i, cnt) {\n\t\tp1[i] = (fp[i] + conj(fp[(cnt - i) % cnt])) / base(2, 0);\n\t\tp2[i] = (fp[i] - conj(fp[(cnt - i) % cnt])) / base(0, 2);\n\t}\n\tforn(i, cnt) fp[i] = p1[i] * p2[i];\n\tfft(fp, cnt, true);\n\n\tforn(i, cnt) ans[i] = int(fp[i].real() + 0.5);\n}\n\nvoid mul(int* a, int* b) {\n\tforn(i, 1 << LOGN) {\n\t\ta[i] = !!a[i];\n\t\tb[i] = !!b[i];\n\t}\n\tmul(a, b, a);\n}\n\nvoid binPow(int* a, int b) {\n\tstatic int ans[N];\n\tforn(i, 1 << LOGN) ans[i] = !i;\n\twhile (b) {\n\t\tif (b & 1) mul(ans, a);\n\t\tmul(a, a);\n\t\tb >>= 1;\n\t}\n\tforn(i, 1 << LOGN) a[i] = ans[i];\n}\n\nvoid solve() {\n\tstatic int ans[N];\n\tmemset(ans, 0, sizeof(ans));\n\tforn(i, sz(a)) ans[a[i]] = 1;\n\n\tbinPow(ans, k);\n\n\tbool f = true;\n\tforn(i, 1 << LOGN)\n\t\tif (ans[i]) {\n\t\t\tif (f) f = false;\n\t\t\telse putchar(' ');\n\t\t\tprintf(\"%d\", i);\n\t\t}\n\tputs(\"\");\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
632
|
F
|
Magic Matrix
|
You're given a matrix $A$ of size $n × n$.
Let's call the matrix with nonnegative elements magic if it is symmetric (so $a_{ij} = a_{ji}$), $a_{ii} = 0$ and $a_{ij} ≤ max(a_{ik}, a_{jk})$ for all triples $i, j, k$. Note that $i, j, k$ do not need to be distinct.
Determine if the matrix is magic.
As the input/output can reach very huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
Consider the undirected complete graph with $n$ nodes, with an edge between nodes $i, j$ with cost $a_{ij}$. Let $B_{ij}$ denote the minimum possible value of the max edge of a path from $i$ to $j$. We know that $a_{ij} \ge B_{ij}$ by definition. If the matrix is magic, we can choose arbitrary $k_{1}, k_{2}, ..., k_{m}$ such that $a_{ij} \le max(a_{i, k1}, a_{k1, k2}, ..., a_{km, j})$ by repeating invocations of the inequality given. Also, you can show that if this inequality is satisfied, then the matrix is magic (by choosing an $m = 1$ and $k_{1}$ arbitrary). So, this shows that the matrix is magic if and only if $a_{ij} \le B_{ij}$. Thus, combining with $a_{ij} \ge B_{ij}$, we have $a_{ij} = B_{ij}$. We need a fast way to compute $B_{ij}$ for all pairs $i, j$. This can be computed as the MST, as the path in the MST minimizes the max edge between all pairs of nodes. So, the algorithm works as follows. First, find the MST on the complete graph. Then, the matrix is magic if and only if the max edge on the path between $i, j$ in the MST is exactly equal to $a_{i, j}$. Also you shouldn't forget to check symmetry of the matrix and diagonal for zeros. P.S.: Unfortunately we couldn't increase the value $n$ in this problem: the tests already had the size about 67MB and they couldn't be given with generator. So most of the users who solved this problem uses bitset-s. The complexity of their solution is $O({\underline{{n}}}_{b}^{s})$, where $b = 32$ or $b = 64$. Complexity: $O(n^{2}logn)$ or $O(n^{2})$.
|
[
"brute force",
"divide and conquer",
"graphs",
"matrices",
"trees"
] | 2,400
|
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \"[\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \" ]\"; } \ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\ntemplate<typename T> inline ostream& operator<< (ostream& out, pair<T*, int> a) { return out << vector<T>(a.x, a.x + a.y); }\n\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 2525, LOGN = 15;\n\nint n, a[N][N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) forn(j, n) assert(scanf(\"%d\", &a[i][j]) == 1);\n\treturn true;\n}\n\nint tt, tin[N], tout[N];\nvector<int> g[N];\n\nvoid dfs(int v) {\n\ttin[v] = tt++;\n\tforn(i, sz(g[v])) dfs(g[v][i]);\n\ttout[v] = tt;\n}\n\ninline bool parent(int a, int b) { return tin[a] <= tin[b] && tout[b] <= tout[a]; }\n\nint p[LOGN][N], pd[LOGN][N];\n\nint d[N], pr[N];\nbool used[N];\n\nint calc(int a, int b) {\n\tint ans = 0;\n\tnfor(i, LOGN) {\n\t\tif (!parent(p[i][a], b)) {\n\t\t\tans = max(ans, pd[i][a]);\n\t\t\ta = p[i][a];\n\t\t}\n\t\tif (!parent(p[i][b], a)) {\n\t\t\tans = max(ans, pd[i][b]);\n\t\t\tb = p[i][b];\n\t\t}\n\t}\n\tif (!parent(a, b)) ans = max(ans, pd[0][a]);\n\tif (!parent(b, a)) ans = max(ans, pd[0][b]);\n\treturn ans;\n}\n\nvoid solve() {\n\tforn(i, n)\n\t\tforn(j, n)\n\t\t\tif (a[i][j] != a[j][i] || (i == j && a[i][j])) {\n\t\t\t\tputs(\"NOT MAGIC\");\n\t\t\t\treturn;\n\t\t\t}\n\n\tforn(i, n) {\n\t\tused[i] = false;\n\t\td[i] = INT_MAX;\n\t\tg[i].clear();\n\t}\n\n\td[0] = 0;\n\tpr[0] = -1;\n\tforn(i, n) {\n\t\tint v = -1;\n\t\tforn(j, n)\n\t\t\tif (!used[j] && (v == -1 || d[v] > d[j]))\n\t\t\t\tv = j;\n\n\t\tassert(v != -1);\n\t\tused[v] = true;\n\t\t//cerr << \"v=\" << v << \" p[v]=\" << pr[v] << endl;\n\n\t\tif (pr[v] != -1) {\n\t\t\tp[0][v] = pr[v];\n\t\t\tpd[0][v] = a[pr[v]][v];\n\t\t\tg[pr[v]].pb(v);\n\t\t} else {\n\t\t\tp[0][v] = v;\n\t\t\tpd[0][v] = 0;\n\t\t}\n\n\t\tforn(j, n)\n\t\t\tif (!used[j] && d[j] > a[v][j]) {\n\t\t\t\td[j] = a[v][j];\n\t\t\t\tpr[j] = v;\n\t\t\t}\n\t}\n\n\t//cerr << mp(pr, n) << endl;\n\n\ttt = 0;\n\tdfs(0);\n\n\tfore(i, 1, LOGN)\n\t\tforn(j, n) {\n\t\t\tp[i][j] = p[i - 1][p[i - 1][j]];\n\t\t\tpd[i][j] = max(pd[i - 1][j], pd[i - 1][p[i - 1][j]]);\n\t\t}\n\n\tforn(i, n)\n\t\tforn(j, n)\n\t\t\tif (a[i][j] != calc(i, j)) {\n\t\t\t\tputs(\"NOT MAGIC\");\n\t\t\t\treturn;\n\t\t\t}\n\tputs(\"MAGIC\");\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << \"Time: \" << gett() - stime << endl;\n\t\t//break;\n\t}\n\t\n return 0;\n}"
|
633
|
A
|
Ebony and Ivory
|
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots.
For every bullet that hits the shield, Ebony deals $a$ units of damage while Ivory deals $b$ units of damage. In order to break the shield Dante has to deal \textbf{exactly} $c$ units of damage. Find out if this is possible.
|
The problem is to find if there exists a solution to the equation: $ax + by = c$ where x and y are both positive integers. The limits are small enough to try all values of x and correspondingly try if such a y exists. The question can also be solved more efficiently using the fact that an integral solution to this problem exists iff $gcd(a, b)|c$. We just have to make one more check to ensure a positive integral solution. Complexity: $O(log(min(a, b))$
|
[
"brute force",
"math",
"number theory"
] | 1,100
| null |
633
|
B
|
A Trivial Problem
|
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer $m$ and asks for the number of positive integers $n$, such that the factorial of $n$ ends with exactly $m$ zeroes. Are you among those great programmers who can solve this problem?
|
We know how to calculate number of zeros in the factorial of a number. For finding the range of numbers having number of zeros equal to a constant, we can use binary search. Though, the limits are small enough to try and find the number of zeros in factorial of all numbers of the given range. Complexity: $O(log(n)^{2})$
|
[
"brute force",
"constructive algorithms",
"math",
"number theory"
] | 1,300
| null |
633
|
C
|
Spy Syndrome 2
|
After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.
For a given sentence, the cipher is processed as:
- Convert all letters of the sentence to lowercase.
- Reverse each of the words of the sentence individually.
- Remove all the spaces in the sentence.
For example, when this cipher is applied to the sentence
Kira is childish and he hates losing
the resulting string is
ariksihsidlihcdnaehsetahgnisol
Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.
|
The given encrypted string can be reversed initially. Then $dp[i]$ can be defined as the index at which the next word should start such that the given string can be formed using the given dictionary. Rabin Karp hashing can be used to compute $dp[i]$ efficiently. Also, care must be taken that in the answer the words have to be printed in the correct casing as they appear in the dictionary. Complexity: $O(n * w)$ where $n$ is the length of the encrypted string, $w$ is the maximum length of any word in the dictionary.
|
[
"data structures",
"dp",
"hashing",
"implementation",
"sortings",
"string suffix structures",
"strings"
] | 1,900
| null |
633
|
D
|
Fibonacci-ish
|
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
- the sequence consists of at least two elements
- $f_{0}$ and $f_{1}$ are arbitrary
- $f_{n + 2} = f_{n + 1} + f_{n}$ for all $n ≥ 0$.
You are given some sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
|
The key to the solution is that the complete Fibonacci-ish sequence is determined by the first two terms. Another thing to note is that for the given constraints on $a[i]$, the length of the Fibonacci-ish sequence is of logarithmic order (the longest sequence possible under current constraints was of length~90) except for the case where $a[i] = a[j] = 0$, where the length can become as long as the length of the given sequence. Thus, the case for 0 has to be handled separately. Complexity: $O(n * n * l)$ where $n$ is the length of the given sequence and $l$ is the length of the longest Fibonacci-ish subsequence.
|
[
"brute force",
"dp",
"hashing",
"implementation",
"math"
] | 2,000
| null |
633
|
E
|
Startup Funding
|
An e-commerce startup pitches to the investors to get funding. They have been functional for $n$ weeks now and also have a website!
For each week they know the number of unique visitors during this week $v_{i}$ and the revenue $c_{i}$. To evaluate the potential of the startup at some range of weeks from $l$ to $r$ inclusive investors use the minimum among the maximum number of visitors multiplied by $100$ and the minimum revenue during this period, that is:
\[
p(l,r)=\operatorname*{min}(100\cdot\operatorname*{max}_{k=l}v_{k},\operatorname*{min}_{k=l}c_{k})
\]
The truth is that investors have no idea how to efficiently evaluate the startup, so they are going to pick some $k$ random distinct weeks $l_{i}$ and give them to managers of the startup. For each $l_{i}$ they should pick some $r_{i} ≥ l_{i}$ and report maximum number of visitors and minimum revenue during this period.
Then, investors will calculate the potential of the startup for each of these ranges and take minimum value of $p(l_{i}, r_{i})$ as the total evaluation grade of the startup. Assuming that managers of the startup always report the optimal values of $r_{i}$ for some particular $l_{i}$, i.e., the value such that the resulting grade of the startup is maximized, what is the expected resulting grade of the startup?
|
Let us denote the number of visitors in the ith week by $v[i]$ and the revenue in the ith week by $r[i]$. Let us define $z[i] = max(min( 100 * max(v[i...j]), min(c[i...j]))) for all (j > = i)$. Note that $max(v[i...j])$ is an increasing function in $j$ and $min(r[i...j])$ is a decreasing function in j. Thus, for all i, $z[i]$ can be computed using RMQ sparse table in combination with binary search. Thus the question reduces to selecting $k$ values randomly from the array $z$. Let us suppose we select these $k$ values and call the minimum of these values $x$. Now, $x$ is the random variable whose expected value we need to find. If we sort $z$ in non-decreasing order: $E(X) = (z[1] * C(n - 1, k - 1) + z[2] * C(n - 2, k - 1) + z[3] * C(n - 3, k - 1)....) / (C(n, k))$ where $C(n, k)$ is the number of ways of selecting $k$ objects out of n. Since $C(n, k)$ will be big values, we should not compute $C(n, k)$ explicitly and just write them as ratios of the previous terms. Example: $C(n - 1, k - 1) / C(n, k) = k / n$ and so on. Complexity: $O(n * lgn)$
|
[
"binary search",
"constructive algorithms",
"data structures",
"probabilities",
"two pointers"
] | 2,400
| null |
633
|
F
|
The Chocolate Spree
|
Alice and Bob have a tree (undirected acyclic connected graph). There are $a_{i}$ chocolates waiting to be picked up in the $i$-th vertex of the tree. First, they choose two different vertices as their starting positions (Alice chooses first) and take all the chocolates contained in them.
Then, they alternate their moves, selecting one vertex at a time and collecting all chocolates from this node. To make things more interesting, they decided that one can select a vertex only if he/she selected a vertex adjacent to that one at his/her previous turn and this vertex has not been already chosen by any of them during other move.
If at any moment one of them is not able to select the node that satisfy all the rules, he/she will skip his turns and let the other person pick chocolates as long as he/she can. This goes on until both of them cannot pick chocolates any further.
Due to their greed for chocolates, they want to collect as many chocolates as possible. However, as they are friends they only care about the total number of chocolates they obtain \textbf{together}. What is the maximum total number of chocolates they may pick?
|
The problem boils down to computing the maximum sum of two disjoint weighted paths in a tree (weight is on the nodes not edges). It can be solved applying DP as in the given solution : Complexity: $O(n)$ where $n$ is the number of nodes in the tree.
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] | 2,600
|
"#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n#include <ctime>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <vector>\n#include <list>\n#include <deque>\n#include <queue>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\n#define pb push_back\n#define mp make_pair\n#define fs first\n#define sc second\n\nconst double pi = acos(-1.0);\nconst int size = 1000 * 1000 + 100;\n\nint n;\nlong long a[size];\nlong long insubtree[size];\nlong long longest[size];\nlong long ans = 0;\n\nvector <int> vertex[size];\n\nvoid dfs1(int v, int f) {\n vector <long long> mxs;\n longest[v] = a[v];\n insubtree[v] = a[v];\n for (int i = 0; i < (int) vertex[v].size(); i++) {\n if (vertex[v][i] != f) {\n dfs1(vertex[v][i], v);\n longest[v] = max(longest[v], longest[vertex[v][i]] + a[v]);\n insubtree[v] = max(insubtree[v], insubtree[vertex[v][i]]);\n mxs.pb(longest[vertex[v][i]]);\n }\n }\n\n sort(mxs.rbegin(), mxs.rend());\n\n if ((int) mxs.size() > 0) {\n insubtree[v] = max(insubtree[v], mxs[0] + a[v]);\n }\n if ((int) mxs.size() > 1) {\n insubtree[v] = max(insubtree[v], mxs[0] + mxs[1] + a[v]);\n }\n}\n\nvoid dfs2(int v, int f, long long best, long long lgt) {\n ans = max(ans, insubtree[v] + best);\n\n set <pair <long long, int> > bestset;\n set <pair <long long, int> > lgtset;\n bestset.insert(mp(best, -1));\n lgtset.insert(mp(lgt, -1));\n\n for (int i = 0; i < (int) vertex[v].size(); i++) {\n if (vertex[v][i] != f) {\n bestset.insert(mp(insubtree[vertex[v][i]], i));\n lgtset.insert(mp(longest[vertex[v][i]], i));\n }\n } \n\n for (int i = 0; i < (int) vertex[v].size(); i++) {\n if (vertex[v][i] != f) {\n bestset.erase(mp(insubtree[vertex[v][i]], i));\n lgtset.erase(mp(longest[vertex[v][i]], i));\n\n long long nb = bestset.rbegin()->fs;\n long long curb = a[v];\n set <pair <long long, int> >::iterator it = lgtset.end();\n if (lgtset.size() > 0) {\n --it;\n curb += it->fs;\n }\n if (lgtset.size() > 1) {\n --it;\n curb += it->fs;\n }\n\n dfs2(vertex[v][i], v, max(nb, curb), lgtset.rbegin()->fs + a[v]);\n\n bestset.insert(mp(insubtree[vertex[v][i]], i));\n lgtset.insert(mp(longest[vertex[v][i]], i));\n }\n }\n}\n\nint main() {\n scanf(\"%d\", &n);\n for (int i = 0; i < n; i++)\n scanf(\"%lld\", &a[i]);\n\n for (int i = 0; i < n - 1; i++) {\n int v, u;\n\n scanf(\"%d%d\", &u, &v);\n u--, v--;\n\n vertex[v].pb(u);\n vertex[u].pb(v);\n }\n\n dfs1(0, -1);\n ans = 0ll;\n\n dfs2(0, -1, 0ll, 0ll);\n\n printf(\"%lld\\n\", ans);\n\n return 0;\n}"
|
633
|
G
|
Yash And Trees
|
Yash loves playing with trees and gets especially excited when they have something to do with prime numbers. On his 20th birthday he was granted with a rooted tree of $n$ nodes to answer queries on. Hearing of prime numbers on trees, Yash gets too intoxicated with excitement and asks you to help out and answer queries on trees for him. Tree is rooted at node $1$. Each node $i$ has some value $a_{i}$ associated with it. Also, integer $m$ is given.
There are queries of two types:
- for given node $v$ and integer value $x$, increase all $a_{i}$ in the subtree of node $v$ by value $x$
- for given node $v$, find the number of prime numbers $p$ less than $m$, for which there exists a node $u$ in the subtree of $v$ and a non-negative integer value $k$, such that $a_{u} = p + m·k$.
|
Perform an euler tour (basically a post/pre order traversal) of the tree and store it as an array. Now, the nodes of the subtree are stored are part of the array as a subarray (contiguous subsequence). Query Type 2 requires you to essentially answer the number of nodes in the subtree such that their value modulo $m$ is a prime. Since, $m \le 1000$, we can build a segment tree(with lazy propagation) where each node has a bitset, say $b$ where $b[i]$ is on iff a value $x$ exists in the segment represented by that node, such that $i\equiv x\mod m$. The addition operations then are simply reduced to bit-rotation within the bitset of the node. Complexity: $O(n * lgn * f)$, where $n$ is the cardinality of the vertices of the tree, $f$ is a small factor denoting the time required for conducting bit rotations on a bitset of size 1000.
|
[
"bitmasks",
"data structures",
"dfs and similar",
"math",
"number theory"
] | 2,800
| null |
633
|
H
|
Fibonacci-ish II
|
Yash is finally tired of computing the length of the longest Fibonacci-ish sequence. He now plays around with more complex things such as Fibonacci-ish potentials.
Fibonacci-ish potential of an array $a_{i}$ is computed as follows:
- Remove all elements $j$ if there exists $i < j$ such that $a_{i} = a_{j}$.
- Sort the remaining elements in ascending order, i.e. $a_{1} < a_{2} < ... < a_{n}$.
- Compute the potential as $P(a) = a_{1}·F_{1} + a_{2}·F_{2} + ... + a_{n}·F_{n}$, where $F_{i}$ is the $i$-th Fibonacci number (see notes for clarification).
You are given an array $a_{i}$ of length $n$ and $q$ ranges from $l_{j}$ to $r_{j}$. For each range $j$ you have to compute the Fibonacci-ish potential of the array $b_{i}$, composed using all elements of $a_{i}$ from $l_{j}$ to $r_{j}$ inclusive. Find these potentials modulo $m$.
|
The problem can be solved by taking the queries offline and using a square-root decomposition trick popularly called as "Mo's algorithm". Apart from that, segment tree(with lazy propagation) has to be maintained for the Fibonacci-ish potential of the elements in the current [l,r] range. The fact used in the segment tree for lazy propagation is: $F(k + 1) * (a_{1} * F(i) + a_{2} * F(i + 1)...) + F(k) * (a_{1} * F(i - 1) + a_{2} * F(i) + ....) = (a_{1} * F(i + k) + a_{2} * F(i + k + 1)....)$ Example: Suppose currently the array is [100,400,500,100,300]. Using Mo's algorithm, currently the segment tree is configured for the answer of the segment [3,5]. The segment tree' node [4,5] will store answer=500*F(2)=1000. In general, the node $[l_{1}, r_{1}]$ of segment tree will contain answer for the values in the current range of $[l_{2}, r_{2}]$ of Mo's for the values that have rank in sorted array $[l_{1}, r_{1}]$. The answer will thus be of the form $a_{1} * F(i) + a_{2} * F(i + 1)...$. We maintain an invariant that apart from the answer, it will also store answer for one step back in Fibonacci, i.e., $a_{1} * F(i - 1) + a_{2} * F(i)...$. Now, when values are added (or removed) in the segment tree, the segments after the point after which the value is added have to be updated. For this we maintain a lazy count parameter (say $k$). Thus, when we remove the laziness of the node, we use the above stated formula to remove the laziness in O(1) time. Complexity: $O((n+q)*{\sqrt{n+q}}*l o g(n))$
|
[
"data structures",
"implementation"
] | 3,100
|
"#include<bits/stdc++.h>\n#define rep(i,s,n) for(i=(s);i<(n);i++)\n#define pb push_back\n#define mp make_pair\nusing namespace std;\ntypedef long long ll;\nconst int SZ = 3e4+8;\nint M;\nint fibs[SZ],vals[SZ],ar[SZ];\nint st[4*SZ][2],lazy[4*SZ];\nvoid preprocess()\n{\n\tfibs[0] = 0;\n\tfibs[1] = 1;\n\tfor(int i=2; i<SZ; i++)\n\t\tfibs[i] = (fibs[i-1] + fibs[i-2]) % M;\n\tfor(int i=2; i<SZ; i+=2)\n\t\tfibs[i] = -fibs[i];\n}\ninline int modulo(int x,int m)\n{\n\tx%=m;\n\tif(x<0)x+=m;\n\treturn x;\n}\n// initially s = 0, e = N-1, x = position where added(overall), i=0, \n// n = index of fibo to be added, toadd = true if element to be added, false to remove\n// val is the array from which ai is taken\nvoid update(int s,int e,int x,int i,int n,bool toadd)\n{\n\tif(lazy[i]!=0)\n\t{\n\t\tint a,b,c,d;\n\t\tif(lazy[i]>0)\n\t\t{\n\t\t\ta = abs(fibs[lazy[i]+1]);\n\t\t\tb = c = abs(fibs[lazy[i]]);\n\t\t\td = abs(fibs[lazy[i]-1]);\n\t\t}\n\t\telse if(lazy[i]<0)\n\t\t{\n\t\t\ta = fibs[-(lazy[i]+1)];\n\t\t\tb = c = fibs[-lazy[i]];\n\t\t\td = fibs[-(lazy[i]-1)];\n\t\t}\n\t\ta = a*st[i][0];\n\t\tb = b*st[i][1];\n\t\tc = c*st[i][0];\n\t\td = d*st[i][1];\n\t\tst[i][0] = modulo(a+b,M);\n\t\tst[i][1] = modulo(c+d,M);\n\t\tif(s!=e)\n\t\t\tlazy[2*i+1]+=lazy[i], lazy[2*i+2] += lazy[i];\n\t\tlazy[i] = 0;\t\n\t}\n\tif(x>e)\n\t\treturn;\n\tif(x<s)\n\t{\n\t\tint a = st[i][0];\n\t\tint b = st[i][1];\n\t\tif(toadd)\n\t\t{\n\t\t\tst[i][0] = modulo(a+b,M);\n\t\t\tst[i][1] = a;\n\t\t\tif(s!=e)\n\t\t\t\tlazy[2*i+1]++,lazy[2*i+2]++; \n\t\t}\n\t\telse\n\t\t{\n\t\t\tst[i][0] = b;\n\t\t\tst[i][1] = modulo(a-b,M);\n\t\t\tif(s!=e)\n\t\t\t\tlazy[2*i+1]--,lazy[2*i+2]--; \n\t\t}\n\t\treturn;\n\t}\n\tif(s==e)\n\t{\n\t\tif(toadd)\n\t\t{\n\t\t\tint xr = vals[s];\n\t\t\tst[i][0] = (xr*abs(fibs[n]))%M;\n\t\t\tst[i][1] = (xr*abs(fibs[n-1]))%M;\n\t\t}\n\t\telse\n\t\t\tst[i][0] = st[i][1] = 0;\n\t\treturn;\n\t}\n\tint mid = (s+e)/2;\n\tupdate(s,mid,x,2*i+1,n,toadd);\n\tupdate(mid+1,e,x,2*i+2,n,toadd);\n\tint a = st[2*i+1][0],b = st[2*i+1][1];\n\tint c = st[2*i+2][0],d = st[2*i+2][1];\n\tst[i][0] = (a+c)%M;\n\tst[i][1] = (b+d)%M;\n}\nint sqn;\ninline bool sub(pair<int,int> x,pair<int,int> y)\n{\t\n\tdouble v1 = x.first;\n\tv1=ceil(v1/sqn);\n\tdouble v2 = y.first;\n\tv2=ceil(v2/sqn);\n\tif(v1==v2)\n\t\treturn x.second<y.second;\n\telse\n\t\treturn v1<v2;\n}\nint bit[SZ];\nint l = SZ;\n\nvoid bit_update(int i,int val)\n{\n while(i<=l)\n {\n bit[i]=bit[i]+val;\n i=i+(i&(-i));\n }\n}\n\nint bit_summ(int a)\n{\n int s=0;\n while(a>0)\n {\n s+=bit[a];\n a=a-(a&(-a));\n }\n return s;\n}\nint ans[SZ],num[SZ];\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tint N,Q,l,r;\n\tcin>>N>>M;\n\tpreprocess();\n\tsqn = sqrt(N);\n\tfor(int i=1;i<=N;i++)\n\t{\n\t\tcin>>ar[i];\n\t\tvals[i-1] = ar[i];\n\t}\n\tsort(vals,vals+N);\n\tfor(int i=1;i<=N;i++)\n\t\tar[i] = lower_bound(vals,vals+N,ar[i]) - vals;\n\tfor(int i=0;i<N;i++)\n\t\tvals[i]%=M;\n\tcin>>Q;\n\tvector<pair<pair<int,int>,int> > queries;\n\tfor(int i=0;i<Q;i++)\n\t{\n\t\tcin>>l>>r;\n\t\tqueries.push_back(make_pair(make_pair(l,r),i));\n\t}\n\tsort(queries.begin(),queries.end(),[&](pair<pair<int,int>,int> a,pair<pair<int,int>,int> b){\n\t\treturn sub(a.first,b.first);\n\t});\n\tl=r=1;\n\tnum[ar[1]]++;\n\tbit_update(ar[1]+1,1);\n\tupdate(0,N-1,ar[1],0,1,true);\n\tfor(int i=0; i<queries.size(); i++)\n\t{\n\t\tpair<int,int> p = queries[i].first;\n\t\tint ix = queries[i].second,pos;\n\t\twhile(l<p.first)\n\t\t{\n\t\t\tnum[ar[l]]--;\n\t\t\tif(num[ar[l]]==0)\n\t\t\t{\n\t\t\t\tbit_update(ar[l]+1,-1);\n\t\t\t\tupdate(0,N-1,ar[l],0,0,false);\n\t\t\t}\n\t\t\tl++;\n\t\t}\n\t\twhile(l>p.first)\n\t\t{\n\t\t\tl--;\n\t\t\tnum[ar[l]]++;\n\t\t\tif(num[ar[l]]==1)\n\t\t\t{\n\t\t\t\tpos = bit_summ(ar[l]) + 1;\n\t\t\t\tbit_update(ar[l]+1,1);\n\t\t\t\tupdate(0,N-1,ar[l],0,pos,true);\n\t\t\t}\n\t\t}\n\t\twhile(r<p.second)\n\t\t{\n\t\t\tr++;\n\t\t\tnum[ar[r]]++;\n\t\t\tif(num[ar[r]]==1)\n\t\t\t{\n\t\t\t\tpos = bit_summ(ar[r]) + 1;\n\t\t\t\tbit_update(ar[r]+1,1);\n\t\t\t\tupdate(0,N-1,ar[r],0,pos,true);\n\t\t\t}\n\t\t}\t\t\n\t\twhile(r>p.second)\n\t\t{\n\t\t\tnum[ar[r]]--;\n\t\t\tif(num[ar[r]]==0)\n\t\t\t{\n\t\t\t\tbit_update(ar[r]+1,-1);\t\t\n\t\t\t\tupdate(0,N-1,ar[r],0,0,false);\n\t\t\t}\n\t\t\tr--;\n\t\t}\n\t\tans[ix] = st[0][0];\n\t}\t\n\tfor(int i=0; i<Q; i++)\n\t\tcout<<ans[i]<<\"\\n\";\n}"
|
634
|
A
|
Island Puzzle
|
A remote island chain contains $n$ islands, labeled $1$ through $n$. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands $1$ and $2$, islands $2$ and $3$, and so on, and additionally a bridge connects islands $n$ and $1$. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.
The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.
Determine if it is possible for the islanders to arrange the statues in the desired order.
|
Notice that, as we move the empty pedestal around the circle, we cyclically permute the statues (and the empty pedestal can be anywhere). Thus, we can reach one state from another if and only if, after removing the empty pedestal, they are cyclic shifts of each other. The starting and ending configurations are permutations, so we can check this in linear time. Runtime: $O(n)$
|
[
"constructive algorithms",
"implementation"
] | 1,300
| null |
635
|
A
|
Orchestra
|
Paul is at the orchestra. The string section is arranged in an $r × c$ rectangular grid and is filled with violinists with the exception of $n$ violists. Paul really likes violas, so he would like to take a picture including at least $k$ of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.
Two pictures are considered to be different if the coordinates of corresponding rectangles are different.
|
We can iterate over each possible rectangle and count the number of violists enclosed. This can be optimized with rectangular prefix sums, though the simple brute force is sufficient for this problem. Runtime: $O(n^{6})$
|
[
"brute force",
"implementation"
] | 1,100
| null |
639
|
A
|
Bear and Displayed Friends
|
Limak is a little polar bear. He loves connecting with other bears via social networks. He has $n$ friends and his relation with the $i$-th of them is described by a unique integer $t_{i}$. The bigger this value is, the better the friendship is. No two friends have the same value $t_{i}$.
Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.
The system displays friends who are online. On the screen there is space to display at most $k$ friends. If there are more than $k$ friends online then the system displays only $k$ best of them — those with biggest $t_{i}$.
Your task is to handle queries of two types:
- "1 id" — Friend $id$ becomes online. It's guaranteed that he wasn't online before.
- "2 id" — Check whether friend $id$ is displayed by the system. Print "YES" or "NO" in a separate line.
Are you able to help Limak and answer all queries of the second type?
|
You should remember all friends displayed currently (in set or list) and when you add someone new you must check whether there are at most $k$ people displayed. If there are $k + 1$ then you can iterate over them (over $k + 1$ people in your set/list) and find the worst one. Then - remove him. The intended complexity is O(n + q*k).
|
[
"implementation"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
const int nax = 1e6 + 5;
int t[nax];
struct cmp {
bool operator()(int a, int b) {
return t[a] < t[b];
}
};
int main() {
int n, k, q;
scanf("%d%d%d", &n, &k, &q);
for(int i = 1; i <= n; ++i) scanf("%d", &t[i]);
set<int, cmp> displayed;
while(q--) {
int type, a;
scanf("%d%d", &type, &a);
if(type == 1) {
displayed.insert(a);
if((int) displayed.size() > k)
displayed.erase(displayed.begin());
}
else {
if(displayed.find(a) == displayed.end())
puts("NO");
else
puts("YES");
}
}
return 0;
}
|
639
|
B
|
Bear and Forgotten Tree 3
|
A tree is a connected undirected graph consisting of $n$ vertices and $n - 1$ edges. Vertices are numbered $1$ through $n$.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values $n$, $d$ and $h$:
- The tree had exactly $n$ vertices.
- The tree had diameter $d$. In other words, $d$ was the biggest distance between two vertices.
- Limak also remembers that he once rooted the tree in vertex $1$ and after that its height was $h$. In other words, $h$ was the biggest distance between vertex $1$ and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
|
You may want to write some special if for $n = 2$. Let's assume $n \ge 3$. If $d = 1$ or $d > 2h$ then there is no answer (it isn't hard to see and prove). Otherwise, let's construct a tree as follows. We need a path of length $h$ starting from vertex $1$ and we can just build it. If $d > h$ then we should also add an other path from vertex $1$, this one with length $d - h$. Now we have the required height and diameter but we still maybe have too few vertices used. But what we built is one path of length $d$ where $d \ge 2$. You can choose any vertex on this path other than ends of the path (let's call him $v$), and add new vertices by connecting them all directly with $v$. You can draw it to see that you won't increase height or diameter this way. In my code I sometimes had $v = 1$ but sometimes (when $d = h$) I needed some other vertex and $v = 2$ was fine.
|
[
"constructive algorithms",
"graphs",
"trees"
] | 1,600
|
#include<bits/stdc++.h> using namespace std; int main() { int n, d, h; scanf("%d%d%d", &n, &d, &h); if(d > 2 * h || (d == 1 && n != 2)) { puts("-1"); return 0; } for(int i = 1; i <= h; ++i) printf("%d %d ", i, i + 1); int x = 1; for(int i = 1; i <= d - h; ++i) { int y = h + 1 + i; printf("%d %d ", x, y); x = y; } for(int i = d + 2; i <= n; ++i) printf("%d %d ", i, (d == h) ? 2 : 1); return 0; }
|
639
|
C
|
Bear and Polynomials
|
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.
He considers a polynomial valid if its degree is $n$ and its coefficients are integers not exceeding $k$ by the absolute value. More formally:
Let $a_{0}, a_{1}, ..., a_{n}$ denote the coefficients, so $P(x)=\sum_{i=0}^{n}a_{i}\cdot x^{i}$. Then, a polynomial $P(x)$ is valid if all the following conditions are satisfied:
- $a_{i}$ is integer for every $i$;
- $|a_{i}| ≤ k$ for every $i$;
- $a_{n} ≠ 0$.
Limak has recently got a valid polynomial $P$ with coefficients $a_{0}, a_{1}, a_{2}, ..., a_{n}$. He noticed that $P(2) ≠ 0$ and he wants to change it. He is going to change one coefficient to get a \textbf{valid} polynomial $Q$ of degree $n$ that $Q(2) = 0$. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.
|
Let's count only ways to decrease one coefficient to get the required conditions (you can later multiply coefficient by $- 1$ and run your program again to also calculate ways to increase a coefficient). One way of thinking is to treat the given polynomial as a number. You can find the binary representation - a sequence with $0$'s and $1$'s of length at most $n+\log(10^{9})$. Changing one coefficient affects up to $\log(10^{9})$ consecutive bits there and we want to get a sequence with only $0$'s. We may succeed only if all $1$'s are close to each other and otherwise we can print $0$ to the output. Let's think what happens when $1$'s are close to each other. Let's say that we got a sequence with two $1$'s as follows: $...00101000...$. Decreasing by $5$ one coefficient (the one that was once in a place of the current first bit $1$) will create a sequence of $0$'s only. It's not complicated to show that decreasing coefficients on the right won't do a job (because the first $1$ will remain there) but you should also count some ways to change coefficients on the left. We can decrease by $10$ a coefficient on the left from first $1$, or decrease by $20$ a coefficient even more on the left, and so on. Each time you should check whether changing the original coefficient won't exceed the given maximum allowed value $k$. One other solution is to go from left to right and keep some integer value - what number should be added to the current coefficient to get sum equal to $0$ on the processed prefix. Then, we should do the same from right to left. In both cases maybe in some moment we should break because it's impossible to go any further. In one case it happens when we should (equally) divide an odd number by $2$, and in the other case it happens when our number becomes too big (more than $2 \cdot 10^{9}$) because we won't be able to make it small again anyway.
|
[
"hashing",
"implementation",
"math"
] | 2,200
|
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int nax = 1e6 + 5; int t[nax]; ll pref[nax], suf[nax]; const ll WRONG = 1e16 + 5; int main() { int n, k; scanf("%d%d", &n, &k); for(int i = 0; i <= n; ++i) scanf("%d", &t[i]); for(int i = 0; i < n; ++i) { pref[i+1] = pref[i] + t[i]; if(pref[i+1] % 2) { for(int j = i + 1; j <= n; ++j) pref[j] = WRONG; break; } else pref[i+1] /= 2; } for(int i = n; i > 0; --i) { suf[i-1] = suf[i] + t[i]; suf[i-1] *= 2; if(abs(suf[i-1]) >= WRONG) { for(int j = i - 1; j >= 0; --j) suf[j] = WRONG; break; } } int ans = 0; for(int i = 0; i <= n; ++i) if(suf[i] != WRONG && pref[i] != WRONG) { long long maybe = -(pref[i] + suf[i]); if(maybe == 0 && i == n) continue; if(abs(maybe) <= k) ++ans; } printf("%d ", ans); return 0; }
|
639
|
D
|
Bear and Contribution
|
Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are $n$ registered users and the $i$-th of them has contribution $t_{i}$.
Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments.
- Limak can spend $b$ minutes to read one blog and upvote it. Author's contribution will be increased by $5$.
- Limak can spend $c$ minutes to read one comment and upvote it. Author's contribution will be increased by $1$.
Note that it's possible that Limak reads blogs faster than comments.
Limak likes ties. He thinks it would be awesome to see a tie between at least $k$ registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value $x$ that at least $k$ registered users have contribution exactly $x$.
How much time does Limak need to achieve his goal?
|
It isn't enough to sort the input array and use two pointers because it's not correct to assume that the optimal set of people will be an interval. Instead, let's run some solution five times, once for each remainder after dividing by $5$ (remainders $0, 1, 2, 3, 4$). For each remainder $r$ we assume that we should move $k$ people to some value $x$ that $x\ \operatorname{mod}5=r$ (and at the end we want at least $k$ people to have contribution $x$). Note that $x$ must be close to some number from the input because otherwise we should decrease $x$ by $5$ and for sure we would get better solution. The solution is to iterate over possible values of $x$ from lowest to highest (remember that we fixed remainder $r=x\ \mathrm{~mod~5}$). At the same time, we should keep people in $5$ vectors/lists and do something similar to the two pointers technique. We should keep two pointers on each of $5$ lists and always move the best among $5$ options. The complexity should be $O(n \cdot 5)$.
|
[
"data structures",
"greedy",
"sortings",
"two pointers"
] | 2,400
|
#include <bits/stdc++.h> using namespace std; int n, k; long long c1, c2; long long con[1000007]; long long res; long long aktual; vector <long long> pos[5]; queue <long long> val[5]; int w; long long p; inline long long calc(long long a, long long b) { return ((b-a)%5)*c2+((b-a)/5)*c1; } int main() { res=1000000000; res*=res; scanf("%d%d", &n, &k); scanf("%lld%lld", &c1, &c2); c1=min(c1, 5*c2); for (int i=1; i<=n; i++) { scanf("%lld", &con[i]); con[i]+=1000000001; } sort(con+1, con+n+1); for (int i=k; i<=n; i++) { for (int j=0; j<5; j++) { pos[(con[i]+j)%5].push_back(con[i]+j); } } for (int h=0; h<5; h++) { sort(pos[h].begin(), pos[h].end()); for (int i=0; i<5; i++) { while(!val[i].empty()) val[i].pop(); } w=0; aktual=0; for (int i=0; i<pos[h].size(); i++) { if (i) aktual+=c1*min(w, k)*(pos[h][i]-pos[h][i-1])/5; while(w<n && con[w+1]<=pos[h][i]) { w++; val[con[w]%5].push(con[w]); aktual+=calc(con[w], pos[h][i]); if (w>k) { p=0; for (int j=0; j<5; j++) { if (!val[j].empty()) { p=max(p, calc(val[j].front(), pos[h][i])); } } for (int j=0; j<5; j++) { if (!val[j].empty() && calc(val[j].front(), pos[h][i])==p) { aktual-=p; val[j].pop(); break; } } } } if (w>=k) { res=min(res, aktual); } } } printf("%lld ", res); return 0; }
|
639
|
E
|
Bear and Paradox
|
Limak is a big polar bear. He prepared $n$ problems for an algorithmic contest. The $i$-th problem has \textbf{initial} score $p_{i}$. Also, testers said that it takes $t_{i}$ minutes to solve the $i$-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it — Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by $c$ in this statement.
Let $T$ denote the total number of minutes needed to solve all problems (so, $T = t_{1} + t_{2} + ... + t_{n}$). The contest will last exactly $T$ minutes. So it's just enough to solve all problems.
Points given for solving a problem decrease linearly. Solving the $i$-th problem after $x$ minutes gives exactly $p_{i}\cdot(1-c\cdot{\frac{x}{T}})$ points, where $c\in[0,1]$ is some real constant that Limak must choose.
Let's assume that $c$ is fixed. During a contest a participant chooses some order in which he or she solves problems. There are $n!$ possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order.
Limak assumes that every participant will properly estimate $t_{i}$ at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem.
For two distinct problems $i$ and $j$ such that $p_{i} < p_{j}$ Limak wouldn't be happy to see a participant with strictly more points for problem $i$ than for problem $j$. He calls such a situation a paradox.
It's not hard to prove that there will be no paradox for $c = 0$. The situation may be worse for bigger $c$. What is the maximum real value $c$ (remember that $c\in[0,1]$) for which there is no paradox possible, that is, there will be no paradox for \textbf{any optimal order} of solving problems?
It can be proved that the answer (the maximum $c$ as described) always exists.
|
It's good to know what to do with problems about optimal order. Often you can use the following trick - take some order and look at two neighbouring elements. When is it good to swap? (When does swapping them increase the score?) You should write some simple formula (high school algebra) and get some inequality. In this problem it turns out that one should sort problems by a fraction $\scriptstyle{\vec{r}}_{i}$ and it doesn't depend on a constant $c$. There may be many problems with the same value of $\scriptstyle{\vec{r}}_{i}$ and we can order them however we want (and the question will be: if there is a paradox for at least one order). Let's call such a set of tied problems a block. For each problem you can calculate its minimum and maximum possible number of granted points - one case is at the end of his block and the other case is to solve this problem as early as possible so at the beginning of his block. So, for fixed $c$ for each problem we can find in linear time the best and worst possible scores (given points). When do we get a paradox? Where we have two problems $i$ and $j$ that $p_{i} < p_{j}$ ($p_{i}$ was worth less points) we solved problem $i$ much earlier and later we got less points for problem $p_{j}$. We can now use some segment tree or sort problems by $p_{i}$ and check whether there is a pair of problems with inequalities we are looking for - $p_{i} < p_{j}$ and $max_{i} > min_{j}$ where $max_{i}$ and $min_{j}$ we found in the previous paragraph. We can do the binary search over the answer to get complexity $O(n\cdot\log n\cdot\log(10^{9}))$ or faster. Can you solve the problem in linear time?
|
[
"binary search",
"greedy",
"math",
"sortings"
] | 2,800
|
#include<bits/stdc++.h> using namespace std; typedef pair<int,int> pii; typedef long double ld; #define points first #define time second bool paradox(vector<vector<pii>> & w, ld c) { ld time_total = 0; for(auto group : w) for(pii p : group) time_total += p.time; ld time_so_far = 0; vector<pair<int,pair<ld,ld>>> all; for(vector<pii> & group : w) { ld time_this_group = 0; for(pii & p : group) time_this_group += p.time; for(pii & p : group) { ld small = p.points * (1 - c * (time_so_far + time_this_group) / time_total); ld big = p.points * (1 - c * (time_so_far + p.time) / time_total); all.push_back(make_pair(p.points, make_pair(small, big))); } time_so_far += time_this_group; } sort(all.begin(), all.end()); ld max_so_far = -1; for(int i = 0; i < (int) all.size(); ++i) { int j = i; while(j + 1 < (int) all.size() && all[j+1].first == all[i].first) ++j; for(int k = i; k <= j; ++k) if(all[k].second.first < max_so_far) return true; // paradox for(int k = i; k <= j; ++k) max_so_far = max(max_so_far, all[k].second.second); i = j; } return false; } int cmp(const pii & a, const pii & b) { // -1, 0 or 1 long long tmp = (long long) a.first * b.second - (long long) a.second * b.first; if(tmp > 0) return -1; if(tmp == 0) return 0; return 1; } bool sort_cmp(const pii & a, const pii & b) { int memo = cmp(a, b); return memo == -1 || (memo == 0 && a.points < b.points); } const int nax = 1e6 + 5; pii in[nax]; int main() { int n; scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", &in[i].points); for(int i = 0; i < n; ++i) scanf("%d", &in[i].time); sort(in, in + n, sort_cmp); vector<vector<pii>> w; for(int i = 0; i < n; ++i) { if(i == 0 || cmp(in[i-1], in[i]) != 0) w.push_back(vector<pii>{}); w.back().push_back(in[i]); } ld low = 0, high = 1; for(int rep = 0; rep < 40; ++rep) { ld mid = (low + high) / 2; if(paradox(w, mid)) high = mid; else low = mid; } printf("%.10lf ", (double) (low + high) / 2); return 0; }
|
639
|
F
|
Bear and Chemistry
|
Limak is a smart brown bear who loves chemistry, reactions and transforming elements.
In Bearland (Limak's home) there are $n$ elements, numbered $1$ through $n$. There are also special machines, that can transform elements. Each machine is described by two integers $a_{i}, b_{i}$ representing two elements, not necessarily distinct. One can use a machine either to transform an element $a_{i}$ to $b_{i}$ or to transform $b_{i}$ to $a_{i}$. Machines in Bearland aren't very resistant and each of them can be used \textbf{at most once}. It is possible that $a_{i} = b_{i}$ and that many machines have the same pair $a_{i}, b_{i}$.
Radewoosh is Limak's biggest enemy and rival. He wants to test Limak in the chemistry. They will meet tomorrow and both of them will bring all their machines. Limak has $m$ machines but he doesn't know much about his enemy. They agreed Radewoosh will choose two distinct elements, let's denote them as $x$ and $y$. Limak will be allowed to use both his and Radewoosh's machines. He may use zero or more (maybe even all) machines to achieve the goal, each machine at most once. Limak will start from an element $x$ and his task will be to first get an element $y$ and then to again get an element $x$ — \textbf{then we say that he succeeds}. After that Radewoosh would agree that Limak knows the chemistry (and Radewoosh would go away).
Radewoosh likes some particular non-empty set of favorite elements and he will choose $x, y$ from that set. Limak doesn't know exactly which elements are in the set and also he doesn't know what machines Radewoosh has. Limak has heard $q$ gossips (queries) though and each of them consists of Radewoosh's machines and favorite elements. For each gossip Limak wonders if he would be able to \textbf{succeed} tomorrow for every pair $x, y$ chosen from the set of favorite elements. If yes then print "YES" (without the quotes). But if there exists a pair $(x, y)$ from the given set that Limak wouldn't be able to succeed then you should print "NO" (without the quotes).
|
Task is about checking if after adding some edges to graph, some given subset of vertices will be in one biconnected component. Firstly, let's calculate biconnected components in the initial graph. For every vertex in each query we will replace it with index of its bicon-component (for vertices from subset and for edges endpoints). Now we have a forest. When we have a list of interesting vertices in a new graph (bicon-components of vertices from subset or edges) we can compress an entire forest, so it will containg at most 2 times more vertices than the list (from query) and will have simillar structure to forest. To do it, we sort vertices by left-right travelsal order and take LCA of every adjacent pair on the sorted list. If you have compressed forest, then you just have to add edges and calculate biconnected components normally, in linear time.
|
[
"data structures",
"dfs and similar",
"graphs",
"trees"
] | 3,300
|
#include <bits/stdc++.h> using namespace std; int n, m, q; int p1, p2, p3, p4; vector < pair <int,int> > graph[1000007]; int l; int pre[1000007]; int low[1000007]; vector <int> vec; int bic[1000007]; int b; vector <int> bgraph[1000007]; int bpre[1000007]; int bpost[1000007]; int c; int conn[1000007]; int dis[1000007]; vector <int> jump[1000007]; vector <int> subset; vector < pair <int,int> > edges; int trans[1000007]; vector <int> sta; vector < pair <int,int> > ngraph[1000007]; int bic2[1000007]; int res; void dfs1(int v, int p) { l++; pre[v]=l; low[v]=l; sta.push_back(v); for (int i=0; i<graph[v].size(); i++) { if (graph[v][i].second==p) continue; if (pre[graph[v][i].first]) { low[v]=min(low[v], pre[graph[v][i].first]); } else { dfs1(graph[v][i].first, graph[v][i].second); low[v]=min(low[v], low[graph[v][i].first]); } } if (pre[v]==low[v]) { b++; while(sta.back()!=v) { bic[sta.back()]=b; sta.pop_back(); } bic[sta.back()]=b; sta.pop_back(); } } void dfs2(int v, int p) { l++; bpre[v]=l; conn[v]=c; jump[v].push_back(p); while(jump[v].back()) { p1=jump[v].size()-1; p2=jump[v].back(); jump[v].push_back(jump[p2][min(p1, (int)jump[p2].size()-1)]); } for (int i=0; i<bgraph[v].size(); i++) { if (bgraph[v][i]!=p) { dis[bgraph[v][i]]=dis[v]+1; dfs2(bgraph[v][i], v); } } l++; bpost[v]=l; } int lca(int v, int u) { if (conn[v]!=conn[u]) return 0; for (int i=jump[v].size()-1; i>=0; i--) { if (i<jump[v].size() && dis[jump[v][i]]>=dis[u]) { v=jump[v][i]; } } for (int i=jump[u].size()-1; i>=0; i--) { if (i<jump[u].size() && dis[jump[u][i]]>=dis[v]) { u=jump[u][i]; } } for (int i=jump[v].size()-1; i>=0; i--) { if (i<jump[v].size() && i<jump[u].size() && jump[v][i]!=jump[u][i]) { v=jump[v][i]; u=jump[u][i]; } } if (v!=u) v=jump[v][0]; return v; } bool comp(int v, int u) { return bpre[v]<bpre[u]; } void filtr() { vector <int> vec2=vec; vec.clear(); sort(vec2.begin(), vec2.end(), comp); for (int i=0; i<vec2.size(); i++) { if (!vec2[i]) continue; if (!i || vec2[i]!=vec2[i-1]) { vec.push_back(vec2[i]); } } } void dfs3(int v, int p) { l++; pre[v]=l; low[v]=l; sta.push_back(v); for (int i=0; i<ngraph[v].size(); i++) { if (ngraph[v][i].second==p) continue; if (pre[ngraph[v][i].first]) { low[v]=min(low[v], pre[ngraph[v][i].first]); } else { dfs3(ngraph[v][i].first, ngraph[v][i].second); low[v]=min(low[v], low[ngraph[v][i].first]); } } if (pre[v]==low[v]) { b++; while(sta.back()!=v) { bic2[sta.back()]=b; sta.pop_back(); } bic2[sta.back()]=b; sta.pop_back(); } } long long R; int rotate(int element) { element=(element+R)%n; if (element==0) element=n; return element; } int main() { scanf("%d%d%d", &n, &m, &q); for (int i=1; i<=m; i++) { scanf("%d%d", &p1, &p2); graph[p1].push_back(make_pair(p2, i)); graph[p2].push_back(make_pair(p1, i)); } for (int i=1; i<=n; i++) { if (!pre[i]) { dfs1(i, 0); } } for (int i=1; i<=n; i++) { for (int j=0; j<graph[i].size(); j++) { if (bic[i]!=bic[graph[i][j].first]) { bgraph[bic[i]].push_back(bic[graph[i][j].first]); } } } l=0; for (int i=1; i<=b; i++) { if (!bpre[i]) { c++; dfs2(i, 0); } } for (int h=1; h<=q; h++) { subset.clear(); edges.clear(); vec.clear(); scanf("%d%d", &p1, &p2); while(p1--) { scanf("%d", &p3); p3=rotate(p3); subset.push_back(bic[p3]); vec.push_back(bic[p3]); } while(p2--) { scanf("%d%d", &p3, &p4); p3=rotate(p3); p4=rotate(p4); edges.push_back(make_pair(bic[p3], bic[p4])); vec.push_back(bic[p3]); vec.push_back(bic[p4]); } sort(vec.begin(), vec.end(), comp); for (int i=vec.size()-1; i; i--) { vec.push_back(lca(vec[i], vec[i-1])); } filtr(); c=vec.size(); for (int i=0; i<c; i++) { trans[vec[i]]=i+1; ngraph[i+1].clear(); pre[i+1]=0; low[i+1]=0; } l=0; sta.clear(); for (int i=0; i<c; i++) { while(!sta.empty() && bpost[vec[i]]>bpost[sta.back()]) { sta.pop_back(); } if (!sta.empty()) { l++; ngraph[trans[vec[i]]].push_back(make_pair(trans[sta.back()], l)); ngraph[trans[sta.back()]].push_back(make_pair(trans[vec[i]], l)); } sta.push_back(vec[i]); } sta.clear(); for (int i=0; i<edges.size(); i++) { l++; ngraph[trans[edges[i].first]].push_back(make_pair(trans[edges[i].second], l)); ngraph[trans[edges[i].second]].push_back(make_pair(trans[edges[i].first], l)); } b=0; l=0; for (int i=1; i<=c; i++) { if (!pre[i]) { dfs3(i, 0); } } res=1; for (int i=1; i<subset.size(); i++) { if (bic2[trans[subset[i]]]!=bic2[trans[subset[0]]]) { res=0; } } if (res) { printf("YES "); R+=h; } else { printf("NO "); } } return 0; }
|
641
|
A
|
Little Artem and Grasshopper
|
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells $1 × n$. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
|
We can just emulate grasshopper behavior and save all positions it visits. It is obvious that we will have no more than O(n) different positions. If grasshopper appears in the same position twice that means that there is a loop and the answer is INFINITE. Otherwise the answer is FINITE.
|
[
"implementation"
] | 1,000
| null |
641
|
B
|
Little Artem and Matrix
|
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size $n × m$. There are $n + m$ inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from $1$ to $n$ from top to bottom, while columns are numbered with integers from $1$ to $m$ from left to right.
Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of $q$ turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.
Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
|
Let's have 2 matrices: a, idx. In a we will have NULL for cell if we don't know the value or the value. idx will be initialized with idx[i][j] = {i, j}; Then we need to emulate the process on matrix idx. If we have 3rd query we can set up the value in matrix a, because we know the original position of that cell keeping idx.
|
[
"implementation"
] | 1,400
| null |
641
|
C
|
Little Artem and Dance
|
Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are $n$ pairs of boys and girls standing in a circle. Initially, boy number $1$ dances with a girl number $1$, boy number $2$ dances with a girl number $2$ and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves:
- Value $x$ and some direction are announced, and all boys move $x$ positions in the corresponding direction.
- Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl $1$ swaps with the one who was dancing with the girl number $2$, while the one who was dancing with girl number $3$ swaps with the one who was dancing with the girl number $4$ and so one. It's guaranteed that $n$ is even.
Your task is to determine the final position of each boy.
|
The key in this problem is that order of all elements in odd positions and in even positions is the same. Let's say we have 2 arrays: [1, 3, 5, ...] and [2, 4, ...] (odd positions and even positions). Now if we call 2nd commands we just swap these 2 arrays, but order is the same. Obviously 1st command also keeps the order. By order I mean cyclic order (right neighbor is the same in cycle position). Let's just keep the position of 1st boy and 2nd boy. Now if we apply 1st operation we move it by X or -X. Second type of the query just swaps the positions. In the end we can construct the answer if we know positions of 1st and 2nd boys.
|
[
"brute force",
"constructive algorithms",
"implementation"
] | 1,800
| null |
641
|
D
|
Little Artem and Random Variable
|
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from $1$ to $n$ inclusive. For each dice the probability of each outcome is given (of course, their sum is $1$), and different dices may have different probability distributions.
We throw both dices simultaneously and then calculate values $max(a, b)$ and $min(a, b)$, where $a$ is equal to the outcome of the first dice, while $b$ is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for $max(a, b)$ and $min(a, b)$. That is, for each $x$ from $1$ to $n$ you know the probability that $max(a, b)$ would be equal to $x$ and the probability that $min(a, b)$ would be equal to $x$. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.
|
First, let's solve inverse problem: find minimum (maximum) of two distributions. Let's use the following formulas: P(a = k) = P(a <= k) - P(a <= k-1) P(max(a, b) <= k) = P(a <= k) * P(b <= k) For minimum: P(min(a, b) >= k) = P(a >= k) * P(b >= k) = (1 - P(a <= k-1)) *(1 - P(b <= k-1)) Now in our original problem minimum and maximum defines system of square equations for each pair P(a <= k), P(b <= k). Solving these equations we get P(a<=k), P(b<=k) = (u + v \pm sqrt((u + v)^2 - 4u)) / 2, where u = P(max(a,b) <= k), v = P(min(a,b) <= k). Now we can notice that if there exists an answer, then there exists an answer when we chose the signs for each pair equally (check out this comment)
|
[
"dp",
"implementation",
"math",
"probabilities"
] | 2,400
| null |
641
|
E
|
Little Artem and Time Machine
|
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: \underline{multiset}.
Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types:
- Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer.
- Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset.
- Count the number of instances of the given integer that are stored in the multiset.
But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example.
- First Artem adds integer $5$ to the multiset at the $1$-st moment of time.
- Then Artem adds integer $3$ to the multiset at the moment $5$.
- Then Artem asks how many $5$ are there in the multiset at moment $6$. The answer is $1$.
- Then Artem returns back in time and asks how many integers $3$ are there in the set at moment $4$. Since $3$ was added only at moment $5$, the number of integers $3$ at moment $4$ equals to $0$.
- Then Artem goes back in time again and removes $5$ from the multiset at moment $3$.
- Finally Artyom asks at moment $7$ how many integers $5$ are there in the set. The result is $0$, since we have removed $5$ at the moment $3$.
Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.
Help Artem implement time travellers multiset.
|
There are many ways to solve this problem. One of the ways was SQRT-decomposition. First let's compress all times. Now for each block in the decomposition we will store for each element the balance in that block. So to answer the query we need to calculate sum of balances from first block to the block before the one where our element is located and then just process all requests in the current block. Another way was to use data structure from std library, described here. For each element we have two trees: remove times and add times. Then by getting order of the time in remove and add tree we can calculate the answer.
|
[
"data structures"
] | 2,000
| null |
641
|
F
|
Little Artem and 2-SAT
|
Little Artem is a very smart programmer. He knows many different difficult algorithms. Recently he has mastered in \underline{2-SAT} one.
In computer science, 2-satisfiability (abbreviated as \underline{2-SAT}) is the special case of the problem of determining whether a conjunction (logical \underline{AND}) of disjunctions (logical \underline{OR}) have a solution, in which all disjunctions consist of no more than two arguments (variables). For the purpose of this problem we consider only \underline{2-SAT} formulas where each disjunction consists of exactly two arguments.
Consider the following \underline{2-SAT} problem as an example: $(1x_{1}\ \mathrm{Ole}\ x_{2})\ \mathrm{AND}\ (x_{3}\ \mathrm{Olg}\ 1x_{4})\ \mathrm{AND}\ \ldots\ \mathrm{AND}\ (x_{2n-1}\ \mathrm{Olg}\ x_{2n})$. Note that there might be negations in \underline{2-SAT} formula (like for $x_{1}$ and for $x_{4}$).
Artem now tries to solve as many problems with \underline{2-SAT} as possible. He found a very interesting one, which he can not solve yet. Of course, he asks you to help him.
The problem is: given two \underline{2-SAT} formulas $f$ and $g$, determine whether their sets of possible solutions are the same. Otherwise, find any variables assignment $x$ such that $f(x) ≠ g(x)$.
|
Let's build for both 2-SAT formulas implication graph and let's find strong connected components in this graph. If both of the formulas are not satisfiable then the answer is SIMILAR. If only one formula is not satisfiable then we can find an answer for the second one and output it. Now, let's assume both formulas are satisfiable. Let's have a transitive closure for both of the graphs. Let's call the variable X fixed in the formula F if there is a path -> x or (x -> ). If there is a fixed variable in one formula, but not fixed in the other (or fixed but has other value) we can find the solution for that second formula with opposite value of that fixed variable - that will be an answer. If we could not find these variables, we can remove all of them. There is no fixed variables in the rest of them. Let's find an edge u->v, presented in one graph, but not presented in the other. Let's find the solution for formula without the edge with u = 1 and v = 0 (we always can find it). That is the answer.
|
[] | 3,000
| null |
641
|
G
|
Little Artem and Graph
|
Little Artem is given a graph, constructed as follows: start with some $k$-clique, then add new vertices one by one, connecting them to $k$ already existing vertices that form a $k$-clique.
Artem wants to count the number of spanning trees in this graph modulo $10^{9} + 7$.
|
Let's define k-clique B the descendant of k-clique A, if B could be produced from A with the sequence of the following steps: add vertex to the clique, connected with all clique vertices in the graph description and remove exactly one other vertex. Let's calculate the DP with states (k-clique, separation its vertices to the components) - number of spanning forests int the graph, induced by the clique and all its descendants so that clique will be divided to different connected components according to the defined vertices separation (all of the rest vertices will be connected with some of these components). To calculate that we need to precalculate all separations from k to k+1 elements and transitions: 1) (separation of k+1 vertices) x (separation k+1 vertices) -> (separation k+1 vertices | null), transform pair of separations - forests to the set of connected components of their union or null if there appears a cycle. 2) (separation of k+1 vertices) x (vertex) -> (separation of k+1 vertices | null), transform forest to the new forest, generated by adding new edge from vertex to vertex k+1 (or null, if there appears a cycle) 3) (separation of k+1 vertices) -> (separation of k vertices | null), projecting the separation on the first k vertices (or null, if k+1-th vertex creates a separate component)
|
[] | 2,300
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class k_tree {
final static long MOD = 1000000007;
private static long modPow(long x, long pow, long mod) {
long r = 1;
while (pow > 0) {
if (pow % 2 == 1) {
r = r * x % mod;
}
pow /= 2;
x = x * x % mod;
}
return r;
}
static class Graph {
int k;
int[][] es;
}
static class Partition {
int[] p;
long spanningTreesCache = 0;
public Partition(int[] p) {
this.p = p;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return Arrays.equals(p, ((Partition) o).p);
}
@Override
public int hashCode() {
return Arrays.hashCode(p);
}
public long spanningTrees() {
if (spanningTreesCache == 0) {
int[] cnts = new int[p.length];
for (int i : p) {
cnts[i]++;
}
spanningTreesCache = 1;
for (int i = 0; i < cnts.length; ++i) {
if (cnts[i] > 1) {
spanningTreesCache = spanningTreesCache * modPow(cnts[i], cnts[i] - 2, MOD) % MOD;
}
}
}
return spanningTreesCache;
}
}
static class Partitions {
ArrayList<Partition> list = new ArrayList<>();
HashMap<Partition, Integer> index = new HashMap<>();
public Partitions(int k) {
genPartitions(0, 0, new int[k]);
}
private void genPartitions(int i, int m, int[] p) {
if (i == p.length) {
Partition par = new Partition(p.clone());
list.add(par);
index.put(par, index.size());
return;
}
for (p[i] = 0; p[i] <= m; ++p[i]) {
genPartitions(i + 1, Math.max(m, p[i] + 1), p);
}
}
}
static class Facet {
int[] vs;
long[] cs;
public Facet(int[] vs, Partitions pk) {
this.vs = vs;
cs = new long[pk.list.size()];
cs[cs.length - 1] = 1;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Facet facet = (Facet) o;
return Arrays.equals(vs, facet.vs);
}
@Override
public int hashCode() {
return Arrays.hashCode(vs);
}
}
static class DSU {
int[] p, r;
int comps;
DSU(int n) {
p = new int[n];
r = new int[n];
comps = n;
for (int i = 0; i < n; ++i) {
p[i] = i;
}
}
int get(int i) {
if (p[i] != i) {
p[i] = get(p[i]);
}
return p[i];
}
void unite(int i, int j) {
i = get(i);
j = get(j);
if (i != j) {
if (r[i] < r[j]) {
p[i] = j;
} else {
p[j] = i;
}
if (r[i] == r[j]) {
r[i]++;
}
comps--;
}
}
}
static long solveFast(Graph g) {
Partitions pk = new Partitions(g.k), pk1 = new Partitions(g.k + 1);
int[][][] transitions = new int[pk1.list.size()][pk.list.size()][g.k + 1];
int[][] eTransitions = new int[pk1.list.size()][g.k];
int[] reductions = new int[pk1.list.size()];
for (int u = 0; u < pk1.list.size(); u++) {
Partition pu = pk1.list.get(u);
for (int v = 0; v < pk.list.size(); v++) {
Partition pv = pk.list.get(v);
loop: for (int e = 0; e <= g.k; e++) {
DSU dsu = new DSU(2 * g.k + 1);
for (int i = 0, j = 0; i < g.k + 1; ++i) {
if (i == e) {
continue;
}
if (dsu.get(pu.p[i]) == dsu.get(pv.p[j] + g.k + 1)) {
transitions[u][v][e] = -1;
continue loop;
}
dsu.unite(pu.p[i], pv.p[j] + g.k + 1);
j++;
}
int[] p = new int[g.k + 1];
int[] col = new int[2 * g.k + 1];
Arrays.fill(col, -1);
int cols = 0;
for (int i = 0; i < g.k + 1; ++i) {
int c = dsu.get(pu.p[i]);
if (col[c] == -1) {
col[c] = cols++;
}
p[i] = col[c];
}
transitions[u][v][e] = pk1.index.get(new Partition(p));
}
}
for (int e = 0; e < g.k; e++) {
DSU dsu = new DSU(g.k + 1);
if (dsu.get(pu.p[e]) == dsu.get(pu.p[g.k])) {
eTransitions[u][e] = -1;
continue;
}
dsu.unite(pu.p[e], pu.p[g.k]);
int[] p = new int[g.k + 1];
int[] col = new int[2 * g.k + 1];
Arrays.fill(col, -1);
int cols = 0;
for (int i = 0; i < g.k + 1; ++i) {
int c = dsu.get(pu.p[i]);
if (col[c] == -1) {
col[c] = cols++;
}
p[i] = col[c];
}
eTransitions[u][e] = pk1.index.get(new Partition(p));
}
int cLast = 0;
for (int i = 0; i < g.k + 1; ++i) {
if (pu.p[i] == pu.p[g.k]) {
cLast++;
}
}
if (cLast == 1) {
reductions[u] = -1;
} else {
reductions[u] = pk.index.get(new Partition(Arrays.copyOf(pu.p, g.k)));
}
}
HashMap<Facet, Facet> facetsSet = new HashMap<>();
int[] f0ar = new int[g.k];
for (int i = 0; i < g.k; ++i) {
f0ar[i] = i;
}
Facet f0 = new Facet(f0ar, pk);
Arrays.fill(f0.cs, 0);
for (int u = 0; u < pk.list.size(); u++) {
f0.cs[u] = pk.list.get(u).spanningTrees();
}
facetsSet.put(f0, f0);
Facet[][] facets = new Facet[g.es.length][g.k];
for (int i = g.k; i < g.k + g.es.length; ++i) {
for (int e = 0; e < g.k; ++e) {
int[] far = new int[g.k];
for (int t = 0, it = 0; t < g.k; ++t) {
if (t != e) {
far[it++] = g.es[i - g.k][t];
}
}
far[g.k - 1] = i;
facets[i - g.k][e] = new Facet(far, pk);
facetsSet.put(facets[i - g.k][e], facets[i - g.k][e]);
}
}
for (int i = g.k + g.es.length - 1; i >= g.k; --i) {
long[] d = new long[pk1.list.size()];
d[d.length - 1] = 1;
Facet fBase = facetsSet.get(new Facet(g.es[i - g.k], pk));
for (int e = 0; e <= g.k; ++e) {
Facet f = e < g.k ? facets[i - g.k][e] : fBase;
long[] d1 = new long[pk1.list.size()];
for (int u = 0; u < pk1.list.size(); ++u) {
for (int v = 0; v < pk.list.size(); v++) {
int w = transitions[u][v][e];
if (w != -1) {
d1[w] = (d1[w] + d[u] * f.cs[v]) % MOD;
}
}
}
d = d1;
}
for (int e = 0; e < g.k; ++e) {
long[] d1 = d.clone();
for (int u = 0; u < pk1.list.size(); ++u) {
int w = eTransitions[u][e];
if (w != -1) {
d1[w] = (d1[w] + d[u]) % MOD;
}
}
d = d1;
}
Arrays.fill(fBase.cs, 0);
for (int u = 0; u < pk1.list.size(); u++) {
int v = reductions[u];
if (v != -1) {
fBase.cs[v] = (fBase.cs[v] + d[u]) % MOD;
}
}
}
return f0.cs[0];
}
public static void solve(Input in, PrintWriter out) throws IOException {
int n = in.nextInt(), k = in.nextInt();
Graph g = new Graph();
g.k = k;
g.es = new int[n - k][k];
for (int i = k; i < n; ++i) {
for (int j = 0; j < k; ++j) {
g.es[i - k][j] = in.nextInt() - 1;
}
Arrays.sort(g.es[i - g.k]);
}
out.println(solveFast(g));
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
out.close();
}
static class Input {
BufferedReader in;
StringBuilder sb = new StringBuilder();
public Input(BufferedReader in) {
this.in = in;
}
public Input(String s) {
this.in = new BufferedReader(new StringReader(s));
}
public String next() throws IOException {
sb.setLength(0);
while (true) {
int c = in.read();
if (c == -1) {
return null;
}
if ("
".indexOf(c) == -1) {
sb.append((char)c);
break;
}
}
while (true) {
int c = in.read();
if (c == -1 || "
".indexOf(c) != -1) {
break;
}
sb.append((char)c);
}
return sb.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
643
|
A
|
Bear and Colors
|
Bear Limak has $n$ colored balls, arranged in one long row. Balls are numbered $1$ through $n$, from left to right. There are $n$ possible colors, also numbered $1$ through $n$. The $i$-th ball has color $t_{i}$.
For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.
There are $\textstyle{\frac{n(n+1)}{2}}$ non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.
|
We are going to iterate over all intervals. Let's first fix the left end of the interval and denote it by $i$. Now, we iterate over the right end $j$. When we go from $j$ to $j + 1$ then we get one extra ball with color $c_{j + 1}$. In one global array $cnt[n]$ we can keep the number of occurrences of each color (we can clear the array for each new $i$). We should increase by one $cnt[c_{j + 1}]$ and then check whether $c_{j + 1}$ becomes a new dominant color. But how to do it? Additionally, let's keep one variable $best$ with the current dominant color. When we go to $j + 1$ then we should whether $cnt[c_{j + 1}] > cnt[best]$ or ($cnt[c_{j + 1}] = = cnt[best]$ and $c_{j + 1} < best$). The second condition checks which color has smaller index (in case of a tie). And we must increase $answer[best]$ by one then because we know that $best$ is dominant for the current interval. At the end, print values $answer[1], answer[2], ..., answer[n]$.
|
[
"implementation"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
const int nax = 5005;
int t[nax], cnt[nax], answer[nax];
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
scanf("%d", &t[i]);
for(int low = 1; low <= n; ++low) {
for(int i = 1; i <= n; ++i)
cnt[i] = 0;
int best = 0;
for(int i = low; i <= n; ++i) {
int val = t[i];
++cnt[val];
if(cnt[val] > cnt[best] || (cnt[val] == cnt[best] && val < best))
best = val;
++answer[best];
}
}
for(int i = 1; i <= n; ++i) printf("%d ", answer[i]);
puts("");
return 0;
}
|
643
|
B
|
Bear and Two Paths
|
Bearland has $n$ cities, numbered $1$ through $n$. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city $a$ and he wanted to go to a city $b$. There was no direct connection so he decided to take a long walk, visiting each city \textbf{exactly once}. Formally:
- There is no road between $a$ and $b$.
- There exists a sequence (path) of $n$ distinct cities $v_{1}, v_{2}, ..., v_{n}$ that $v_{1} = a$, $v_{n} = b$ and there is a road between $v_{i}$ and $v_{i + 1}$ for $i\in\{1,2,\dots,n-1\}$.
On the other day, the similar thing happened. Limak wanted to travel between a city $c$ and a city $d$. There is no road between them but there exists a sequence of $n$ distinct cities $u_{1}, u_{2}, ..., u_{n}$ that $u_{1} = c$, $u_{n} = d$ and there is a road between $u_{i}$ and $u_{i + 1}$ for $i\in\{1,2,\dots,n-1\}$.
Also, Limak thinks that there are at most $k$ roads in Bearland. He wonders whether he remembers everything correctly.
Given $n$, $k$ and four distinct cities $a$, $b$, $c$, $d$, can you find possible paths $(v_{1}, ..., v_{n})$ and $(u_{1}, ..., u_{n})$ to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
|
There is no solution if $n = 4$ or $k \le n$. But for $n \ge 5$ and $k \ge n + 1$ you can construct the following graph: Here, cities $(x1, x2, ..., x_{n - 4})$ denote other cities in any order you choose (cities different than $a, b, c, d$). You should print $(a, c, x1, x2, ..., x_{n - 4}, d, b)$ in the first line, and $(c, a, x1, x2, ..., x_{n - 4}, b, d)$ in the second line. Two not very hard challenges for you. Are you able to prove that the answer doesn't exist for $k = n$? Can you solve the problem if the four given cities don't have to be distinct but it's guaranteed that $a \neq b$ and $c \neq d$? 18286683
|
[
"constructive algorithms",
"graphs"
] | 1,600
|
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, k, a, b, c, d;
scanf("%d%d%d%d%d%d", &n, &k, &a, &b, &c, &d);
if(k <= n || n <= 4) {
puts("-1");
return 0;
}
for(int rep = 0; rep < 2; ++rep) {
printf("%d %d ", a, c);
for(int i = 1; i <= n; ++i)
if(i != a && i != b && i != c && i != d)
printf("%d ", i);
printf("%d %d\n", d, b);
swap(a, c);
swap(b, d);
}
return 0;
}
|
643
|
C
|
Levels and Regions
|
Radewoosh is playing a computer game. There are $n$ levels, numbered $1$ through $n$. Levels are divided into $k$ regions (groups). Each region contains some positive number of consecutive levels.
The game repeats the the following process:
- If all regions are beaten then the game ends immediately. Otherwise, the system finds the first region with at least one non-beaten level. Let $X$ denote this region.
- The system creates an empty bag for tokens. Each token will represent one level and there may be many tokens representing the same level.
- For each already beaten level $i$ in the region $X$, the system adds $t_{i}$ tokens to the bag (tokens representing the $i$-th level).
- Let $j$ denote the first non-beaten level in the region $X$. The system adds $t_{j}$ tokens to the bag.
- Finally, the system takes a uniformly random token from the bag and a player starts the level represented by the token. A player spends one hour and beats the level, even if he has already beaten it in the past.
Given $n$, $k$ and values $t_{1}, t_{2}, ..., t_{n}$, your task is to split levels into regions. Each level must belong to exactly one region, and each region must contain non-empty consecutive set of levels. What is the minimum possible expected number of hours required to finish the game?
|
When we repeat something and each time we have probability $p$ to succeed then the expected number or tries is $\textstyle{\frac{1}{p}}$, till we succeed. How to calculate the expected time for one region $[low, high]$? For each $i$ in some moment we will try to beat this level and then there will be $S = t_{low} + t_{low + 1} + ... + t_{i}$ tokens in the bag, including $t_{i}$ tokens allowing us to beat this new level. The probability to succeed is $\frac{t_{i}}{\mathbf{S}}$, so the expected time is $\frac S{t_{i}}^{S}\,=\,\frac{t_{l o w}}{t_{i}}\,+\,\frac{t_{l o w}^{\quad t_{l o w}+1}}{t_{i}}\,+\,\cdot\,\cdot\,\cdot\,+\,\frac{t_{i}}{t_{i}}\nonumber\,$. So, in total we should sum up values $\scriptstyle{\frac{t(t)}{t}}$ for $i < j$. Ok, we managed to understand the actual problem. You can now stop and try to find a slow solution in $O(n^{2} \cdot k)$. Hint: use the dynamic programming. Now let's write formula for $dp[i][j]$, as the minimum over $l$ denoting the end of the previous region: $d p[i][j]=m a x_{l}\Biggl(d p[l][j-1]+p r e[i]-p r e[l]-(r e v[i]-r e v[l])\star s u m[l]\Biggr)=$ $\begin{array}{c}{{=p r e[i]+m a x_{l}\biggl((1)*(d p[l][j-1]-p r e[l]+r e v[l]*s u m[l])+(-r e v[i])*}}\\ {{\qquad\qquad\qquad\qquad\qquad(s u m[l])\biggr)=}}\end{array}$ $=p r e[i]+m a x_{l}\left((1,-r e v[i])X(d p[l][j-1]-p r e[l]+r e v[l]+r e v[l]+s u m[l])\right)$ So we can use convex hull trick to calculate it in $O(n \cdot k)$. You should also get AC with a bit slower divide&conquer trick, if it's implemented carefully.
|
[
"dp"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
int n, k;
double wcz;
long double sum[200007];
long double rev[200007];
long double pre[200007];
long double inf;
long double dpo[200007];
long double dpn[200007];
long double x[200007];
long double y[200007];
int l;
vector <int> sta;
inline long double vec(int s, int a, int b)
{
return (x[a]-x[s])*(y[b]-y[s])-(x[b]-x[s])*(y[a]-y[s]);
}
int main()
{
inf=1000000000.0;
inf*=inf;
scanf("%d%d", &n, &k);
for (int i=1; i<=n; i++)
{
scanf("%lf", &wcz);
sum[i]=wcz;
pre[i]=pre[i-1]+sum[i-1]/sum[i]+1.0;
rev[i]=1.0/sum[i]+rev[i-1];
sum[i]+=sum[i-1];
}
for (int i=1; i<=n; i++)
{
dpn[i]=pre[i];
}
for (int h=2; h<=k; h++)
{
for (int i=0; i<=n; i++)
{
dpo[i]=dpn[i];
dpn[i]=pre[i];
x[i]=dpo[i]+rev[i]*sum[i]-pre[i];
y[i]=sum[i];
}
sta.clear();
l=0;
for (int i=1; i<=n; i++)
{
while(sta.size()>1 && vec(sta[sta.size()-2], sta[sta.size()-1], i-1)>=0)
sta.pop_back();
l=min(l, (int)sta.size()-1);
l=max(l, 0);
sta.push_back(i-1);
while(l+1<sta.size() && 1*x[sta[l+1]]-rev[i]*y[sta[l+1]]<=1*x[sta[l]]-rev[i]*y[sta[l]])
l++;
dpn[i]+=1*x[sta[l]]-rev[i]*y[sta[l]];
}
}
printf("%.10lf\n", (double)dpn[n]);
return 0;
}
|
643
|
D
|
Bearish Fanpages
|
There is a social website with $n$ fanpages, numbered $1$ through $n$. There are also $n$ companies, and the $i$-th company owns the $i$-th fanpage.
Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow.
The website doesn’t allow a situation where $i$ follows $j$ and at the same time $j$ follows $i$. Also, a fanpage can't follow itself.
Let’s say that fanpage $i$ follows some other fanpage $j_{0}$. Also, let’s say that $i$ is followed by $k$ other fanpages $j_{1}, j_{2}, ..., j_{k}$. Then, when people visit fanpage $i$ they see ads from $k + 2$ distinct companies: $i, j_{0}, j_{1}, ..., j_{k}$. Exactly $t_{i}$ people subscribe (like) the $i$-th fanpage, and each of them will click exactly one add. For each of $k + 1$ companies $j_{0}, j_{1}, ..., j_{k}$, exactly $\left\lfloor{\frac{t_{i}}{k+2}}\right\rfloor$ people will click their ad. Remaining $t_{i}-(k+1)\cdot\left\lfloor{\frac{t_{i}}{k+2}}\right\rfloor$ people will click an ad from company $i$ (the owner of the fanpage).
The total income of the company is equal to the number of people who click ads from this copmany.
Limak and Radewoosh ask you for help. Initially, fanpage $i$ follows fanpage $f_{i}$. Your task is to handle $q$ queries of three types:
- 1 i j — fanpage $i$ follows fanpage $j$ from now. It's guaranteed that $i$ didn't follow $j$ just before the query. Note an extra constraint for the number of queries of this type (below, in the Input section).
- 2 i — print the total income of the $i$-th company.
- 3 — print two integers: the smallest income of one company and the biggest income of one company.
|
Let's say that every company has one parent (a company it follows). Also, every copmany has some (maybe empty) set of children. It's crucial that sets of children are disjoint. For each company let's keep (and always update) one value, equal to the sum of: It turns out that after each query only the above sum changes only for a few values. If $a$ starts to follows $b$ then you should care about $a, b, par[a], par[b], par[par[a]]$. And maybe $par[par[b]]$ and $par[par[par[a]]]$ if you want to be sure. You can stop reading now for a moment and analyze that indeed other companies will keep the same sum, described above. Ok, but so far we don't count the income coming from parent's fanpage. But, for each company we can store all its children in one set. All children have the same "income from parent's fanpage" because they have the same parent. So, in set you can keep children sorted by the sum described above. Then, we should always puts the extreme elements from sets in one global set. In the global set you care about the total income, equal to the sum described above and this new "income from parent". Check codes for details. The complexity should be $O((n+q)\cdot\log n)$, with big constant factor.
|
[] | 2,900
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int nax = 1e6 + 5;
int par[nax];
ll t[nax];
multiset<ll> BEST;
ll interior[nax]; // the income from my fanpage and my children's fanpages
// (so, doesn't include income from my parent)
struct cmp {
bool operator ()(int a, int b) {
if(interior[a] != interior[b])
return interior[a] < interior[b];
return a < b;
}
};
struct Children {
set<int,cmp> s;
vector<ll> getBest() {
vector<ll> ret;
if(!s.empty())
ret.push_back(interior[*s.begin()]);
if((int) s.size() >= 2) {
auto it = s.end();
--it;
ret.push_back(interior[*it]);
}
return ret;
}
void insert(int a) {
s.insert(a);
}
void erase(int a) {
s.erase(a);
}
int degree; // not always equal to s.size(), to allow more comfortable updates
} children[nax];
ll value_for_other(int a) {
return t[a] / (2 + children[a].degree);
}
ll value_for_self(int a) {
return t[a] - (1 + children[a].degree) * value_for_other(a);
}
int main() {
int n, q;
scanf("%d%d", &n, &q);
for(int i = 1; i <= n; ++i)
scanf("%lld", &t[i]);
for(int i = 1; i <= n; ++i) {
scanf("%d", &par[i]);
children[par[i]].degree++;
children[par[i]].insert(i);
}
// calculate initial values of interior[n]
for(int i = 1; i <= n; ++i) {
children[par[i]].erase(i);
// income from my fanpage
interior[i] = value_for_self(i);
// and from children's fanpages
for(int x : children[i].s)
interior[i] += value_for_other(x);
children[par[i]].insert(i);
}
// fill BEST
for(int i = 1; i <= n; ++i) {
vector<ll> values = children[i].getBest();
for(ll value : values)
BEST.insert(value + value_for_other(i));
}
// read and process queries
while(q--) {
int type;
scanf("%d", &type);
if(type == 1) {
int a, b;
scanf("%d%d", &a, &b);
set<int> interesting = set<int>{a, b, par[a], par[b], par[par[a]]};
set<int> more = interesting;
for(int x : interesting) more.insert(par[x]);
for(int x : more) {
vector<ll> values = children[x].getBest();
for(ll value : values) {
auto it = BEST.find(value + value_for_other(x));
assert(it != BEST.end());
BEST.erase(it);
}
}
for(int x : interesting)
children[par[x]].erase(x);
for(int rep = -1; rep <= 1; rep += 2) { // first -1, then 1
for(int x : interesting) {
interior[x] += rep * value_for_self(x);
for(int y : interesting)
if(par[y] == x)
interior[x] += rep * value_for_other(y);
}
if(rep == -1) {
children[par[a]].degree--;
par[a] = b;
children[par[a]].degree++;
}
}
for(int x : interesting)
children[par[x]].insert(x);
for(int x : more) {
vector<ll> values = children[x].getBest();
for(ll value : values)
BEST.insert(value + value_for_other(x));
}
}
else if(type == 2) {
int a;
scanf("%d", &a);
printf("%lld\n", interior[a] + value_for_other(par[a]));
}
else {
printf("%lld ", *BEST.begin());
auto it = BEST.end();
--it;
printf("%lld\n", *it);
}
}
return 0;
}
|
643
|
E
|
Bear and Destroying Subtrees
|
Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index $1$ and is a root of the tree.
Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability $\textstyle{\frac{1}{2}}$, independently of other edges. Then, Limak gets the penalty — an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.
You must handle queries of two types.
- 1 v denotes a query of the first type. A new vertex appears and its parent is $v$. A new vertex has the next available index (so, new vertices will be numbered $2, 3, ...$).
- 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in $v$. Then, what would be the expected value of the penalty Limak gets after the attack?
In a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries.
|
Let $dp[v][h]$ denote the probability that subtree $v$ (if attacked now) would have height at most $h$. The first observation is that we don't care about big $h$ because it's very unlikely that a path with e.g. 100 edges will survive. Let's later talk about choosing $h$ and now let's say that it's enough to consider $h$ up to $60$. When we should answer a query for subtree $v$ then we should sum up $h \cdot (dp[v][h] - dp[v][h - 1])$ to get the answer. The other query is harder. Let's say that a new vertex is attached to vertex $v$. Then, among $dp[v][0], dp[v][1], dp[v][2], ...$ only $dp[v][0]$ changes (other values stay the same). Also, one value $dp[par[v]][1]$ changes, and so does $dp[par[par[v]]][2]$ and so on. You should iterate over $MAX_H$ vertices (each time going to parent) and update the corresponding value. TODO - puts here come formula for updating value. The complexity is $O(q \cdot MAX_H)$. You may think that $MAX_H = 30$ is enough because $\frac{1}{2^{3}/0}$ is small enough. Unfortunately, there exist malicious tests. Consider a tree with $\stackrel{N}{\mathrm{3I}}$ paths from root, each with length $31$. Now, we talk about the probability of magnitude: $1 - (1 - (1 / 2)^{d})^{N / d}$ which is more than $10^{ - 6}$ for $d = 30$.
|
[
"dp",
"math",
"probabilities",
"trees"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
int q;
int n=1;
int par[500007];
int d=60;
double dp[500007][63];
int p1, p2;
vector <int> sta;
void ans(int v)
{
double res=0.0;
for (int i=1; i<=d; i++)
{
res+=1.0-dp[v][i];
}
printf("%.10lf\n", res);
}
void add(int v)
{
n++;
par[n]=v;
sta.clear();
v=n;
for (int i=1; i<=d; i++)
{
dp[n][i]=1.0;
}
for (int i=1; i<=d+1 && v; i++)
{
sta.push_back(v);
v=par[v];
}
for (int i=(int)sta.size()-2; i>0; i--)
{
dp[sta[i+1]][i+1]/=(dp[sta[i]][i]+1.0)/2.0;
}
for (int i=0; i+1<(int)sta.size(); i++)
{
dp[sta[i+1]][i+1]*=(dp[sta[i]][i]+1.0)/2.0;
}
}
int main()
{
scanf("%d", &q);
for (int i=1; i<=d; i++)
{
dp[1][i]=1.0;
}
while(q--)
{
scanf("%d%d", &p1, &p2);
if (p1==1)
add(p2);
else
ans(p2);
}
return 0;
}
|
643
|
F
|
Bears and Juice
|
There are $n$ bears in the inn and $p$ places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
- Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.
- Each bear drinks a glass from each barrel he chose.
- All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers $q$ scenarios. In the $i$-th scenario the party will last for $i$ nights. Then, let $R_{i}$ denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define $X_{i}=(i\cdot R_{i})\ \ \mathrm{mod}\ 2^{32}$. Your task is to find $X_{1}\oplus X_{2}\oplus\cdot\cdot\Leftrightarrow X_{q}$, where $\mathbb{C}$ denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
|
Let's start with $O(q \cdot p^{2})$ approach, with the dynamic programming. Let $dp[days][beds]$ denote the maximum number of barrels to win if there are $days$ days left and $beds$ places to sleep left. Then: $d p[d a y s][b e d s]=\sum_{i}d p[d a y s-1][b e d s-i]\cdot C(n-(p-b e d s),i)$ Here, $i$ represents the number of bears who will go to sleep. If the same $i$ bears drink from the same $X$ barrels and this exact set of bears go to sleep then on the next day we only have $X$ barrels to consider (wine is in one of them). And for $X = dp[days - 1][beds - i]$ we will manage to find the wine then. And how to compute the dp faster? Organizers have ugly solution with something similar to meet in the middle. We calculate dp for first $q^{2 / 3}$ days and later we use multiply vectors by matrix, to get further answers faster. The complexity is equivalent to $O(p \cdot q)$ but only because roughly $q = p^{3}$. We saw shortest codes though. How to do it guys? You may wonder why there was $2^{32}$ instead of $10^{9} + 7$. It was to fight with making the brute force faster. For $10^{9} + 7$ you could add $sum + = dp[a][b] \cdot dp[c][d]$ about $15$ times (using unsigned long long's) and only then compute modulo. You would then get very fast solution.
|
[
"dp",
"math",
"meet-in-the-middle"
] | 2,900
|
#include<bits/stdc++.h>
using namespace std;
typedef unsigned int T;
T C(T a, T b) {
assert(a >= b && b >= 0);
vector<T> w;
for(T i = 0; i < b; ++i)
w.push_back(a - i);
for(T i = 1; i <= b; ++i) {
T x = i;
for(T & y : w) {
T g = __gcd(x, y);
x /= g;
y /= g;
}
assert(x == 1);
}
T ans = 1;
for(T x : w) ans *= x;
return ans;
}
const T MAX_P = 132;
const T MAX_Q = 2000 * 1000 + 5;
const T magic = 1024 * 16;
struct M {
T t[MAX_P][MAX_P];
T p;
M operator * (M other) {
M ans;
ans.p = p;
#define FOR(i) for(T i = 0; i <= p; ++i)
FOR(i) FOR(j) ans.t[i][j] = 0;
FOR(i) FOR(j) FOR(k)
ans.t[i][k] += t[i][j] * other.t[j][k];
return ans;
}
};
M matrices[MAX_Q / magic + 1];
T dp[magic][MAX_P], memo_C[MAX_P][MAX_P];
int main() {
ios_base :: sync_with_stdio(false);
T n, p, q;
cin >> n >> p >> q;
p = min(p, n - 1); // we allow at most n-1 bears to go to sleep
for(T beds = 0; beds <= p; ++beds)
for(T i = 0; i <= beds; ++i)
memo_C[beds][i] = C(n-(p-beds), i);
// compute matrices
for(T i = 0; i <= p; ++i)
matrices[0].t[i][i] = 1;
M & basic = matrices[1];
basic.p = p;
for(T beds = 0; beds <= p; ++beds)
for(T i = 0; i <= beds; ++i)
basic.t[beds-i][beds] = memo_C[beds][i];
for(T i = 1; i < magic; i *= 2)
basic = basic * basic;
for(T i = 2; i <= q / magic; ++i)
matrices[i] = matrices[1] * matrices[i-1];
// compute first vectors
for(T beds = 0; beds <= p; ++beds)
dp[0][beds] = 1;
for(T day = 1; day < magic; ++day)
for(T beds = 0; beds <= p; ++beds)
for(T i = 0; i <= beds; ++i) {
T & x = dp[day][beds];
x += dp[day-1][beds-i] * memo_C[beds][i];
}
T hashed;
for(T i = 1; i <= q; ++i) {
T i_dp = i % magic;
T i_matr = i / magic;
T ans = 0;
for(T beds = 0; beds <= p; ++beds)
ans += dp[i_dp][beds] * matrices[i_matr].t[beds][p];
hashed ^= i * ans;
}
cout << hashed << "\n";
return 0;
}
|
643
|
G
|
Choosing Ads
|
One social network developer recently suggested a new algorithm of choosing ads for users.
There are $n$ slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users.
Every time it is needed to choose ads to show, some segment of slots is picked by a secret algorithm. Then some advertisers are chosen. The only restriction is that it should be guaranteed for advertisers which own at least $p$% of slots composing this segment that their ad will be shown.
From the other side, users don't like ads. So it was decided to show no more than $\left|{\frac{100}{p}}\right|$ ads at once. You are asked to develop a system to sell segments of slots and choose ads in accordance with the rules described above.
|
Let's first consider a solution processing query in O(n) time, but using O(1) extra memory. If p = 51%, it's a well known problem. We should store one element and some balance. When processing next element, if it's equal to our, we increase balance. If it's not equal, and balance is positive, we decrease it. If it is zero, we getting new element as stored, and setting balance to 1. To generalize to case of elements, which are at least 100/k%, we will do next. Let's store k elements with balance for each. When getting a new element, if it's in set of our 5, we will add 1 to it's balance. If we have less, than 5 elements, just add new element with balance 1. Else, if there is element with balance 0, replace it by new element with balance one. Else, subtract 1 from each balance. The meaning of such balance becomes more mysterious, but it's not hard to check, that value is at least 100/k% of all elements, it's balance will be positive. To generalize even more, we can join two of such balanced set. To do that, we sum balances of elements of all sets, than join sets to one, and then removing elements with smallest balance one, by one, untill there is k elements in set. To remove element, we should subtract it's balance from all other balances. And now, we can merge this sets on segment, using segment tree. This solution will have complexity like $n * log(n) * MERGE$, where MERGE is time of merging two structures. Probably, when k is 5, $k^{2} / 2$ is fastest way. But the profit is we don't need complex structures to check which elements are really in top, so solution works much faster.
|
[
"data structures"
] | 3,200
| null |
645
|
A
|
Amity Assessment
|
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a $2 × 2$ grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
|
One solution is to just brute force and use DFS to try all the possibilities. Alternatively, note that two puzzles can be changed to each other if and only if the $A$, $B$, and $C$ have the same orientation-clockwise or counterclockwise-in the puzzle. A third option, since the number of possibilities is so small, is to simply classify all of the $4! = 24$ configurations by hand.
|
[
"brute force",
"constructive algorithms",
"implementation"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
string b, b1, b2, e, e1, e2;
int main(){
cin >> b1 >> b2 >> e1 >> e2;
swap(b2[0], b2[1]);
swap(e2[0], e2[1]);
b = b1 + b2;
e = e1 + e2;
b.erase(b.find('X'), 1);
e.erase(e.find('X'), 1);
if((b + b).find(e) != string::npos){
cout << "YESn";
} else {
cout << "NOn";
}
}
|
645
|
B
|
Mischievous Mess Makers
|
It is a balmy spring afternoon, and Farmer John's $n$ cows are ruminating about link-cut cacti in their stalls. The cows, labeled $1$ through $n$, are arranged so that the $i$-th cow occupies the $i$-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his $k$ minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making \textbf{no more than one} swap each minute.
Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the $k$ minutes that they have. We denote as $p_{i}$ the label of the cow in the $i$-th stall. The messiness of an arrangement of cows is defined as the number of pairs $(i, j)$ such that $i < j$ and $p_{i} > p_{j}$.
|
Loosely speaking, we're trying to reverse the array as much as possible. Intuitively, the optimal solution seems to be to switch the first and last cow, then the second and second-to-last cow, and so on for $k$ minutes, unless the sequence is reversed already, in which case we are done. But how can we show that these moves give the optimal messiness? It is clear when $2 \cdot k \ge n - 1$ that we can reverse the array with this method. However, when $2 \cdot k < n - 1$, there are going to be cows that we must not have not moved a single time. Since in each move we swap at most $2$ cows, there must be at least $n - 2 \cdot k$ cows that we have not touched, with $p_{i} = i$. Two untouched cows $i$ and $j$ must have $p_{i} < p_{j}$, so there must be at least $\frac{(n-2\cdot k)(n-2\cdot k-1)}{2}$ pairs of cows which are ordered correctly. In fact, if we follow the above process, we get that $p_{i} = (n + 1) - i$ for the first $k$ and last $k$ cows, while $p_{i} = i$ for the middle $n - 2 \cdot k$ cows. From this we can see that the both $i < j$ and $p_{i} < p_{j}$ happen only when $i$ and $j$ are in the middle $n - 2 \cdot k$ cows. Therefore we know our algorithm is optimal. An $O(k)$ solution, therefore, is to count how many incorrectly ordered pairs $(i, j)$ are created at each step and add them up. When we swap cow $i$ and $(n + 1) - i$ in step $i$, this creates $1 + 2 \cdot (n - 2i)$ more pairs. So the answer will be $\textstyle\sum_{i=1}^{k}1+2(n-2i)$. We can reduce this to $O(1)$ by using our earlier observation, that every pair except those $\frac{(n-2\cdot k)(n-2\cdot k-1)}{2}$ pairs are unordered, which gives ${\frac{n(n-1)}{2}}-{\frac{(n-2\cdot k)(n-2\cdot k-1)}{2}}$ total pairs $(i, j)$. Note that this does always not fit in a 32-bit integer.
|
[
"greedy",
"math"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
LL n, k;
cin >> n >> k;
LL c = max(n-2*k,0LL);
LL a = n*(n-1)/2-c*(c-1)/2;
cout << a << endl;
}
|
645
|
C
|
Enduring Exodus
|
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his $k$ cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of $n$ rooms located in a row, some of which are occupied.
Farmer John wants to book a set of $k + 1$ currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms $i$ and $j$ is defined as $|j - i|$. Help Farmer John protect his cows by calculating this minimum possible distance.
|
First, observe that the $k + 1$ rooms that Farmer John books should be consecutive empty rooms. Thus we can loop over all such sets of rooms with a sliding window in linear time. To check the next set of rooms, we simply advance each endpoint of our interval to the next empty room. Every time we do this, we need to compute the optimal placement of Farmer John's room. We can maintain the position of his room with two pointers-as we slide our window of rooms to the right, the optimal position of Farmer John's room should always move to the right or remain the same. This solution runs in $O(n)$. Alternatively, we can use binary search or an STL set to find the best placement for Farmer John's room as we iterate over the intervals of rooms. The complexity of these approaches is $O(n\log n)$.
|
[
"binary search",
"two pointers"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int N, K, res = 1e9;
string S;
int next(int i){ // finds the next empty room
do {
i += 1;
} while(i < N && S[i] == '1');
return i;
}
int main(){
cin >> N >> K >> S;
int l = next(-1), m = l, r = l;
for(int i = 0; i < K; i++){ // sets up the sliding window
r = next(r);
}
while(r < N){
while(max(m - l, r - m) > max(next(m) - l, r - next(m))){
m = next(m);
}
res = min(res, max(m - l, r - m));
l = next(l);
r = next(r);
}
cout << res << 'n';
}
|
645
|
D
|
Robot Rapping Results Report
|
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot $i$ will beat robot $j$ if and only if robot $i$ has a higher skill level than robot $j$. And if robot $i$ beats robot $j$ and robot $j$ beats robot $k$, then robot $i$ will beat robot $k$. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the \textbf{minimum number} of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
|
The robots will become fully sorted if and only if there exists a path with $n$ vertices in the directed graph defined by the match results. Because it is guaranteed that the results are not contradictory, this graph must be directed and acyclic-a DAG. Thus we can compute the longest path in this DAG via dynamic programming or a toposort. We now have two cases. First, if the longest path contains $n$ vertices, then it must uniquely define the ordering of the robots. This means the answer is the time at which the last edge was added to this path. Otherwise, if the longest path has fewer than $n$ vertices, then multiple orderings satisfy the results and you should print $- 1$. Note that this algorithm runs in $O(n + m)$. Another solution to this problem binary searches on the answer. For some $k$, consider only those edges that were added before time $k$. We can determine if the robots could be totally ordered at time $k$ by running a toposort and checking if the longest path covers all $n$ vertices. This might be more intuitive for some, but has a complexity of $O(n\log n)$.
|
[
"binary search",
"dp",
"graphs"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000005;
int N, M, dp[MAXN], res[MAXN];
vector<pair<int,int>> adj[MAXN];
int check(int v){
if(dp[v]) return dp[v];
dp[v] = 1;
for(auto p : adj[v]){
int n = p.first;
if(check(n) + 1 > dp[v]){
dp[v] = dp[n] + 1;
res[v] = max(res[n], p.second);
}
}
return dp[v];
}
int main(){
scanf("%d%d", &N, &M);
for(int i = 0; i < M; i++){
int a, b;
scanf("%d%d", &a, &b);
a -= 1, b -= 1;
adj[a].push_back({b, i + 1});
}
for(int i = 0; i < N; i++){
if(check(i) == N){
printf("%dn", res[i]);
return 0;
}
}
printf("-1n");
}
|
645
|
E
|
Intellectual Inquiry
|
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first $k$ English letters.
Each morning, Bessie travels to school along a sidewalk consisting of $m + n$ tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first $m$ sidewalk tiles with one of the first $k$ lowercase English letters, spelling out a string $t$. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last $n$ tiles of the sidewalk by herself.
Consider the resulting string $s$ ($|s| = m + n$) consisting of letters labeled on tiles in order from home to school. For any sequence of indices $p_{1} < p_{2} < ... < p_{q}$ we can define subsequence of the string $s$ as string $s_{p1}s_{p2}... s_{pq}$. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of \textbf{distinct subsequences} of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!
Note that empty subsequence also counts.
|
For simplicity, let's represent the letters by $1, 2, ..., k$ instead of actual characters. Let $a[i]$ denote the number of distinct subsequences of the string that end in the letter $i$. Appending the letter $j$ to a string only changes the value of $a[j]$. Note that the new $a[j]$ becomes $1+\sum_{i=1}^{k}a[i]$-we can have the single letter $j$, or append $j$ to any of our old subsequences. The key observation is that no matter what character $j$ we choose to append, $a[j]$ will always end up the same. This suggests a greedy algorithm-always appending the character $j$ with the smallest $a[j]$. But how do we know which $a[j]$ is minimal while maintaining their values modulo $10^{9} + 7$? The final observation is that if the last occurrence of $j$ is after the last occurrence of $j'$ in our string, then $a[j] > a[j']$. This is true because appending $j$ to the string makes $a[j]$ larger than all other $a[i]$. So instead of choosing the minimum $a[i]$, we can always choose the letter that appeared least recently. Since the sequence of letters we append becomes periodic, our solution runs in $O(L+n+k\log k)$. Of course, we can also find the least recently used letter with less efficient approaches, obtaining solutions with complexity $O((L + n)k)$.
|
[
"dp",
"greedy",
"strings"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
const int MAXK = 26;
int N, K, last[MAXK], ord[MAXK];
ll dp[MAXK], sum;
string S;
bool comp(int a, int b){
return last[a] < last[b];
}
void append(int c){
sum = (sum - dp[c] + MOD) % MOD;
dp[c] = (dp[c] + sum + 1) % MOD;
sum = (sum + dp[c]) % MOD;
}
int main(){
cin >> N >> K >> S;
fill(last, last + K, -1);
for(int i = 0; i < S.size(); i++){
int c = S[i] - 'a';
last[c] = i;
append(c);
}
iota(ord, ord + K, 0);
sort(ord, ord + K, comp);
for(int i = 0; i < N; i++){
int c = ord[i % K];
append(c);
}
cout << (sum + 1) % MOD << 'n';
}
|
645
|
F
|
Cowslip Collections
|
In an attempt to make peace with the Mischievious Mess Makers, Bessie and Farmer John are planning to plant some flower gardens to complement the lush, grassy fields of Bovinia. As any good horticulturist knows, each garden they plant must have the exact same arrangement of flowers. Initially, Farmer John has $n$ different species of flowers he can plant, with $a_{i}$ flowers of the $i$-th species.
On each of the next $q$ days, Farmer John will receive a batch of flowers of a new species. On day $j$, he will receive $c_{j}$ flowers of the same species, but of a different species from those Farmer John already has.
Farmer John, knowing the right balance between extravagance and minimalism, wants exactly $k$ species of flowers to be used. Furthermore, to reduce waste, each flower of the $k$ species Farmer John chooses must be planted in some garden. And each of the gardens must be identical; that is to say that each of the $k$ chosen species should have an equal number of flowers in each garden. As Farmer John is a proponent of national equality, he would like to create the greatest number of gardens possible.
After receiving flowers on each of these $q$ days, Farmer John would like to know the sum, over all possible choices of $k$ species, of the maximum number of gardens he could create. Since this could be a large number, you should output your result modulo $10^{9} + 7$.
|
After each query, the problem is essentially asking us to compute the sum of $\mathrm{gcd}(f_{1},f_{2},\cdot\cdot\cdot\,,f_{k})$ for each choice of $k$ flowers. One quickly notes that it is too slow to loop over all choices of $k$ flowers, as there could be up to $\binom{n+q}{k}$ choices of $k$ species. So how can we compute a sum over $\binom{n+q}{k}$ terms? Well, we will definitely need to use the properties of the gcd function. If we figure out for each integer $a \le 10^{6}$ how many times $\operatorname{gcd}(f_{1},f_{2},\cdot\cdot\cdot,f_{k})=a$ occurs in the sum (let this be $g(a)$), then our answer will be equal to $\sum_{a}a\cdot g(a)$ overall all $a$. It seems that if $d(a)$ is the number of multiples of $a$ in our sequence, then there are $\binom{d(a)}{k}$ $k$-tuples which have gcd $a$. Yet there is something wrong with this reasoning: some of those $k$-tuples can have gcd $2a$, or $3a$, or any multiple of $a$. In fact, ${\binom{d(a)}{k}}=\sum_{a\bar{|m|}}g(m)$, the number of gcds which are a multiple of $a$. We will try to write $\sum_{a}a\cdot g(a)$ as a sum of these $\sum_{a|m}g(m)$. We'll take an example, when $a$ ranges from $1$ to $4$. The sum we wish to compute is $g(1) + 2g(2) + 3g(3) + 4g(4)$ which can be written as $(g(1) + g(2) + g(3) + g(4)) + (g(2) + g(4)) + 2(g(3)) + 2(g(4)),$ or $\sum_{1i m}g(m)+\sum_{2|m}g(m)+2\sum_{3i m}g(m)+2\sum_{4|m}g(m).$ In general, we want to find coefficients $p_{i}$ such that we can write $\sum_{a}a\cdot g(a)$ as $\sum_{i}p_{i}\left(\sum_{i\vert m}g(m)\right)=\sum_{i}p_{i}\biggl(\stackrel{d(i)}{k}\biggr)$. Equating coefficients of $g(a)$ on both sides, we get that $a=\sum_{i\lfloor a}p_{i}$. (The mathematically versed reader will note that $p_{i} = \phi (i)$, Euler's totient function, but this is not necessary to solve the problem.) We can thus precalculate all $p_{i}$ in $O(A\log(A))$ using a recursive formula: $p_{i}=a-\sum_{i\vert a.i\neq a}p_{i}$. We can also precalculate $\binom{l}{k}$ for each $l \le 200000$, so in order to output $\sum_{i=1}^{100000}p_{i}{\binom{d(i)}{k}}$ after each query we should keep track of the values of the function $d(i)$, the number of multiples of $i$. When receiving $c_{i}$ flowers, we only need to update $d$ for the divisors of $c_{i}$ and add ${\binom{d+1}{k}}-{\binom{d}{k}}$. If we precompute the list of divisors of every integer using a sieve or sqrt checking, each update requires $O(divisors)$. Thus the complexity of this algorithm is $O(A\log A)$ or $O(A{\sqrt{A}})$ preprocessing, and $O((n + q) \cdot max(divisors))$.
|
[
"combinatorics",
"math",
"number theory"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
const int MAXN = 200005;
const int MAXA = 1000005;
int N, K, Q, A[MAXN];
int use[MAXA], phi[MAXA], cnt[MAXA];
vector<int> divisors[MAXA];
ll bin[MAXN], res;
ll inv(ll a, ll p){
if(a == 1) return 1;
return (p - p / a) * inv(p % a, p) % p;
}
void read(){
scanf("%d%d%d", &N, &K, &Q);
for(int i = 0; i < N + Q; i++){
scanf("%d", &A[i]);
use[A[i]] = 1;
}
}
void init(){
iota(phi, phi + MAXA, 0);
for(int i = 1; i < MAXA; i++){
for(int j = i; j < MAXA; j += i){
if(i != j) phi[j] -= phi[i];
if(use[j]) divisors[j].push_back(i);
}
}
bin[K - 1] = 1;
for(int i = K; i < MAXN; i++){
bin[i] = bin[i - 1] * i % MOD * inv(i - K + 1, MOD) % MOD;
}
}
int main(){
read();
init();
for(int i = 0; i < N + Q; i++){
for(int d : divisors[A[i]]){
res = (res + bin[cnt[d]] * phi[d]) % MOD;
cnt[d] += 1;
}
if(i >= N){
printf("%dn", res);
}
}
}
|
645
|
G
|
Armistice Area Apportionment
|
After a drawn-out mooclear arms race, Farmer John and the Mischievous Mess Makers have finally agreed to establish peace. They plan to divide the territory of Bovinia with a line passing through at least two of the $n$ outposts scattered throughout the land. These outposts, remnants of the conflict, are located at the points $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$.
In order to find the optimal dividing line, Farmer John and Elsie have plotted a map of Bovinia on the coordinate plane. Farmer John's farm and the Mischievous Mess Makers' base are located at the points $P = (a, 0)$ and $Q = ( - a, 0)$, respectively. Because they seek a lasting peace, Farmer John and Elsie would like to minimize the maximum difference between the distances from any point on the line to $P$ and $Q$.
Formally, define the \textbf{difference} of a line ${\mathit{l}}_{\circ}$ relative to two points $P$ and $Q$ as the smallest real number $d$ so that for all points $X$ on line ${\mathit{l}},$, $|PX - QX| ≤ d$. (It is guaranteed that $d$ exists and is unique.) They wish to find the line ${\mathit{l}},$ passing through two distinct outposts $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ such that the difference of ${\mathit{l}},$ relative to $P$ and $Q$ is minimized.
|
First, let's try to solve the smaller case where we only have two points. Let ${\mathit{l}},$ be the line passing through $x_{i}$ and $x_{j}$. We want to compute the difference of ${\mathit{l}}_{\circ}$ relative to $P$ and $Q$. Define $P'$ as the reflection of $P$ over ${\mathit{l}},$. By the triangle inequality, we have $|PX - QX| = |P'X - QX| \le P'Q$. Equality can be achieved when $X$, $P'$ and $Q$ are collinear-that is, when $X$ is the intersection of ${\mathit{l}},$ and line $P'Q$. (If ${\mathit{l}},$ and $P'Q$ are parallel, we can imagine that they intersect at infinity.) Therefore, the difference of a line ${\mathit{l}},$ relative to $P$ and $Q$ is the distance from $P'$ to $Q$. We can also think about $P'$ in a different way. Let $C_{i}$ be the circle with center $x_{i}$ that pases through $P$. Then $P'$ is the second intersection of the two circles $C_{i}$ and $C_{j}$. Thus our problem of finding a line with minimum difference becomes equivalent to finding the intersection among ${C_{i}}$ that lies closest to $Q$. This last part we can do with a binary search. Consider the problem of checking if two circles $C_{i}$ and $C_{j}$ intersect at a point within a distance $r$ of $Q$. In other words, we wish to check if they intersect inside a circle $S$ of radius $r$ centered at $Q$. Let $A_{i}$ and $A_{j}$ be the arcs of $S$ contained by $C_{i}$ and $C_{j}$, respectively. Observe that $C_{i}$ and $C_{j}$ intersect inside the circle if and only if the two arcs overlap, but do not contain each other. Thus we can verify this condition for all pairs of points with a radial sweep line along the circle. Due to the binary search and the sorting necessary for the sweep line, this solution runs in $O(n\log n\log P)$, where $P$ is the precision required. One might also wonder if precision will be an issue with all the calculations that we're doing. It turns out that it won't be, since our binary search will always stabilize the problem and get us very close to the answer. Here's my original solution using a projective transformation: We begin by binary searching on the the minimum possible difference. Thus we wish to solve the decision problem "Can a difference of $k$ be achieved?" Consider the hyperbola $|PX - QX| = k$. Note that our answer is affirmative if and only if a pair of outposts defines a line that does not intersect the hyperbola. Our next step is a reduction to an equivalent decision problem on a circle through a projective transformation. We express this transformation as the composition of two simpler operations. The first is an affine map that takes the hyperbola $|PX - QX| = k$ to the unit hyperbola. The second maps homogenous coordinates $(x, y, z)$ to $(z, y, x)$. Under the latter, the unit hyperbola $x^{2} - y^{2} = z^{2}$ goes to the unit circle $x^{2} + y^{2} = z^{2}$. Because projective transformations preserve collinearity, a line intersecting the hyperbola is equivalent to a line intersecting the circle. Thus we want to know if any pair of the outposts' images defines a line that does not intersect the circle. We now map the image of each outpost to the minor arc on the unit circle defined by its tangents. (We disregard any points lying inside the circle.) Observe that our condition is equivalent to the existence of two intersecting arcs, neither of which contains the other. Verifying that two such arcs exist can be done with a priority queue and a radial sweep line in $O(n\log n)$. The total complexity of our solution is therefore $O(n\log n\log P)$, where $P$ is the precision that we need. It turns out that the implementation of this algorithm is actually pretty neat:
|
[
"binary search",
"geometry"
] | 3,200
|
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
const ld EPS = 1e-12;
const ld PI = acos(-1);
const int MAXN = 100005;
int N;
ld A, X[MAXN], Y[MAXN];
bool check(ld m){
ld u = m / 2;
ld v = sqrt(A * A - u * u);
vector<pair<ld,ld>> ev;
for(int i = 0; i < N; i++){
ld x = 1, y = Y[i] / v, alpha;
if(X[i] != 0){
x *= u / X[i], y *= u / X[i];
ld r = sqrt(x * x + y * y);
if(r < 1) continue;
alpha = acos(1 / r);
} else {
alpha = PI / 2;
}
ld base = atan2(y, x) - alpha;
if(base < 0) base += 2 * PI;
ev.push_back({base, base + 2 * alpha});
}
priority_queue<ld, vector<ld>, greater<ld>> pq;
sort(ev.begin(), ev.end());
for(int i = 0; i < 2; i++){
for(int j = 0; j < ev.size(); j++){
while(pq.size() && pq.top() < ev[j].first) pq.pop();
if(pq.size() && pq.top() < ev[j].second) return 1;
pq.push(ev[j].second);
ev[j].first += 2 * PI;
ev[j].second += 2 * PI;
}
}
return 0;
}
int main(){
ios::sync_with_stdio(0);
cin >> N >> A;
for(int i = 0; i < N; i++){
cin >> X[i] >> Y[i];
}
ld lo = 0, hi = 2 * A;
while(hi - lo > EPS){
ld mid = (lo + hi) / 2;
(check(mid) ? hi : lo) = mid;
}
cout << fixed << setprecision(10);
cout << (lo + hi) / 2 << 'n';
}
|
650
|
A
|
Watchmen
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are $n$ watchmen on a plane, the $i$-th watchman is located at point $(x_{i}, y_{i})$.
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen $i$ and $j$ to be $|x_{i} - x_{j}| + |y_{i} - y_{j}|$. Daniel, as an ordinary person, calculates the distance using the formula $\sqrt{(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}}$.
The success of the operation relies on the number of pairs $(i, j)$ ($1 ≤ i < j ≤ n$), such that the distance between watchman $i$ and watchmen $j$ calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
When Manhattan distance equals to Euclidean distance? $d_{eu}^{2} = (x_{1} - x_{2})^{2} + (y_{1} - y_{2})^{2}$ $d_{mh}^{2} = (|x_{1} - x_{2}| + |y_{1} - y_{2}|)^{2} = (x_{1} - x_{2})^{2} + 2|x_{1} - x_{2}||y_{1} - y_{2}| + (y_{1} - y_{2})^{2}$ So it is true only when $x_{1} = x_{2}$ or $y_{1} = y_{2}$. This means that to count the number of such pair we need to calculate number of points on each horizontal line and each vertical line. We can do that easily with the use of std::map/TreeMap/HashMap/Dictionary, or just by sorting all coordinates. If we have $k$ points on one horizontal or vertical line they will add $k(k - 1) / 2$ pairs to the result. But if we have several points in one place we will count their pairs twice, so we need to subtract from answer number of pairs of identical points which we can calculate with the same formula and using the same method of finding equal values as before. If we use TreeMap/sort then solution will run in $O(n\log n)$ and if unordered_map/HashMap then in $O(n)$.
|
[
"data structures",
"geometry",
"math"
] | 1,400
| null |
650
|
B
|
Image Preview
|
Vasya's telephone contains $n$ photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo $n$. Similarly, by swiping right from the last photo you reach photo $1$. It takes $a$ seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and \textbf{can't} be rotated. It takes $b$ second to change orientation of the photo.
Vasya has $T$ seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends $1$ second to notice all details in it. If photo is in the wrong orientation, he spends $b$ seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during $T$ seconds.
|
What photos we will see in the end? Some number from the beginning of the gallery and some from the end. There are 4 cases: We always go right. We always go left. We initially go right, then reverse direction, go through all visited photos and continue going left. We initially go left, then reverse direction, go through all visited photos and continue going right. First two cases are straightforward, we can just emulate them. Third and fourth cases can be done with the method of two pointers. Note that if we see one more picture to the right, we spend more time on the right side and the number of photos seen to the left will decrease. This solution will run in $O(n)$. Alternative solution is to fix how many photos we've seen to the right and search how many we can see to the left with binary search. For this method we will need to precompute times of seeing $k$ pictures to the right and to the left. But this is solution is $O(n\log n)$, which is slightly worse then previous one, but maybe it is easier for somebody.
|
[
"binary search",
"brute force",
"dp",
"two pointers"
] | 1,900
| null |
650
|
C
|
Table Compression
|
Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.
Petya decided to compress tables. He is given a table $a$ consisting of $n$ rows and $m$ columns that is filled with positive integers. He wants to build the table $a'$ consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row $i$ of the initial table $a_{i, j} < a_{i, k}$, then in the resulting table $a'_{i, j} < a'_{i, k}$, and if $a_{i, j} = a_{i, k}$ then $a'_{i, j} = a'_{i, k}$. Similarly, if in some column $j$ of the initial table $a_{i, j} < a_{p, j}$ then in compressed table $a'_{i, j} < a'_{p, j}$ and if $a_{i, j} = a_{p, j}$ then $a'_{i, j} = a'_{p, j}$.
Because large values require more space to store them, the maximum value in $a'$ should be as small as possible.
Petya is good in theory, however, he needs your help to implement the algorithm.
|
First we will solve our problem when all values are different. We will construct a graph, where vertices are cells $(i, j)$ and there is an edge between two of them if we know that one is strictly less then the other and this relation should be preserved. This graph obviously has no cycles, so we can calculate answer as dynamic programming on the vertices: We can do this with topological sort or with lazy computations. But if we will construct our graph naively then it will contain $O(nm(n + m))$ edges. To reduce this number we will sort each row and column and add edges only between neighbours in the sorted order. Now we have $O(nm)$ edges and we compute them in $O(n m\log(n m))$ time. But to solve the problem completely in the beginning we need to compress all equal values which are in the same rows and columns. We can construct second graph with edges between equal cells in the same way as before and find all connected components in it. They will be our new vertices for the first graph.
|
[
"dfs and similar",
"dp",
"dsu",
"graphs",
"greedy"
] | 2,200
| null |
650
|
D
|
Zip-line
|
Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them.
It is known that the forest consists of $n$ trees staying in a row numbered from left to right with integers from $1$ to $n$. According to Vasya, the height of the $i$-th tree is equal to $h_{i}$. The zip-line of length $k$ should hang over $k$ ($1 ≤ k ≤ n$) trees $i_{1}, i_{2}, ..., i_{k}$ ($i_{1} < i_{2} < ... < i_{k}$) such that their heights form an increasing sequence, that is $h_{i1} < h_{i2} < ... < h_{ik}$.
Petya had been in this forest together with Vasya, and he now has $q$ assumptions about the mistake in Vasya's sequence $h$. His $i$-th assumption consists of two integers $a_{i}$ and $b_{i}$ indicating that, according to Petya, the height of the tree numbered $a_{i}$ is actually equal to $b_{i}$. Note that Petya's assumptions are \textbf{independent} from each other.
Your task is to find the maximum length of a zip-line that can be built over the trees under each of the $q$ assumptions.
In this problem the length of a zip line is considered equal to the number of trees that form this zip-line.
|
We need to find the longest increasing subsequence (LIS) after each change if all changes are independent. First lets calculate LIS for the initial array and denote its length as $k$. While calculating it we will store some additional information: $len_{l}[i]$ - maximal length of LIS ending on this element. Also we will need $len_{r}[i]$ - maximal length of LIS starting from this element (we can calc it when searching longest decreasing sequence on reversed array). Lets solve the case when we take our new element in the resulting LIS. Then we just calculate $max_{i < a, h[i] < b}(len_{l}[i]) + 1 + max_{j > a, h[j] > b}(len_{r}[j])$. It can be done online with persistent segment tree or offline with scanline with regular segment tree in $O(\log n)$ time. This is the only case when answer can be larger then $k$, and it can be only $k + 1$ to be exact. Second case is when we change our element and ruin all LIS of size $k$. Then answer is $k - 1$. Otherwise we will have at least one not ruined LIS of size $k$ and it is the answer. Lets calculate number of different LIS by some modulo. It can be done with the same dynamic programming with segment tree as just finding LIS. Then we can check if $liscount = liscount_{left}[a] * liscount_{right}[a]$. This exactly means that all sequences go through our element. But if you don't want the solution with such "hashing" there is another approach. For each element we can calc if it can be in LIS. If so then we know on which position it will go ($len_{l}[i]$). Then for each position we will know if there are several elements wanting to go on that position or only one. If only one then it means that all LIS are going through that element. Overall complexity is $O(n\log n)$. P.S. We can solve this without segment tree, just using alternative approach to calculating LIS with dynamic programming and binary search.
|
[
"binary search",
"data structures",
"dp",
"hashing"
] | 2,600
| null |
650
|
E
|
Clockwork Bomb
|
My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.
I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner.
I see $n$ contacts connected by $n - 1$ wires. Contacts are numbered with integers from $1$ to $n$. Bomb has a security mechanism that ensures the following condition: if there exist $k ≥ 2$ contacts $c_{1}, c_{2}, ..., c_{k}$ forming a circuit, i. e. there exist $k$ \textbf{distinct} wires between contacts $c_{1}$ and $c_{2}$, $c_{2}$ and $c_{3}$, $...$, $c_{k}$ and $c_{1}$, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length $2$. It is also prohibited to connect a contact with itself.
On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than $n - 2$ wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear.
I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused.
|
First idea is that answer is always equals to the number of edges from the first tree, which are not in the second one. This means that if we have an edge in both trees we will never touch it. So if we have such edge we can remove this edge and merge its two vertices together, nothing will change. Second idea that if we will take any edge from the first tree there always exists some edge from the second tree, which we can swap (otherwise second graph is not connected, but the tree is always connected). So the order of adding edges from the first tree can be arbitrary. Third idea is that if we will select leaf node in the first tree, then cut its only edge, then we can add instead of it any edge going from this vertex in the second tree. Overall algorithm: we store linked lists of edges in vertices, when edge is in both trees we use disjoint-set union to merge vertices and join their lists. We can simply traverse first tree to get any order of edges in which the current edge will always contain leaf as one of its vertices. Complexity is $O(n \alpha )$, which in practice is almost linear.
|
[
"data structures",
"dfs and similar",
"dsu",
"greedy",
"trees"
] | 3,200
| null |
651
|
A
|
Joysticks
|
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at $a_{1}$ percent and second one is charged at $a_{2}$ percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).
Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.
Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by \textbf{more than $100$ percent}.
|
Main idea is that each second we need to charge the joystick with lowest power level. We can just emulate it or get an $O(1)$ formula, because process is very simple.
|
[
"dp",
"greedy",
"implementation",
"math"
] | 1,100
| null |
651
|
B
|
Beautiful Paintings
|
There are $n$ pictures delivered for the new exhibition. The $i$-th painting has beauty $a_{i}$. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of $a$ in any order. What is the maximum possible number of indices $i$ ($1 ≤ i ≤ n - 1$), such that $a_{i + 1} > a_{i}$.
|
Lets look at the optimal answer. It will contain several segment of increasing beauty and between them there will be drops in the beautifulness. Solution is greedy. Lets sort all paintings and lets select which of them will be in the first increasing segment. We just go from left to right and select only one painting from each group of several paintings with the fixed beauty value. We continue this operation while there is at least one painting left. With the careful implementation we will get $O(n\log n)$ solution. But this solution gives us the whole sequence, but the problem was a little bit easier - to determine number of such segments. From the way we construct answer it is easy to see that the number of segments always equal to the maximal number of copies of one value. Obviously we can't get less segments than that and our algorithm gives us exactly this number. This solution is $O(n)$.
|
[
"greedy",
"sortings"
] | 1,200
| null |
652
|
A
|
Gabriel and Caterpillar
|
The $9$-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height $h_{1}$ cm from the ground. On the height $h_{2}$ cm ($h_{2} > h_{1}$) on the same tree hung an apple and the caterpillar was crawling to the apple.
Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by $a$ cm per hour by day and slips down by $b$ cm per hour by night.
In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at $10$ am and finishes at $10$ pm. Gabriel's classes finish at $2$ pm. You can consider that Gabriel noticed the caterpillar just after the classes at $2$ pm.
Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple.
|
Let's consider three cases. $h_{1} + 8a \ge h_{2}$ - in this case the caterpillar will get the apple on the same day, so the answer is $0$. The first condition is false and $a \le b$ - in this case the caterpillar will never get the apple, because it can't do that on the first day and after each night it will be lower than one day before. If the first two conditions are false easy to see that the answer equals to $\left[{\frac{h_{2}-h_{1}-8a}{12(a-b)}}\right]$. Also this problem can be solved by simple modelling, because the heights and speeds are small. Complexity: $O(1)$.
|
[
"implementation",
"math"
] | 1,400
|
int h1, h2;
int a, b;
bool read() {
return !!(cin >> h1 >> h2 >> a >> b);
}
void solve() {
if (h1 + 8 * a >= h2)
puts("0");
else if (a > b) {
int num = h2 - h1 - 8 * a, den = 12 * (a - b);
cout << (num + den - 1) / den << endl;
} else
puts("-1");
}
|
652
|
B
|
z-sort
|
A student of $z$-school found a kind of sorting called $z$-sort. The array $a$ with $n$ elements are $z$-sorted if two conditions hold:
- $a_{i} ≥ a_{i - 1}$ for all even $i$,
- $a_{i} ≤ a_{i - 1}$ for all odd $i > 1$.
For example the arrays [1,2,1,2] and [1,1,1,1] are $z$-sorted while the array [1,2,3,4] isn’t $z$-sorted.
Can you make the array $z$-sorted?
|
Easy to see that we can $z$-sort any array $a$. Let $k=\lfloor{\frac{n}{2}}\rfloor$ be the number of even positions in $a$. We can assign to those positions $k$ maximal elements and distribute other $n - k$ elements to odd positions. Obviously the resulting array is $z$-sorted. Complexity: $O(nlogn)$.
|
[
"sortings"
] | 1,000
|
const int N = 1010;
int n, a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
int ans[N];
void solve() {
sort(a, a + n);
int p = 0, q = n - 1;
forn(i, n)
if (i & 1) ans[i] = a[q--];
else ans[i] = a[p++];
assert(q + 1 == p);
forn(i, n) {
if (i) putchar(' ');
printf("%d", ans[i]);
}
puts("");
}
|
652
|
C
|
Foe Pairs
|
You are given a permutation $p$ of length $n$. Also you are given $m$ foe pairs $(a_{i}, b_{i})$ ($1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}$).
Your task is to count the number of different intervals $(x, y)$ ($1 ≤ x ≤ y ≤ n$) that do not contain any foe pairs. So you shouldn't count intervals $(x, y)$ that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).
Consider some example: $p = [1, 3, 2, 4]$ and foe pairs are ${(3, 2), (4, 2)}$. The interval $(1, 3)$ is incorrect because it contains a foe pair $(3, 2)$. The interval $(1, 4)$ is also incorrect because it contains two foe pairs $(3, 2)$ and $(4, 2)$. But the interval $(1, 2)$ is correct because it doesn't contain any foe pair.
|
Let's precompute for each value $x$ its position in permutation $pos_{x}$. It's easy to do in linear time. Consider some foe pair $(a, b)$ (we may assume $pos_{a} < pos_{b}$). Let's store for each value $a$ the leftmost position $pos_{b}$ such that $(a, b)$ is a foe pair. Denote that value as $z_{a}$. Now let's iterate over the array $a$ from right to left and maintain the position $rg$ of the maximal correct interval with the left end in the current position $lf$. To maintain the value $rg$ we should simply take the minimum with the value $z[lf]$: $rg = min(rg, z[lf])$. And finally we should increment the answer by the value $rg - lf + 1$. Complexity: $O(n + m)$.
|
[
"combinatorics",
"sortings",
"two pointers"
] | 1,800
|
const int N = 300300;
int n, m;
int p[N];
pt b[N];
bool read() {
if (!(cin >> n >> m)) return false;
forn(i, n) {
assert(scanf("%d", &p[i]) == 1);
p[i]--;
}
forn(i, m) {
int x, y;
assert(scanf("%d%d", &x, &y) == 2);
x--, y--;
b[i] = pt(x, y);
}
return true;
}
int pos[N];
vector<int> z[N];
void solve() {
forn(i, n) pos[p[i]] = i;
forn(i, n) z[i].clear();
forn(i, m) {
int x = pos[b[i].x], y = pos[b[i].y];
if (x > y) swap(x, y);
z[x].pb(y);
}
li ans = 0;
int rg = n;
nfor(i, n) {
forn(j, sz(z[i])) rg = min(rg, z[i][j]);
ans += rg - i;
}
cout << ans << endl;
}
|
652
|
D
|
Nested Segments
|
You are given $n$ segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
|
This problem is a standard two-dimensional problem that can be solved with one-dimensional data structure. In the same way a lot of other problems can be solved (for example the of finding the maximal weighted chain of points so that both coordinates of each point are greater than the coordinates of the predecessing point). Rewrite the problem formally: for each $i$ we should count the number of indices $j$ so that the following conditions are hold: $a_{i} < a_{j}$ and $b_{j} < a_{j}$. Let's sort all segments by the left ends from right to left and maintain some data structure (Fenwick tree will be the best choice) with the right ends of the processed segments. To calculate the answer for the current segment we should simple take the prefix sum for the right end of the current segment. So the condition $a_{i} < a_{j}$ is hold by sorting and iterating over the segments from the right to the left (the first dimension of the problem). The condition $b_{j} < a_{j}$ is hold by taking the prefix sum in data structure (the second dimension). Complexity: $O(nlogn)$.
|
[
"data structures",
"sortings"
] | 1,800
|
const int N = 1200300;
int n;
pair<pti, int> a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d%d", &a[i].x.x, &a[i].x.y) == 2), a[i].y = i;
return true;
}
int t[N];
vector<int> ys;
inline void inc(int i, int val) {
for ( ; i < sz(ys); i |= i + 1)
t[i] += val;
}
inline int sum(int i) {
int ans = 0;
for ( ; i >= 0; i = (i & (i + 1)) - 1)
ans += t[i];
return ans;
}
int ans[N];
void solve() {
ys.clear();
forn(i, n) ys.pb(a[i].x.y);
sort(all(ys));
ys.erase(unique(all(ys)), ys.end());
forn(i, sz(ys)) t[i] = 0;
sort(a, a + n);
nfor(i, n) {
int idx = int(lower_bound(all(ys), a[i].x.y) - ys.begin());
ans[a[i].y] = sum(idx);
inc(idx, +1);
}
forn(i, n) printf("%dn", ans[i]);
}
|
652
|
E
|
Pursuit For Artifacts
|
Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience.
In that country there are $n$ islands and $m$ bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful artifacts. Johnny is not interested in artifacts, but he can get some money by selling some artifact.
At the start Johnny is in the island $a$ and the artifact-dealer is in the island $b$ (possibly they are on the same island). Johnny wants to find some artifact, come to the dealer and sell it. The only difficulty is that bridges are too old and destroying right after passing over them. Johnnie's character can't swim, fly and teleport, so the problem became too difficult.
Note that Johnny can't pass the half of the bridge, collect the artifact and return to the same island.
Determine if Johnny can find some artifact and sell it.
|
Edge biconnected component in an undirected graph is a maximal by inclusion set of vertices so that there are two edge disjoint paths between any pair of vertices. Consider the graph with biconnected components as vertices. Easy to see that it's a tree (if it contains some cycle then the whole cycle is a biconnected component). All edges are destroying when we passing over them so we can't returnto the same vertex (in the tree) after leaving it by some edge. Consider the biconncted components that contains the vertices $a$ and $b$. Let's denote them $A$ and $B$. Statement: the answer is YES if and only if on the path in the tree from the vertex $A$ to the vertex $B$ there are an edge with an artifact or there are a biconnected component that contains some edge with an artifact. Easy to see that the statement is true: if there are such edge then we can pass over it in the tree on the path from $A$ to $B$ or we can pass over it in biconnected component. The converse also easy to check. Here is one of the ways to find edge biconnected components: Let's orient all edges to direction that depth first search passed it for the first time. Let's find in new directed graph strongly connected components. Statement: the strongly connected components in the new graph coincide with the biconnected components in old undirected graph. Also you can notice that the edges in tree is the bridges of the graph (bridges in terms of graph theory). So you can simply find the edges in the graph. const int N = 500500, M = 500500; int n, m; int eused[M]; vector eid[N]; vector g1[N], tg1[N]; vector w[N]; int a, b; bool read() { if (!(cin >> n >> m)) return false; forn(i, m) eused[i] = false; forn(i, n) { g1[i].clear(); tg1[i].clear(); eid[i].clear(); w[i].clear(); } forn(i, m) { int x, y, z; assert(scanf("%d%d%d", &x, &y, &z) == 3); x--, y--; g1[x].pb(y); g1[y].pb(x); eid[x].pb(i); eid[y].pb(i); w[x].pb(z); w[y].pb(z); } assert(cin >> a >> b); a--, b--; return true; } int u, used[N]; int sz, perm[N]; void dfs1(int v) { used[v] = u; forn(i, sz(g1[v])) { int u = g1[v][i]; int cid = eid[v][i]; if (!eused[cid]) { eused[cid] = true; tg1[u].pb(v); } if (used[u] != ::u) dfs1(u); } perm[sz++] = v; } int c, comp[N]; void dfs2(int v) { used[v] = u; for (auto u : tg1[v]) if (used[u] != ::u) dfs2(u); comp[v] = c; } vector g2[N]; vector w2[N]; bool good[N]; bool dfs3(int v, int p, int t, bool& ans) { if (v == t) { ans |= good[v]; return true; } } void solve() { u++, sz = 0; dfs1(0); assert(sz == n); reverse(perm, perm + sz); } Complexity: $O(n + m)$.
|
[
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,300
|
u++, c = 0;
forn(i, sz) if (used[perm[i]] != u) dfs2(perm[i]), c++;
forn(i, c) good[i] = false;
forn(i, c) {
g2[i].clear();
w2[i].clear();
}
forn(i, n)
forn(j, sz(g1[i])) {
int x = comp[i], y = comp[g1[i][j]];
if (x != y) {
g2[x].pb(y);
w2[x].pb(w[i][j]);
} else if (w[i][j]) good[x] = true;
}
n = c;
a = comp[a], b = comp[b];
bool ans = good[a];
assert(dfs3(a, -1, b, ans));
puts(ans ? "YES" : "NO");
|
652
|
F
|
Ants on a Circle
|
$n$ ants are on a circle of length $m$. An ant travels one unit of distance per one unit of time. Initially, the ant number $i$ is located at the position $s_{i}$ and is facing in the direction $d_{i}$ (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are distinct.
All the ants move simultaneously, and whenever two ants touch, they will both switch their directions. Note that it is possible for an ant to move in some direction for a half of a unit of time and in opposite direction for another half of a unit of time.
Print the positions of the ants after $t$ time units.
|
The first observation: if all the ants are indistinguishable we can consider that there are no collisions and all the ants are passing one through another. So we can easily determine the final positions of all the ants, but we can't say which ant will be in which position. The second observation: the relative order of the ants will be the same all the time. So to solve the problem we should only find the position of one ant after $t$ seconds. Let's solve that problem in the following way: Consider the positions of all the ants after $m$ time units. Easy to see that by the first observation all the positions of the ants will left the same, but the order will be different (we will have some cyclic shift of the ants). If we find that cyclic shift $sh$ we can apply it $\lfloor{\frac{t}{m}}\rfloor$ times. After that we will have only $t \pm od m$ time units. So the problem now is to model the process for the one ant with $m$ and $r \pm od m$ time units. Note that in that time interval the fixed ant will have no more than two collisions with each other ant. So if we model the process with ignoring all collisions except the ones that include the fixed ant, we will have no more than $2n$ collisions. Let's model that process with two queues for the ants going to the left and to the right. Each time we should take the first ant in the queue with opposite direction, process the collision and add that ant to the end of the other queue. Hint: you will have a problem when the fixed ant can be in two different positions at the end, but it's easy to fix with doing the same with the next ant. const int N = 300300; int n, m; li t; pair<pair<int, char>, int> a[N]; bool read() { if (!(cin >> n >> m >> t)) return false; forn(i, n) { assert(scanf("%d %c", &a[i].x.x, &a[i].x.y) == 2); a[i].x.x--; a[i].y = i; } return true; } int dx[] = { -1, +1 }; const string dirs("LR"); inline int getDir(char d) { return (int) dirs.find(d); } inline int getPos(li x, char d, li t) { x %= m, t %= m; li ans = (x + t * dx[getDir(d)]) % m; (ans < 0) && (ans += m); return int(ans); } typedef pair<li, li> ptl; void clear(queue& q) { while (!q.empty()) q.pop(); } queue tol, tor; int calc(int v, li t) { clear(tol); clear(tor); } int ans[N]; void solve() { assert(n > 1); sort(a, a + n); } Complexity: $O(nlogn)$.
|
[
"constructive algorithms",
"math"
] | 2,800
|
vector<int> poss;
forn(i, n)
poss.pb(getPos(a[i].x.x, a[i].x.y, t));
sort(all(poss));
vector<vector<int>> xs;
forn(s, 2) {
int x = calc(s, m);
int pos = -1;
forn(i, n)
if (a[i].x.x == x) {
assert(pos == -1);
pos = i;
}
assert(pos != -1);
pos = (pos - s + n) % n;
li k = (t / m) % n;
pos = int((s + pos * k) % n);
x = calc(pos, t % m);
xs.pb(vector<int>());
forn(i, sz(poss))
if (poss[i] == x)
xs.back().pb(i);
assert(!xs.back().empty());
if (sz(xs.back()) == 2) assert(xs.back()[0] + 1 == xs.back()[1]);
}
int pos = xs[0][0];
if (sz(xs[0]) > 1) {
assert(sz(xs[0]) == 2);
assert(pos + 1 == xs[0][1]);
if (xs[0] != xs[1])
pos = xs[0][1];
}
forn(ii, n) {
int i = (ii + pos) % sz(poss);
ans[a[ii].y] = poss[i];
}
forn(i, n) {
if (i) putchar(' ');
assert(0 <= ans[i] && ans[i] < m);
printf("%d", ans[i] + 1);
}
puts("");
|
653
|
A
|
Bear and Three Balls
|
Limak is a little polar bear. He has $n$ balls, the $i$-th ball has size $t_{i}$.
Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:
- No two friends can get balls of the same size.
- No two friends can get balls of sizes that differ by more than $2$.
For example, Limak can choose balls with sizes $4$, $5$ and $3$, or balls with sizes $90$, $91$ and $92$. But he can't choose balls with sizes $5$, $5$ and $6$ (two friends would get balls of the same size), and he can't choose balls with sizes $30$, $31$ and $33$ (because sizes $30$ and $33$ differ by more than $2$).
Your task is to check whether Limak can choose three balls that satisfy conditions above.
|
watch out for test like "1 1 1 2 2 2 2 3 3 3". It shows that it's not enough to sort number and check three neighbouring elements. You must remove repetitions. The easier solution is to write 3 for-loops, without any sorting. Do you see how?
|
[
"brute force",
"implementation",
"sortings"
] | 900
| null |
653
|
B
|
Bear and Compressing
|
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of $q$ possible operations. Limak can perform them in any order, any operation may be applied any number of times. The $i$-th operation is described by a string $a_{i}$ of length two and a string $b_{i}$ of length one. No two of $q$ possible operations have the same string $a_{i}$.
When Limak has a string $s$ he can perform the $i$-th operation on $s$ if the first two letters of $s$ match a two-letter string $a_{i}$. Performing the $i$-th operation removes first two letters of $s$ and inserts there a string $b_{i}$. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string $s$ exactly by $1$. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any $a_{i}$.
Limak wants to start with a string of length $n$ and perform $n - 1$ operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
|
you should generate all $6^{n}$ possible starting strings and for each of them check whether you will get "a" at the end. Remember that you should check two first letters, not last ones (there were many questions about it).
|
[
"brute force",
"dfs and similar",
"dp",
"strings"
] | 1,300
| null |
653
|
C
|
Bear and Up-Down
|
The life goes up and down, just like nice sequences. Sequence $t_{1}, t_{2}, ..., t_{n}$ is called nice if the following two conditions are satisfied:
- $t_{i} < t_{i + 1}$ for each odd $i < n$;
- $t_{i} > t_{i + 1}$ for each even $i < n$.
For example, sequences $(2, 8)$, $(1, 5, 1)$ and $(2, 5, 1, 100, 99, 120)$ are nice, while $(1, 1)$, $(1, 2, 3)$ and $(2, 5, 3, 2)$ are not.
Bear Limak has a sequence of positive integers $t_{1}, t_{2}, ..., t_{n}$. This sequence \textbf{is not nice} now and Limak wants to fix it by a single swap. He is going to choose two indices $i < j$ and swap elements $t_{i}$ and $t_{j}$ in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
|
Let's call an index $i$ bad if the given condition about $t_{i}$ and $t_{i + 1}$ doesn't hold true. We are given a sequence that has at least one bad place and we should count ways to swap two elements to fix all bad places (and not create new bad places). The shortest (so, maybe easiest) solution doesn't use this fact but one can notice that for more than $4$ bad places the answer is $0$ because swapping $t_{i}$ and $t_{j}$ can affect only indices $i - 1, i, j - 1, j$. With one iteration over the given sequence we can find and count all bad places. Let $x$ denote index of the first bad place (or index of some other bad place, it's not important). We must swap $t_{x}$ or $t_{x - 1}$ with something because otherwise $x$ would still be bad. Thus, it's enough to consider $O(n)$ swaps ~-- for $t_{x}$ and for $t_{x - 1}$ iterate over index of the second element to swap (note that "the second element" doesn't have to be bad and samples show it). For each of $O(n)$ swaps we can do the following (let $i$ and $j$ denote chosen two indices): Count bad places among four indices: $i - 1, i, j - 1, j$. If it turns out that these all not all initial bad places then we don't have to consider this swap - because some bad place will still exist anyway. Swap $t_{i}$ and $t_{j}$. Check if there is some bad place among four indices: $i - 1, i, j - 1, j$. If not then we found a correct way. Swap $t_{i}$ and $t_{j}$ again, to get an initial sequence. Be careful not to count the same pair of indices twice. In the solution above it's possible to count twice a pair of indices $(x - 1, x)$ (where $x$ was defined in the paragraph above). So, add some if or do it more brutally - create a set of pairs and store sorted pairs of indices there.
|
[
"brute force",
"implementation"
] | 1,900
| null |
653
|
D
|
Delivery Bears
|
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with $n$ nodes and $m$ edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node $1$ to node $n$. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has \textbf{exactly} $x$ bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
|
Let's transform this into a flow problem. Here, we transform "weight" into "flow", and each "bear" becomes a "path". Suppose we just want to find the answer for a single $x$. We can do this binary search on the flow for each path. To check if a particular flow of $F$ is possible, reduce the capacity of each edge from $c_{i}$ to $[c_{i}/F]$. Then, check if the max flow in this graph is at least $x$. The final answer is then $x$ multiplied by the flow value that we found.
|
[
"binary search",
"flows",
"graphs"
] | 2,200
|
//#pragma comment(linker, "/STACK:16777216")
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <assert.h>
#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define norm asdfasdgasdgsd
#define eps 1e-7
#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 512
const int N = 200500;
using namespace std;
struct edge
{
int a, b, cap, flow;
};
int n, s, t, d[N], ptr[N];
vector<edge> e;
vector<int> g[N];
void add_edge(int a, int b, int cap)
{
edge e1 = { a, b, cap, 0 };
edge e2 = { b, a, 0, 0 };
g[a].push_back(e.size());
e.push_back(e1);
g[b].push_back(e.size());
e.push_back(e2);
}
bool bfs()
{
for (int i = 0; i < n; i++)
{
d[i] = -1;
}
d[s] = 0;
queue<int> qu;
qu.push(s);
while (qu.size())
{
int v = qu.front();
qu.pop();
for (int i = 0; i < g[v].size(); i++)
{
int id = g[v][i];
int to = e[id].b;
if (d[to] == -1 && e[id].flow < e[id].cap)
{
d[to] = d[v] + 1;
qu.push(to);
}
}
}
return d[t] != -1;
}
int dfs(int v, int flow)
{
if (v == t || flow == 0)
return flow;
for (; ptr[v] < g[v].size(); ptr[v]++)
{
int id = g[v][ptr[v]];
int to = e[id].b;
if (d[to] != d[v] + 1)
continue;
int pushed = dfs(to, min(flow, e[id].cap - e[id].flow));
if (pushed)
{
e[id].flow += pushed;
e[id ^ 1].flow -= pushed;
return pushed;
}
}
return 0;
}
int dinic()
{
int flow = 0;
while (true)
{
if (!bfs())
break;
for (int i = 0; i < n; i++)
{
ptr[i] = 0;
}
while (true)
{
int pushed = dfs(s, 10000);
if (!pushed)
break;
flow += pushed;
}
}
return flow;
}
int m, x, k;
vector<pair<pair<int, int>, int> > E;
void construct_graph(double val)
{
e.clear();
for (int i = 0; i < n; i++)
g[i].clear();
for (int i = 0; i < E.size(); i++)
{
//cout << E[i].second << " " << val << endl;
long double d_here = E[i].second*1.0 / val+eps;
if (d_here>1e9)
d_here = 1e6;
int here = d_here;
add_edge(E[i].first.first, E[i].first.second, here);
}
}
void update_graph(double val)
{
for (int i = 0; i < E.size(); i++)
{
double d_here = E[i].second*1.0 / val+eps;
if (d_here>1e9)
d_here = 1e6;
int here = d_here;
int rem = here - e[i * 2].cap;
e[i * 2].cap += rem;
//cout << rem << " " << val << " " << e[i * 2].cap << " "<<e[i*2].flow<<endl;
}
}
double get_next(double val)
{
double res = 0;
for (int i = 0; i < E.size(); i++)
{
double d_here = E[i].second*1.0 / val+eps;
if (d_here>1e9)
d_here = 1e6;
int here = d_here;
double thold = (E[i].second*1.0 / (here + 1));
res = max(res, thold);
}
return res;
}
vector<pair<int, double> > G[N];
double D[N];
//set<pair<double, int> > S;
//set<pair<double, int> > ::iterator it;
priority_queue<pair<double, int> > S,emp;
double smart_next(double val)
{
for (int i = 0; i < n; i++)
{
G[i].clear();
D[i] = 0;
}
for (int i = 0; i < E.size(); i++)
{
//cout << e[i*2].a<<" "<<e[i*2].b<<" "<<e[i * 2].cap << " " << e[i * 2].flow << endl;
double T = E[i].second*1.0 / (e[i * 2].cap + 1);
if (e[i * 2].flow < e[i * 2].cap)
G[E[i].first.first].push_back(make_pair(E[i].first.second, val));
else
G[E[i].first.first].push_back(make_pair(E[i].first.second, T));
if (e[i * 2 + 1].flow < e[i * 2+1].cap)
{
G[E[i].first.second].push_back(make_pair(E[i].first.first, val));
}
else
G[E[i].first.second].push_back(make_pair(E[i].first.first, T));
}
S = emp;
D[0] = val;
for (int i = 0; i < n; i++)
S.push(make_pair(D[i], i));
while (S.size())
{
pair<double, int> p = S.top();
S.pop();
if (D[p.second]>p.first + eps)
continue;
int cur = p.second;
if (cur == n - 1)
break;
//cout << cur << " " << p.first <<" "<<S.size()<< endl;
for (int i = 0; i < G[cur].size(); i++)
{
int to = G[cur][i].first;
double cost = min(G[cur][i].second, D[cur]);
if (D[to]<cost-eps)
{
//S.erase(make_pair(D[to], to));
D[to] = cost;
S.push(make_pair(D[to], to));
}
}
}
return D[n - 1];
}
double solve_naive(int need)
{
long double l, r;
l = 1e-6;
r = 1e6;
for (int iter = 1; iter <= 70; iter++)
{
double mid = l + r;
mid /= 2;
construct_graph(mid);
int here = dinic();
if (here >= need)
l = mid;
else
r = mid;
}
return l;
}
int main(){
//freopen("route.in","r",stdin);
//freopen("route.out","w",stdout);
//freopen("F:/in.txt", "r", stdin);
//freopen("F:/output.txt", "w", stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);
cin >> n >> m >> x;
k = 1;
s = 0;
t = n - 1;
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
--a;
--b;
E.push_back(make_pair(make_pair(a, b), c));
}
cout.precision(7);
long double cur_val = solve_naive(x);
construct_graph(cur_val - eps);
int cur_flow = dinic();
for (int i = x; i < x + k; i++)
{
//cout << i << "@" << cur_flow << endl;
while (cur_flow < i)
{
double next_cand = smart_next(cur_val);
update_graph(next_cand);
//cout << next_cand << endl;
//cin.get();
bfs();
for (int j = 0; j < n; j++)
ptr[j] = 0;
while (true)
{
int pushed = dfs(s, 1000000);
if (pushed == 0)
break;
cur_flow += pushed;
}
// cout << pushed << endl;
// cin.get();
cur_val = next_cand;
}
cout << fixed << cur_val*i << "\n";
}
/*
for (int i = x; i < x + k; i++)
{
cout << fixed << solve_naive(i)*i << endl;
}*/
cin.get(); cin.get();
return 0;
}
|
653
|
E
|
Bear and Forgotten Tree 2
|
A tree is a connected undirected graph consisting of $n$ vertices and $n - 1$ edges. Vertices are numbered $1$ through $n$.
Limak is a little polar bear. He once had a tree with $n$ vertices but he lost it. He still remembers something about the lost tree though.
You are given $m$ pairs of vertices $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{m}, b_{m})$. Limak remembers that for each $i$ there was \textbf{no edge} between $a_{i}$ and $b_{i}$. He also remembers that vertex $1$ was incident to exactly $k$ edges (its degree was equal to $k$).
Is it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions.
|
You are given a big graph with some edges forbidden, and the required degree of vertex 1. We should check whether there exists a spanning tree. Let's first forget about the condition about the degree of vertex 1. The known fact: a spanning tree exists if and only if the graph is connected (spend some time on this fact if it's not obvious for you). So, let's check if the given graph is connected. We will do it with DFS. We can't run standard DFS because there are maybe $O(n^{2})$ edges (note that the input contains forbidden edges, and there may be many more allowed edges then). We should modify it by adding a set or list of unvisited vertices $s$. When we are at vertex $a$ we can't check all edges adjacent to $a$ and instead let's iterate over possible candidates for adjacent unvisited vertices (iterate over $s$). For each $b$ in $s$ we should check whether $a$ and $b$ are connected by a forbidden edge (you can store input edges in a set of pairs or in a similar structure). If they are connected by a forbidden edge then nothing happens (but for each input edge it can happen only twice, for each end of edge, thus $O(m)$ in total), and otherwise we get a new vertex. The complexity is $O((n+m)\cdot\log m)$ where $\log\gamma$ is from using set of forbidden edges. Now we will check for what degree of vertex 1 we can build a tree. We again consider a graph with $n$ vertices and $m$ forbidden edges. We will first find out what is the minimum possible degree of vertex 1 in some spanning tree. After removing vertex 1 we would get some connected components and in the initial graph they could be connected to each other only with edges to vertex 1. With the described DFS we can find $c$ ($1 \le c \le n - 1$) - the number of created connected components. Vertex 1 must be adjacent to at least one vertex in each of $c$ components. And it would be enough to get some tree because in each component there is some spanning tree - together with edges to vertex 1 they give us one big spanning tree with $n$ vertices (we assume that the initial graph is connected). And the maximum degree of vertex 1 is equal to the number of allowed edges adjacent to this vertex. It's because more and more edges from vertex 1 can only help us (think why). It will be still possible to add some edges in $c$ components to get one big spanning tree. So, what is the algorithm? Run the described DFS to check if the graph is connected (if not then print "NO"). Remove vertex 1 and count connected components (e.g. starting DFS's from former neighbours of vertex 1). Also, simply count $d$ - the number of allowed edges adjacent to vertex 1. If the required degree $k$ is between $c$ and $d$ inclusive then print "YES", and otherwise print "NO".
|
[
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
set<pair<int,int>> forbidden;
bool is_ok(int a, int b) {
if(a > b) swap(a, b);
return forbidden.find(make_pair(a, b)) == forbidden.end();
}
set<int> remaining;
void dfs(int a) {
vector<int> memo;
for(int b : remaining) if(is_ok(a, b))
memo.push_back(b);
for(int b : memo)
remaining.erase(b);
for(int b : memo) dfs(b);
}
void NO() {
puts("impossible");
exit(0);
}
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for(int i = 2; i <= n; ++i) remaining.insert(i);
int allowed_degree = n - 1; // maximum possible degree of vertex 1
for(int i = 0; i < m; ++i) {
int a, b;
scanf("%d%d", &a, &b);
if(a > b) swap(a, b);
if(a == 1) --allowed_degree;
forbidden.insert(make_pair(a, b));
}
if(allowed_degree < k) NO(); // not enough allowed edges from 1
int components = 0; // connected components
for(int i = 2; i <= n; ++i) if(is_ok(1, i) && remaining.find(i)!=remaining.end()) {
dfs(i);
++components;
}
if(!remaining.empty()) NO(); // the graph isn't connected
if(components > k) NO(); // we need more than k edges from 1
puts("possible");
return 0;
}
|
653
|
F
|
Paper task
|
Alex was programming while Valentina (his toddler daughter) got there and started asking many questions about the round brackets (or parenthesis) in the code. He explained her a bit and when she got it he gave her a task in order to finish his code on time.
For the purpose of this problem we consider only strings consisting of opening and closing round brackets, that is characters '(' and ')'.
The sequence of brackets is called correct if:
- it's empty;
- it's a correct sequence of brackets, enclosed in a pair of opening and closing brackets;
- it's a concatenation of two correct sequences of brackets.
For example, the sequences "()()" and "((()))(())" are correct, while ")(()", "(((((" and "())" are not.
Alex took a piece of paper, wrote a string $s$ consisting of brackets and asked Valentina to count the number of \textbf{distinct} non-empty substrings of $s$ that are correct sequences of brackets. In other words, her task is to count the number of non-empty correct sequences of brackets that occur in a string $s$ as a \textbf{substring} (don't mix up with subsequences).
When Valentina finished the task, Alex noticed he doesn't know the answer. Help him don't loose face in front of Valentina and solve the problem!
|
There are two solutions. The first and more common solution required understanding how do SA (suffix array) and LCP (longest common prefix) work. The second processed the input string first and then run SA+LCP like a blackbox, without modifying or caring about those algorithms. Modify-SA-solution - The main idea is to modify the algorithm for computing the number of distinct substrings using SA + LCP. Let $query(L, R)$ denote the number of well formed prefixes of $substring(L, R)$. For example, for $substring(L, R) = "(())()("$ we would have $query(L, R) = 2$ because we count $(())$ oraz $(())()$. How to be able to get $query(L, R)$ fast? You can treat the opening bracket as $+ 1$ and the ending bracket as $- 1$. Then you are interested in the number of intervals starting in $L$, ending not after $R$, with sum on the interval equal to zero. Additionally, the sum from $L$ to any earlier right end can't be less than zero. Maybe you will need some preprocessing here, maybe binary search, maybe segment trees. It's an exercise for you. We can iterate over suffix array values and for each suffix we add $query(suffix, N) - query(suffix, suffix + LCP[suffix] - 1)$ to the answer. In other words we count the number of well formed substrings in the current suffix and subtract the ones we counted in the previous step. The complexity is $O(n\log n)$ but you could get AC with very fast solution with extra $\log\beta$. Compressing-solution - I will slowly compress the input string, changing small well-formed substrings to some new characters (in my code they are represented by integer numbers, not by letters). Let's take a look at the example: $|((\cdot)\rangle(|\rightarrow\ )(a\rangle(\cdot)\rightarrow\rangle b(\cdot)(\cdot)\rightarrow\jmath a(\cdot)\rightarrow\jmath a a\rightarrow\jmath c a\rightarrow\jmath d$ or equivalently: $\,((\cdot\!\cdot)(\,)(\,)(\,)\rightarrow\ )(a)a a\rightarrow\ )b a a\rightarrow\ )b a a\rightarrow\ ]c a\rightarrow\ d$ Whenever I have a maximum (not possible to expand) substring with single letters only, without any brackets, then I add this substring to some global list of strings. At the end I will count distinct substrings in the found list of strings (using SA+LCP). In the example above I would first add a string "a" and later I would add "baa". Note that each letter represents some well formed substring, e.g. 'b' represents $(())$ here. I must make sure that the same substrings will be compressed to the same letters. To do it, I always move from left to right, and I use trie with map (two know what to get from some two letters).
|
[
"data structures",
"string suffix structures",
"strings"
] | 2,600
|
// Suffix Array from http://apps.topcoder.com/forums/?module=Thread&threadID=627379&start=0&mc=39#1038914
#include <bits/stdc++.h>
using namespace std;
const int nax = 3e6 + 5, inf = 1e9 + 5;
int H, str[nax], Bucket[nax], nBucket[nax]; // needed for Suffix Array
struct Suffix {
int idx; // Suffix starts at idx, i.e. it's str[ idx .. L-1 ]
bool operator<(const Suffix& sfx) const
// Compares two suffixes based on their first 2H symbols,
// assuming we know the result for H symbols.
{
if(H == 0) return str[idx] < str[sfx.idx];
else if(Bucket[idx] == Bucket[sfx.idx])
return (Bucket[idx+H] < Bucket[sfx.idx+H]);
else
return (Bucket[idx] < Bucket[sfx.idx]);
}
bool operator==(const Suffix& sfx) const
{
return !(*this < sfx) && !(sfx < *this);
}
} Pos[nax];
int UpdateBuckets(int L) {
int start = 0, id = 0, c = 0;
for(int i = 0; i < L; i++)
{
/*
If Pos[i] is not equal to Pos[i-1], a new bucket has started.
*/
if(i != 0 && !(Pos[i] == Pos[i-1]))
{
start = i;
id++;
}
if(i != start) // if there is bucket with size larger than 1, we should continue ...
c = 1;
nBucket[Pos[i].idx] = id; // Bucket for suffix starting at Pos[i].idx is id ...
}
memcpy(Bucket, nBucket, 4 * L);
return c;
}
void SuffixSort(int L) {
for(int i = 0; i < L; i++) Pos[i].idx = i;
// H == 0, Sort based on first Character.
sort(Pos, Pos + L);
// Create initial buckets
int c = UpdateBuckets(L);
for(H=1;c;H *= 2) {
// Sort based on first 2*H symbols, assuming that we have sorted based on first H character
sort(Pos, Pos+L);
// Update Buckets based on first 2*H symbols
c = UpdateBuckets(L);
}
}
int sa[nax], inv_sa[nax]; // needed for calculating LCP
long long count_substrings(vector<int> input) {
long long answer = 0;
for(int i = 0; i < (int) input.size(); ++i) str[i] = input[i];
int n = input.size();
SuffixSort(n + 1);
// calculate LCP
for(int i = 0; i < n; ++i) {
answer += n - Pos[i+1].idx;
sa[i] = Pos[i+1].idx;
inv_sa[sa[i]] = i;
}
int lcp = 0;
for(int i = 0; i < n; ++i) {
int k = inv_sa[i];
if(k == 0) continue;
int j = sa[k-1];
while(str[i+lcp] == str[j+lcp]) ++lcp;
answer -= lcp;
if(lcp > 0) --lcp;
}
return answer;
}
map<int,int> m[nax];
int getHash(int a, int b) {
if(m[a].count(b)) return m[a][b];
static int T = 2;
return m[a][b] = T++;
}
vector<int> global;
void consider(string ss) { // gets one valid gragment, e.g. ()(())()()
assert(!ss.empty());
// cout << ss << " ";
ss = '(' + ss + ')';
// cout << ss << "\n";
int n = ss.length();
vector<vector<int>> stack;
for(int i = 0; i < n; ++i) {
if(ss[i] == '(') stack.push_back(vector<int>{1});
else {
vector<int> & w = stack.back();
for(int j = 1; j < (int) w.size(); ++j)
global.push_back(w[j]);
static int T = -1;
global.push_back(T--);
if(i == n - 1) return;
// for(int x : w) printf("%d ", x);
int h = w[0];
for(int j = 1; j < (int) w.size(); ++j)
h = getHash(h, w[j]);
stack.pop_back();
assert(!stack.empty());
stack.back().push_back(getHash(h, 0));
// printf(" h = %d (%d)\n", h, getHash(h, 0));
}
}
}
char sl[nax];
int pref[nax], minSuf[nax];
int toValue(char z) { return z == '(' ? 1 : -1; }
int main() {
int n;
scanf("%d", &n);
scanf("%s", sl);
/*set<string> brute;
for(int i = 0; i < n; ++i) {
string ss;
int cnt = 0;
for(int j = i; j < n; ++j) {
char z = sl[j];
ss += z;
if(z == '(') ++cnt;
else --cnt;
if(cnt < 0) break;
if(cnt == 0) brute.insert(ss);
}
}
printf("%d\n", (int) brute.size());*/
// find valid fragments, e.g. set {(), (()), ()()()} for ))())))(())(((()()()
for(int i = 0; i < n; ++i) {
if(i) pref[i] = pref[i-1];
pref[i] += toValue(sl[i]);
}
minSuf[n] = inf;
for(int i = n - 1; i >= 0; --i)
minSuf[i] = min(minSuf[i+1], pref[i]);
for(int i = 0; i < n; ++i) {
string ss;
while(sl[i] == '(' && minSuf[i+1] < pref[i]) {
ss += sl[i];
int val = toValue(sl[i]);
while(val) {
++i;
val += toValue(sl[i]);
ss += sl[i];
}
++i;
}
if(ss.empty()) {}//printf("X");
else {
consider(ss);
--i;
}
}
if(global.empty()) {
puts("0");
return 0;
}
long long answer = (long long) global.size() * (global.size() + 1) / 2;
for(int i = 0; i < (int) global.size(); ++i) if(global[i] > 0) {
int j = i;
while(j + 1 < (int) global.size() && global[j+1] > 0) ++j;
long long tmp = j - i + 1;
answer -= tmp * (tmp + 1) / 2;
i = j;
}
printf("%lld\n", count_substrings(global) - answer + 1);
return 0;
}
|
653
|
G
|
Move by Prime
|
Pussycat Sonya has an array consisting of $n$ positive integers. There are $2^{n}$ possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two:
- Choose some element of the subsequence and multiply it by some prime number.
- Choose some element of the subsequence and divide it by some prime number. The chosen element must be divisible by the chosen prime number.
What is the sum of minimum number of operations for all $2^{n}$ possible subsequences? Find and print this sum modulo $10^{9} + 7$.
|
you can consider each prime number separately. Can you find the answer if there are only 1's and 2's in the input? It may be hard to try to iterate over possible placements of the median. Maybe it's better to think how many numbers we will change from 2^p to 2^{p+1}.
|
[
"combinatorics",
"math",
"number theory"
] | 3,100
| null |
658
|
A
|
Bear and Reverse Radewoosh
|
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be $n$ problems. The $i$-th problem has initial score $p_{i}$ and it takes exactly $t_{i}$ minutes to solve it. Problems are sorted by difficulty — it's guaranteed that $p_{i} < p_{i + 1}$ and $t_{i} < t_{i + 1}$.
A constant $c$ is given too, representing the speed of loosing points. Then, submitting the $i$-th problem at time $x$ ($x$ minutes after the start of the contest) gives $max(0, p_{i} - c·x)$ points.
Limak is going to solve problems in order $1, 2, ..., n$ (sorted increasingly by $p_{i}$). Radewoosh is going to solve them in order $n, n - 1, ..., 1$ (sorted decreasingly by $p_{i}$). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.
You may assume that the duration of the competition is greater or equal than the sum of all $t_{i}$. That means both Limak and Radewoosh will accept all $n$ problems.
|
Iterate once from left to right to calculate one player's score and then iterate from right to left. It's generally good not to write something similar twice because you are more likely to make mistakes. Or maybe later you will find some bug and correct it only in one place. So, try to write calculating score in a function and run them twice. Maybe you will need to reverse the given arrays in some moment.
|
[
"implementation"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
const int nax = 1005;
int n, c;
int p[nax], t[nax];
int getScore() {
int total = 0;
int T = 0;
for(int i = 0; i < n; ++i) {
T += t[i];
total += max(0, p[i] - T * c);
}
return total;
}
int main() {
scanf("%d%d", &n, &c);
for(int i = 0; i < n; ++i)
scanf("%d", &p[i]);
for(int i = 0; i < n; ++i)
scanf("%d", &t[i]);
int score1 = getScore();
reverse(t, t + n);
reverse(p, p + n);
int score2 = getScore();
if(score1 > score2) puts("Limak");
else if(score1 < score2) puts("Radewoosh");
else puts("Tie");
return 0;
}
|
659
|
A
|
Round House
|
Vasya lives in a round building, whose entrances are numbered sequentially by integers from $1$ to $n$. Entrance $n$ and entrance $1$ are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance $a$ and he decided that during his walk he will move around the house $b$ entrances in the direction of increasing numbers (in this order entrance $n$ should be followed by entrance $1$). The negative value of $b$ corresponds to moving $|b|$ entrances in the order of decreasing numbers (in this order entrance $1$ is followed by entrance $n$). If $b = 0$, then Vasya prefers to walk beside his entrance.
\begin{center}
{\small Illustration for $n = 6$, $a = 2$, $b = - 5$.}
\end{center}
Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.
|
The answer for the problem is calculated with a formula $((a - 1 + b)$ $\mathrm{mod}$ $n$ + $n$) $\mathrm{mod}$ $n$ + $1$. Such solution has complexity $O(1)$. There is also a solution with iterations, modelling every of $|b|$'s Vasya's moves by one entrance one by one in desired direction, allowed to pass all the tests. This solution's complexity is $O(|b|)$.
|
[
"implementation",
"math"
] | 1,000
| null |
659
|
B
|
Qualifying Contest
|
Very soon Berland will hold a School Team Programming Olympiad. From each of the $m$ Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by $n$ Berland students. There were at least two schoolboys participating from each of the $m$ regions of Berland. The result of each of the participants of the qualifying competition is an integer score from $0$ to $800$ inclusive.
The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a \textbf{greater} number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.
Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
|
Let's consider the participants from every region separately. So for every region we just need to sort all of its participants by their score in non-increasing order. The answer for a region is inconsistent if and only if the score of the second and the third participant in this order are equal, otherwise the answer is the first and the second participant in this order. The solution complexity is $O(n\log n)$.
|
[
"constructive algorithms",
"sortings"
] | 1,300
| null |
659
|
C
|
Tanya and Toys
|
In Berland recently a new collection of toys went on sale. This collection consists of $10^{9}$ types of toys, numbered with integers from $1$ to $10^{9}$. A toy from the new collection of the $i$-th type costs $i$ bourles.
Tania has managed to collect $n$ different types of toys $a_{1}, a_{2}, ..., a_{n}$ from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than $m$ bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.
Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
|
Our task is to take largest amount of toys Tanya doesn't have yet the way the sum of their costs doesn't exceed $m$. To do that one can perform greedy algorithm: let's buy the cheepest toy Tanya doesn't have at every step, while the amount of money left are sufficient to do that. The boolean array $used$ can be a handle in that, storing $true$ values in indices equal to toy types which Tanya does have at the moment. As soon as $10^{9}$ money is sufficient to buy no more than $10^{5}$ toys $\ ({\frac{(1^{9}\times(10^{9}+1)}{2}}\geq10^{9})$, $used$ is enough to be sized $2 \times 10^{5}$ (we won't buy the toys with types numbered greater). So we just need to iterate over the number of type we want to buy, and if corresponding value in $used$ is equal to $false$, we should buy it, otherwise we can't. The solution complexity is $O(n+{\sqrt{m}})$. One can use the <> data structure (C++ \texttt{std::set}, for example), for storing the types Tanya has at the moment. In this case the complexity is $O(n+{\sqrt{m}}\log n)$.
|
[
"greedy",
"implementation"
] | 1,200
| null |
659
|
D
|
Bicycle Race
|
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the $Ox$ axis from west to east, and the $Oy$ axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).
Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.
Help Maria get ready for the competition — determine the number of dangerous turns on the track.
|
From the track description follows that Maria moves the way that the water always located to the right from her, so she could fall into the water only while turning left. To check if the turn is to the left, let's give every Maria's moves directions a number: moving to the north - $0$, moving to the west - $1$, to the south - $2$ and to the east - $3$. Then the turn is to the left if and only if the number of direction after performing a turn $dir$ is equal to the number before performing a turn $oldDir$ plus one modulo $4$ $(d i r\equiv o l d D i r+1(\mod4))$. This solution has complexity $O(n)$. One can solve this problem in alternative way. Let the answer be equal to $x$ (that means that the number of inner corners of $270$ degrees equals $x$, but the number of inner corners of $90$ degrees to $n - x$). As soon as the sum of the inner corners' values of polygon of $n$ vertices is equal to $180 \times (n - 2)$, then $x \times 270 + (n - x) \times 90$ equals to $180 \times (n - 2)$. This leads us to $x={\frac{n-4}{2}}$, being the answer for the problem calculated in $O(1)$.
|
[
"geometry",
"implementation",
"math"
] | 1,500
| null |
659
|
E
|
New Reform
|
Berland has $n$ cities connected by $m$ bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is \textbf{not guaranteed} that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
|
One should notice, that for every connected component of the graph the problem could be solved independently, so we just need to solve the problem for any connected graph. Let this connected graph (of $n$ vertices) contain $n - 1$ edge (such is called a tree). If one maintain a DFS from any of its vertex, every edge will be oriented, and each of them could given to its ending vertex, this way every vertex (except the one we launched DFS from, that is the root) will be satisfied by an edge. In this case the answer is equal to $1$. Let's then deal with a case when the graph contains more than $n - 1$ edges. This graph contains at least one cycle. Let's take arbitrary vertex from any of the cycles and launch a DFS (as above) from it. All vertices except chosen will be satisfied, so we are to give an edge to the chosen vertex. As soon as chosen vertex belongs to a cycle, at least one of its edge will not be taken to account in the DFS, so it can be given to a root. This way all the vertices will be satisfied. Now we are able to solve the task for any connected graph, so we are to divide the graph into a connected components - this can be easily done by DFS or BFS. The solution complexity is $O(n + m)$.
|
[
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy"
] | 1,600
| null |
659
|
F
|
Polycarp and Hay
|
The farmer Polycarp has a warehouse with hay, which can be represented as an $n × m$ rectangular table, where $n$ is the number of rows, and $m$ is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the $i$-th row and the $j$-th column is equal to an integer $a_{i, j}$ and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base $1 × 1$. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
- the total amount of hay remaining in the warehouse must be \textbf{equal} to $k$,
- the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
- the height of at least one stack must remain the same as it was,
- for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
|
In this task one should find a connected area, in which the product of the minimum value of the cells and the number of the cells is equal to $k$. To find such, let's sort all the $n \times m$ cells by their values by non-increasing order. Then we will consecutively add them in this order one by one, maintaining a connected components on their neighbouring relations graph. It's enough to use Disjoint Set Union structure to do so, storing additionally size of every component. Let $a_{i, j}$ be the last added element in some component $id$, so $a_{i, j}$ has the minimum value among all the cells in component $id$ (according to our ordering). If $a_{i, j}$ does not divide $k$, then the component $id$ could not consist of desired area. Otherwise ($a_{i, j}$ is divisor of $k$), let's find $need = k / a_{i, j}$ - desired area size (if it contains $a_{i, j}$), and if $CNT_{id}$ is not less than $need$, then the component $id$ contains desired area, which could be easily found by launching a DFS in a neighbouring relation graph from $a_{i, j}$, visiting only the $a_{p, q} \ge a_{i, j}$ and exactly $need$ of them. The solution complexity is $O(n^{2}\log{n})$.
|
[
"dfs and similar",
"dsu",
"graphs",
"greedy",
"sortings"
] | 2,000
| null |
659
|
G
|
Fence Divercity
|
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of $n$ consecutively fastened vertical boards of centimeter width, the height of each in centimeters is \textbf{a positive integer}. The house owner remembers that the height of the $i$-th board to the left is $h_{i}$.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such $i$, that the height of the $i$-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by $1 000 000 007$ $(10^{9} + 7)$.
|
Let the answer for the problem be the sum $\sum_{l=1}^{n}\sum_{T=l}^{n}c a l c(l,r),$ where $calc(l, r)$ is the number of ways to cut the top part of the fence the way its leftmost part is in position $l$ and the rightmost in position $r$. If $l = r$, that is the case when the cutted top part consists of part of only one board, then $calc(l, r) = h_{l} - 1$. Let $r > l$, then $\begin{array}{c}{{c a l l c}{{c a l c(l,r)=\operatorname*{min}(h_{l}-1,h_{l+1}-1)\times\operatorname*{min}(h_{r-1}-1,h_{r}-1)\times\prod_{i=l+1}^{r-1}\operatorname*{min}(h_{i-1}-1)\times\prod_{i=l}^{r}\operatorname*{min}(h_{i-1}-1)}}\\ {{1,h_{i}-1,h_{i+1}-1).}}\end{array}$ In other words, the number of ways to cut the top part of some board is equal to minimum value among heights of it and its neighbours minus one, otherwise the cutted part will be inconsistent. Leftmost board and rightmost board are considered separately, because each of them does have only one neighbouring board. So the answer looks like $\begin{array}{l}{{\sum_{i=0}^{\left\lfloor n\right\rfloor}(h_{i}-1)+\sum_{l=1}^{n}\sum_{r=l+1}^{n}\operatorname*{min}(h_{l}-1,h_{l+1}-1)\times\operatorname*{min}(h_{r-1}-1,h_{r}-1)\right\rfloor}}\\ {{\mid\times\prod_{i=1+1}^{n-1}\operatorname*{min}(h_{i-1}-1,h_{i}-1).}}\end{array}$ The first summand is easy to calculate, so let's take a look at the second. Let us modify it as the following: $\begin{array}{c}{{\sum_{r=2}^{n}\operatorname*{min}(h_{r-1}-1,h_{r}-1)\times\sum_{l=1}^{r-1}\operatorname*{min}(h_{l}-1,h_{l+1}-1)\times\prod_{i=l+1}^{r-1}\operatorname*{min}(h_{i-1}-1)\sum\prod_{i=l+1}^{r-1}\operatorname*{min}(h_{i-1}-1)\sum\prod_{i=l}^{r}\operatorname*{min}(h_{i-1}-1)\operatorname*{sgn}(h_{i}-1)\rangle\right\},}}\\ {{\frac{1}{g_{i}}-1,h_{i+1}-1.}}\end{array}$ Let $S(r)=\sum_{l=1}^{r-1}\operatorname*{min}(h_{l}-1,h_{l+1}-1)\times\prod_{i=l+1}^{r-1}\operatorname*{min}(h_{i-1}-1,h_{i}-1,h_{i+1}-1).$ Let's take a look how does the $S(r)$ change after increasing $r$ by one: $S(r + 1) = S(r) \times min(h_{r - 1} - 1, h_{r} - 1, h_{r + 1} - 1) + min(h_{r} - 1, h_{r + 1} - 1).$ This way this sum is easy to maintain if consecutively increase $r$ from $2$ to $n$. The solution complexity is $O(n)$.
|
[
"combinatorics",
"dp",
"number theory"
] | 2,300
| null |
660
|
A
|
Co-prime Array
|
You are given an array of $n$ elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than $10^{9}$ in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integers $a$ and $b$ are said to be co-prime if the only positive integer that divides both of them is $1$.
|
Note that we should insert some number between any adjacent not co-prime elements. On other hand we always can insert the number $1$. Complexity: $O(nlogn)$.
|
[
"greedy",
"implementation",
"math",
"number theory"
] | 1,200
|
const int N = 1010;
int n, a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
void solve() {
function<int(int, int)> gcd = [&](int a, int b) { return !a ? b : gcd(b % a, a); };
vector<int> ans;
forn(i, n) {
ans.pb(a[i]);
if (i + 1 < n && gcd(a[i], a[i + 1]) > 1)
ans.pb(1);
}
cout << sz(ans) - n << endl;
forn(i, sz(ans)) {
if (i) putchar(' ');
printf("%d", ans[i]);
}
puts("");
}
|
660
|
B
|
Seating On Bus
|
Consider $2n$ rows of the seats in a bus. $n$ rows of the seats on the left and $n$ rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is $4n$.
Consider that $m$ ($m ≤ 4n$) people occupy the seats in the bus. The passengers entering the bus are numbered from $1$ to $m$ (in the order of their entering the bus). The pattern of the seat occupation is as below:
$1$-st row left window seat, $1$-st row right window seat, $2$-nd row left window seat, $2$-nd row right window seat, ... , $n$-th row left window seat, $n$-th row right window seat.
After occupying all the window seats (for $m > 2n$) the non-window seats are occupied:
$1$-st row left non-window seat, $1$-st row right non-window seat, ... , $n$-th row left non-window seat, $n$-th row right non-window seat.
All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.
$1$-st row left non-window seat, $1$-st row left window seat, $1$-st row right non-window seat, $1$-st row right window seat, ... , $n$-th row left non-window seat, $n$-th row left window seat, $n$-th row right non-window seat, $n$-th row right window seat.
\begin{center}
{\small The seating for $n = 9$ and $m = 36$.}
\end{center}
You are given the values $n$ and $m$. Output $m$ numbers from $1$ to $m$, the order in which the passengers will get off the bus.
|
In this problem you should simply do what was written in the problem statement. There are no tricks. Complexity: $O(n)$.
|
[
"implementation"
] | 1,000
|
int n, m;
bool read() {
return !!(cin >> n >> m);
}
const int N = 111;
int a[N][4];
void solve() {
forn(i, n) {
a[i][0] = 2 * i;
a[i][1] = 2 * (n + i);
a[i][2] = 2 * (n + i) + 1;
a[i][3] = 2 * i + 1;
}
vector<int> ans;
forn(i, n) {
ans.pb(a[i][1]);
ans.pb(a[i][0]);
ans.pb(a[i][2]);
ans.pb(a[i][3]);
}
nfor(i, sz(ans)) // inverse order
if (ans[i] >= m)
ans.erase(ans.begin() + i);
forn(i, m) {
if (i) putchar(' ');
printf("%d", ans[i] + 1);
}
puts("");
}
|
660
|
C
|
Hard Process
|
You are given an array $a$ with $n$ elements. Each element of $a$ is either $0$ or $1$.
Let's denote the length of the longest subsegment of consecutive elements in $a$, consisting of only numbers one, as $f(a)$. You can change no more than $k$ zeroes to ones to maximize $f(a)$.
|
Let's call the segment $[l, r]$ good if it contains no more than $k$ zeroes. Note if segment $[l, r]$ is good than the segment $[l + 1, r]$ is also good. So we can use the method of two pointers: the first pointer is $l$ and the second is $r$. Let's iterate over $l$ from the left to the right and move $r$ while we can (to do that we should simply maintain the number of zeroes in the current segment). Complexity: $O(n)$.
|
[
"binary search",
"dp",
"two pointers"
] | 1,600
|
const int N = 1200300;
int n, k;
int a[N];
bool read() {
if (!(cin >> n >> k)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
void solve() {
int ansl = 0, ansr = 0;
int j = 0, cnt = 0;
forn(i, n) {
if (j < i) {
j = i;
cnt = 0;
}
while (j < n) {
int ncnt = cnt + !a[j];
if (ncnt > k) break;
cnt += !a[j];
j++;
}
if (j - i > ansr - ansl)
ansl = i, ansr = j;
if (cnt > 0) cnt -= !a[i];
}
cout << ansr - ansl << endl;
fore(i, ansl, ansr) a[i] = 1;
forn(i, n) {
if (i) putchar(' ');
printf("%d", a[i]);
}
puts("");
}
|
660
|
D
|
Number of Parallelograms
|
You are given $n$ points on a plane. All the points are distinct, and no three of them lie on the same line. Find the number of parallelograms with vertices at the given points.
|
It's known that the diagonals of a parallelogram split each other in the middle. Let's iterate over the pairs of points $a, b$ and consider the middle of the segment $\overline{{a b}}$: $c={\frac{a+b}{2}}$. Let's calculate the value $cnt_{c}$ for each middle. $cnt_{c}$ is the number of segments $a, b$ with the middle $c$. Easy to see that the answer is $\sum_{e}{\frac{c n i c\cdot(c n t_{e}-1)}{2}}$. Complexity: $O(n^{2}logn)$.
|
[
"geometry"
] | 1,900
|
const int N = 2020;
int n;
int x[N], y[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n)
assert(scanf("%d%d", &x[i], &y[i]) == 2);
return true;
}
inline li C2(li n) { return n * (n - 1) / 2; }
void solve() {
map<pti, int> cnt;
forn(i, n)
forn(j, i) {
int cx = x[i] + x[j];
int cy = y[i] + y[j];
cnt[{cx, cy}]++;
}
li ans = 0;
for (const auto& p : cnt)
ans += C2(p.y);
cout << ans << endl;
}
|
660
|
E
|
Different Subsets For All Tuples
|
For a sequence $a$ of $n$ integers between $1$ and $m$, inclusive, denote $f(a)$ as the number of distinct subsequences of $a$ (including the empty subsequence).
You are given two positive integers $n$ and $m$. Let $S$ be the set of all sequences of length $n$ consisting of numbers from $1$ to $m$. Compute the sum $f(a)$ over all $a$ in $S$ modulo $10^{9} + 7$.
|
Let's consider some subsequence with the length $k > 0$ (the empty subsequences we will count separately by adding the valye $m^{n}$ at the end) and count the number of sequences that contains it. We should do that accurately to not count the same sequence multiple times. Let $x_{1}, x_{2}, ..., x_{k}$ be the fixed subsequence. In the original sequence before the element $x_{1}$ can be some other elements, but none of them can be equal to $x_{1}$ (because we want to count the subsequence exactly one time). So we have $m - 1$ variants for each of the elements before $x_{1}$. Similarly between elements $x_{1}$ and $x_{2}$ can be other elements and we have $m - 1$ choices for each of them. And so on. After the element $x_{k}$ can be some elements (suppose there are $j$ such elements) with no additional constraints (so we have $m$ choices for each of them). We fixed the number of elements at the end $j$, so we should distribute $n - k - j$ numbers between numbers before $x_{1}$, between $x_{1}$ and $x_{2}$, \ldots, between $x_{k - 1}$ and $x_{k}$. Easy to see that we have $\textstyle{\binom{n-j-1}{k-1}}$ choices to do that (it's simply binomial coefficient with allowed repititions). The number of sequences $x_{1}, x_{2}, ..., x_{k}$ equals to $m^{k}$. So the answer is $\sum_{k=1}^{n}\sum_{j=0}^{n-k}m^{k}m^{j}(m-1)^{n-j-k}{\binom{n-j-1}{k-1}}$. Easy to transform the last sum to the sum $\sum_{s=1}^{n}m^{s}(m-1)^{n-s}\sum_{k=0}^{s-1}{\binom{n-s+k}{k}}$. Note the last inner sum can be calculating using the formula for parallel summing: $\sum_{k<n}{\binom{r+k}{k}}\ =\ {\binom{r+n+1}{n}}$. So the answer equals to $m^{n}+\sum_{s=1}^{n}m^{s}(m-1)^{n-s}{\binom{n}{s-1}}$. Also we can get the closed formula for the last sum to get logarithmic solution, but it is not required in the problem. Complexity: $O((n + m)log MOD)$, where $MOD = 10^{9} + 7$.
|
[
"combinatorics",
"math"
] | 2,300
|
int n, m;
bool read() {
return !!(cin >> n >> m);
}
const int N = 1200300;
const int mod = 1000 * 1000 * 1000 + 7;
int gcd(int a, int b, int& x, int& y) {
if (!a) {
x = 0, y = 1;
return b;
}
int xx, yy, g = gcd(b % a, a, xx, yy);
x = yy - b / a * xx;
y = xx;
return g;
}
inline int inv(int a) {
int x, y;
assert(gcd(a, mod, x, y) == 1);
x %= mod;
return x < 0 ? x + mod : x;
}
inline int mul(int a, int b) { return int(a * 1ll * b % mod); }
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); }
int fact[N], ifact[N];
inline int C(int n, int k) {
if (k < 0 || k > n) return 0;
return mul(fact[n], mul(ifact[k], ifact[n - k]));
}
int pm[N], pm1[N];
void solve() {
const int N = n + 1;
fact[0] = 1; fore(i, 1, N) fact[i] = mul(fact[i - 1], i);
forn(i, N) ifact[i] = inv(fact[i]);
pm[0] = 1; fore(i, 1, N) pm[i] = mul(pm[i - 1], m);
pm1[0] = 1; fore(i, 1, N) pm1[i] = mul(pm1[i - 1], sub(m, 1));
int ans = pm[n];
fore(s, 1, n + 1) {
int cur = 1;
cur = mul(cur, pm[s]);
cur = mul(cur, pm1[n - s]);
cur = mul(cur, C(n, s - 1));
inc(ans, cur);
}
cout << ans << endl;
}
|
660
|
F
|
Bear and Bowling 4
|
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 the $i$-th roll is multiplied by $i$ and scores are summed up. So, for $k$ rolls with scores $s_{1}, s_{2}, ..., s_{k}$, the total score is $\textstyle\sum_{i=1}^{k}i\cdot s_{i}$. The total score is $0$ if there were no rolls.
Limak made $n$ rolls and got score $a_{i}$ for the $i$-th of them. He wants to maximize his total score and he came up with an interesting idea. He can say that some first rolls were only a warm-up, and that he wasn't focused during the last rolls. More formally, he can cancel any prefix and any suffix of the sequence $a_{1}, a_{2}, ..., a_{n}$. It is allowed to cancel all rolls, or to cancel none of them.
The total score is calculated as if there were only non-canceled rolls. So, the first non-canceled roll has score multiplied by $1$, the second one has score multiplied by $2$, and so on, till the last non-canceled roll.
What maximum total score can Limak get?
|
The key is to use divide and conquer. We need a recursive function f(left, right) that runs f(left, mid) and f(mid+1, right) (where $mid = (left + right) / 2$) and also considers all intervals going through $mid$. We will eventually need a convex hull of lines (linear functions) and let's see how to achieve it. For variables $L, R$ ($L\in[l e f t,m i d]$, $R\in[m i d+1,r i g h t]$) we will try to write the score of interval $[L, R]$ as a linear function. It would be good to get something close to $a_{L} \cdot x_{R} + b_{L}$ where $a_{L}$ and $b_{L}$ depend on $L$, and $x_{R}$ depends on $R$ only. $\begin{array}{l}{{\displaystyle=\sum_{i=L}^{R}t_{i}\cdot(i-L+1)+\sum_{i=m i d+1}^{R}}}\\ {{=\sum_{i=L}^{m_{i=L}}t_{i}\cdot(i-L+1)+\sum_{i=m i d+1}t_{i}\cdot(i-L+1)}}\\ {{=\sum_{i=L}^{m_{i=L}}t_{i}\cdot(i-L+1)+\sum_{i=m i d+1}t_{i}\cdot(i-m i d)}}\\ {{=\left.\sum_{i=m i d+1}t_{i}\cdot(i-L+1)+\sum_{i=m i d+2}t_{i}\right)+\sum_{i=m i d+1}t_{i}\cdot(i-m i d+1}t_{i})}}\end{array}$ For each $L$ we should find a linear function $f_{L}(x) = a_{L} \cdot x + b_{L}$ where $a_{L}, b_{L}$ should fit the equation $( * )$: $\begin{array}{c}{{b_{L}=\sum_{i=L}^{m i d}t_{i}\cdot\left(i-L+1\right)}}\\ {{a_{L}=m\dot{\imath}d-L+1}}\end{array}$ Now we have a set of linear functions representing all possible left endpoints $L$. For each right endpoint $R$ we should find $x_{R}$ and $const_{R}$ to fit equation $( * )$ again. With value of $x_{R}$ we can iterate over functions $f_{L}$ to find the one maximizing value of $b_{L} + a_{L} \cdot x_{R}$. And (still for fixed $R$) we should add $const_{R}$ to get the maximum possible score of interval ending in $R$. Now let's make it faster. After finding a set of linear functions $f_{L}$ we should build a convex hull of them (note that they're already sorted by slope). To achieve it we need something to compare $3$ functions and decide whether one of them is unnecessary because it's always below one of other two functions. Note that in standard convex hull of points you also need something similar (but for $3$ points). Below you can find an almost-fast-enough solution with a useful function bool is_middle_needed(f1, f2, f3). You may check that numbers calculated there do fit in long long. Finally, one last thing is needed to make it faster than $O(n^{2})$. We should use the fact that we have built a convex hull of functions (lines). For each $R$ you should binary search optimal function. Alternatively, you can sort pairs $(x_{R}, const_{R})$ and then use the two pointers method - check the implementation in my solution below. It gives complexity $O(n\cdot\log^{2}(n))$ because we sort by $x_{R}$ inside of a recursive function. I think it's possible to get rid of this by sorting prefixes ${\mathrm{prefix}}_{R}=\textstyle\sum_{i=1}^{R}t_{i}$ in advance because it's equivalent to sorting by $x_{R}$. And we should use the already known order when we run a recursive function for smaller intervals. So, I think $O(n\log n)$ is possible this way - anybody implemented it? Complexity: $O(nlog^{2}n)$.
|
[
"binary search",
"data structures",
"divide and conquer",
"geometry",
"ternary search"
] | 2,500
|
// O(n log^2(n))
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int nax = 1e6 + 5;
ll ans;
ll t[nax];
struct Fun {
ll a, b;
ll getValue(ll x) { return a * x + b; }
};
bool is_middle_needed(const Fun & f1, const Fun & f2, const Fun & f3) {
// we ask if for at least one 'x' there is f2(x) > max(f1(x), f3(x))
assert(0 < f1.a && f1.a < f2.a && f2.a < f3.a);
// where is the intersection of f1 and f2?
// f1.a * x + f1.b = f2.a * x + f2.b
// x * (f2.a - f1.a) = f1.b - f2.b
// x = (f1.b - f2.b) / (f2.a - f1.a)
ll p1 = f1.b - f2.b;
ll q1 = f2.a - f1.a;
// and the intersection of f1 and f3
ll p2 = f1.b - f3.b;
ll q2 = f3.a - f1.a;
assert(q1 > 0 && q2 > 0);
// return p1 / q1 < p2 / q2
return p1 * q2 < q1 * p2;
}
void rec(int first, int last) {
if(first == last) {
ans = max(ans, t[first]);
return;
}
int mid = (first + last) / 2;
rec(first, mid); // the left half is [first, mid]
rec(mid+1, last); // the right half is [mid+1, last]
// we must consider all intervals starting in [first,mid] and ending in [mid+1, last]
vector<Fun> functions;
ll sum_so_far = 0; // t[i]+t[i+1]+...+t[mid]
ll score_so_far = 0; // t[i]*1 + t[i+1]*2 + ... + t[mid]*(mid-i+1)
for(int i = mid; i >= first; --i) {
sum_so_far += t[i];
score_so_far += sum_so_far;
Fun f = Fun{mid - i + 1, score_so_far};
while(true) {
int s = functions.size();
if(s >= 2 && !is_middle_needed(functions[s-2], functions[s-1], f))
functions.pop_back();
else
break;
}
functions.push_back(f);
}
vector<pair<ll, ll>> points;
sum_so_far = 0;
score_so_far = 0;
for(int i = mid+1; i <= last; ++i) {
sum_so_far += t[i];
score_so_far += t[i] * (i - mid);
points.push_back({sum_so_far, score_so_far});
/*for(Fun & f : functions) {
ll score = score_so_far + f.getValue(sum_so_far);
ans = max(ans, score);
}*/
}
sort(points.begin(), points.end());
int i = 0; // which function is the best
for(pair<ll, ll> p : points) {
sum_so_far = p.first;
score_so_far = p.second;
while(i + 1 < (int) functions.size()
&& functions[i].getValue(sum_so_far) <= functions[i+1].getValue(sum_so_far))
++i;
ans = max(ans, score_so_far + functions[i].getValue(sum_so_far));
}
}
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%lld", &t[i]);
rec(1, n);
printf("%lldn", ans);
return 0;
}
|
662
|
A
|
Gambling Nim
|
As you know, the game of "Nim" is played with $n$ piles of stones, where the $i$-th pile initially contains $a_{i}$ stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game.
Petya and Vasya are tired of playing Nim, so they invented their own version of the game and named it the "Gambling Nim". They have $n$ two-sided cards, one side of the $i$-th card has number $a_{i}$ written on it, while the other side has number $b_{i}$. At the beginning of the game the players put all the cards on the table, each card only one of its sides up, and this side is chosen independently and uniformly. Thus they obtain a sequence $c_{1}, c_{2}, ..., c_{n}$, where $c_{i}$ is equal to $a_{i}$ or $b_{i}$. Then they take $n$ piles of stones, with $i$-th pile containing exactly $c_{i}$ stones and play Nim. Petya takes the first turn.
Given that both players play optimally, find the probability of Petya's victory. Output the answer as an irreducible fraction.
|
It is known that the first player loses if and only if the $xor$-sum of all numbers is $0$. Therefore the problem essentially asks to calculate the number of ways to arrange the cards in such a fashion that the $xor$-sum of the numbers on the upper sides of the cards is equal to zero. Let $S=a_{1}\oplus a_{2}\oplus\cdots\oplus a_{n}$ and $c_{i}=a_{i}\oplus b_{i}$. Suppose that the cards with indices $j_{1}, j_{2}, ..., j_{k}$ are faced with numbers of type $b$ and all the others with numbers of type $a$. Then the $xor$-sum of this arrangement is equal to $S\oplus c_{j1}\oplus c_{j2}\oplus\cdots\leftrightarrow c_{j k}$, that is, $S\oplus[x o r.{\mathrm{sum}}\ \mathrm{of\some{\sulset}}\,c_{i}]$. Hence we want to find the number of subsets $c_{i}$ with $xor$-sum of $S$. Note that we can replace $c_{1}$ with $(c_{1}\oplus c_{2})$, as applying $c_{1}$ is the same as applying $(c_{1}\oplus c_{2})\oplus c_{2}$. Thus we can freely replace ${c_{1}, c_{2}}$ with $(c_{1}\oplus c_{2})$ and $c_{2}$ with $\{c_{1},c_{1}\oplus c_{2}\}$. This means that we can apply the following procedure to simplify the set of $c_{i}$: Pick $c_{f}$ with the most significant bit set to one Replace each $c_{i}$ with the bit in that position set to one to $c_{i}\oplus c_{f}$ Remove $c_{f}$ from the set Repeat steps $1$-$5$ with the remaining set Add $c_{f}$ back to the set After this procedure we get a set that contains $k$ zeros and $n - k$ numbers with the property that the positions of the most significant bit set to one strictly decrease. How do we check now whether it is possible to obtain a subset with $xor$-sum $S$? As we have at most one number with a one in the most significant bit, then it tells us whether we should include that number in the subset or not. Similarly we apply the same argument for all other bits. If we don't obtain a subset with the $xor$-sum equal to $S$, then there is no such subset at all. If we do get a subset with $xor$-sum $S$, then the total number of such subsets is equal to $2^{k}$, as for each of the $n - k$ non-zero numbers we already know whether it must be include in such a subset or not, but any subset of $k$ zeros doesn't change the $xor$-sum. In this case the probability of the second player winning the game is equal to ${\frac{2k}{2^{n}}}$, so the first player wins with probability $\frac{2^{n-k}-1}{2^{n-k}}$.
|
[
"bitmasks",
"math",
"matrices",
"probabilities"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int size = 1000 * 1000 + 1;
const int ssize = 100;
int n;
long long a[size], b[size];
long long ort[ssize];
long long p[ssize];
int main() {
long long cur = 0ll;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lld%lld", &a[i], &b[i]);
cur ^= a[i];
a[i] ^= b[i];
}
a[n] = cur;
int len = 0;
for (int i = 0; i <= n; i++) {
for (int j = 0; j < len; j++) {
if (a[i] & p[j])
a[i] ^= ort[j];
}
if (a[i]) {
ort[len++] = a[i];
p[len - 1] = ((a[i] ^ (a[i] - 1)) + 1) >> 1;
}
}
if (a[n]) {
printf("1/1\\n");
} else {
printf("%lld/%lld\\n", (1ll << len) - 1, (1ll << len));
}
return 0;
}
|
662
|
B
|
Graph Coloring
|
You are given an undirected graph that consists of $n$ vertices and $m$ edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of \textbf{all} edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.
Find the minimum possible number of moves required to make the colors of all edges equal.
|
Author of the problem - gen Examine the two choices for the final color separately, and pick the best option afterwards. Now suppose we want to color the edges red. Each vertex should be recolored at most once, since choosing a vertex two times changes nothing (even if the moves are not consecutive). Thus we need to split the vertices into two sets $S$ and $T$, the vertices that are recolored and the vertices that are not affected, respectively. Let $u$ and $v$ be two vertices connected by a red edge. Then for the color to remain red, both $u$ and $v$ should belong to the same set (either $S$ or $T$). On the other hand, if $u$ and $v$ are connected by a blue edge, then exactly one of the vertices should be recolored. In that case $u$ and $v$ should belong to different sets (one to $S$ and the other to $T$). This problem reduces to $0$-$1$ graph coloring, which can be solved by either $DFS$ or $BFS$. As the graph may be disconnected, we need to process the components separately. If any component does not have a $0$-$1$ coloring, there is no solution. Otherwise we need to add the smallest of the two partite sets of the $0$-$1$ coloring of this component to $S$, as we require $S$ to be of minimum size.
|
[
"dfs and similar",
"graphs"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
const int MX = 100000;
int n, vis[MX];
vector<pair<int, char>> G[MX];
vector<int> part[3];
bool dfs(int v, int p, char c) {
if (vis[v] != 0) {
return vis[v] == p;
}
vis[v] = p;
part[p].push_back(v);
for (auto x : G[v]) {
if (dfs(x.first, x.second == c ? p : p ^ 3, c) == false)
return false;
}
return true;
}
vector<int> solve(char c) {
memset(vis, 0, sizeof vis);
vector<int> ans;
for (int i = 0; i < n; i++)
if (vis[i] == 0) {
part[1].clear();
part[2].clear();
if (dfs(i, 1, c) == false) {
for (int j = 0; j < n + 1; j++) ans.push_back(-1);
return ans;
}
int f = 1;
if (part[2].size() < part[1].size()) f = 2;
ans.insert(ans.end(), part[f].begin(), part[f].end());
}
return ans;
}
int main() {
int m;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
int u, v;
char c;
scanf("%d %d %c", &u, &v, &c);
u--;
v--;
G[u].emplace_back(v, c);
G[v].emplace_back(u, c);
}
auto f = solve('R');
auto g = solve('B');
if (g.size() < f.size()) f = g;
if (f.size() > n) {
printf("-1\\n");
return 0;
}
printf("%d\\n", (int)f.size());
for (int x : f) printf("%d ", x + 1);
printf("\\n");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.