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 luc...
[ "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 cel...
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 th...
[ "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...
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 ...
[ "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 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 $\text...
[ "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...
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 criti...
[ "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 pos...
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 ...
[ "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 ca...
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 ma...
[ "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 develo...
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 t...
[ "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 ...
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 b...
[ "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 foun...
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 ...
[ "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 be...
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]$ ...
[ "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 developmen...
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^...
[ "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 pa...
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...
[ "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 ≥...
$\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. $\an...
[ "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 co...
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 regu...
[ "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 p...
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 ...
[ "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_...
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)$....
[ "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 pr...
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(co...
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...
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...
[ "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...
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 ...
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_{}[...
[ "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...
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}\c...
$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 - an...
[ "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) ...
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 ...
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 calcu...
[]
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#d...
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 w...
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 ca...
[ "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#d...
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 operato...
[ "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#d...
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 ...
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 v...
[ "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#d...
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'...
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 t...
[ "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#d...
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 ...
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_{...
[ "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#d...
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 ...
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 prob...
[ "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 ciphe...
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 hav...
[ "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...
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 ...
[ "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$ inc...
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,...
[ "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 mo...
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 ...
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 ...
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...
[ "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 th...
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 tre...
[ "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...
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,...
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 permutat...
[ "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. ...
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 Wi...
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 i...
[ "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--) { i...
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...
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 a...
[ "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(i...
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}^{...
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 sequenc...
[ "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] %...
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 int...
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 mov...
[ "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; r...
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 i...
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 thi...
[ "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; fo...
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 necess...
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 edge...
[ "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]; ...
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. Gras...
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...
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...
[ "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 ...
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 or...
[ "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$), a...
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 minimu...
[ "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 ...
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 wh...
[ "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 disjunc...
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 ...
[]
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 t...
[]
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 =...
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 o...
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 ca...
[ "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...
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, v...
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 li...
[ "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) ...
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 sy...
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_{...
[ "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(...
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$ f...
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 o...
[]
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(int...
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 eac...
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...
[ "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...
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 drin...
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 num...
[ "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; f...
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 a...
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 z...
[ "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 ...
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...
[ "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...
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 limeli...
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 m...
[ "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 occupie...
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 com...
[ "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 ...
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 o...
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 progra...
[ "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]...
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 ...
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 ca...
[ "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) %...
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$ diffe...
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 c...
[ "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) *...
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 ...
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 ha...
[ "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] / ...
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 Manhat...
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 ...
[ "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...
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 throug...
[ "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 $...
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 a...
[ "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$ tre...
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 wil...
[ "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 w...
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 w...
[ "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...
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...
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 f...
[ "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 intereste...
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 lo...
[ "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$-s...
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 (...
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...
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...
[ "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 sol...
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 po...
[ "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...
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 powerfu...
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 co...
[ "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 (...
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 ...
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 ...
[ "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; ...
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 tha...
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...
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...
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...
[ "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 e...
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 $...
[ "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 ...
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}), (...
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 ...
[ "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 : me...
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 cons...
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 ...
[ "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....
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 pri...
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 di...
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 func...
[ "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...
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 i...
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 test...
[ "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 th...
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...
[ "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 ne...
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 handl...
[ "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 ...
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 ...
[ "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 t...
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 wi...
[ "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 ...
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 co...
[ "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}$...
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 o...
[ "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 ...
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],...
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 $...
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]...
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 ...
[ "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]; ...
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 $...
[ "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...
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(...
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 sub...
[ "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...
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_...
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 var...
[ "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) >...
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 an...
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\cdo...
[ "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]); ...
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 ...
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 sp...
[ "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.fi...