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
1030
B
Vasya and Cornfield
Vasya owns a cornfield which can be defined with two integers $n$ and $d$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $(0, d), (d, 0), (n, n - d)$ and $(n - d, n)$. \begin{center} {\small An example of a cornfield with $n = 7$ and $d = 2$.} \end{center} Vasya also knows t...
For each point $(x, y)$ let's look at values of two diagonals: $x + y$ and $x - y$. Borders of the cornfield, in fact, give limits to this values in the next way: $d \le x + y \le 2n - d$ and $-d \le x - y \le d$ - that's all we need to check. There is a picture below for the further explanation.
[ "geometry" ]
1,100
#include<bits/stdc++.h> using namespace std; int n, d; int m; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> d; cin >> m; for(int i = 0; i < m; ++i){ int x, y; cin >> x >> y; bool ok = true; if(!((x - y) <= d && (x - y) >= -d)) ok = false; if(!((x + y) <= n + n - ...
1030
C
Vasya and Golden Ticket
Recently Vasya found a golden ticket — a sequence which consists of $n$ digits $a_1a_2\dots a_n$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $350178$ is lucky since it can be divided into three segments $350$, $17$ and $8$: $...
Let's iterate over all possible lengths $len$ of the first segment of the partition. Now, knowing this length, we also can calculate sum $S$ of each segment. Now we can form partition with greedy solution: starting from position $len + 1$ we will find maximal prefix (strictly, segment starting at $len + 1$) with sum lo...
[ "implementation" ]
1,300
#include<bits/stdc++.h> using namespace std; int n; string s; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> s; int sum = 0; for(int i = 0; i < n - 1; ++i){ sum += s[i] - '0'; bool ok = true; int pos = i + 1; int sum2 = 0; while(pos < n){ sum2 = s[pos++] - '0'; ...
1030
D
Vasya and Triangle
Vasya has got three integers $n$, $m$ and $k$. He'd like to find three integer points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$, such that $0 \le x_1, x_2, x_3 \le n$, $0 \le y_1, y_2, y_3 \le m$ and the area of the triangle formed by these points is equal to $\frac{nm}{k}$. Help Vasya! Find such points (if it's possib...
Doubled area of any triangle with integer coordinates is always integer. That's why if $2 n m$ is not divisible by $k$ then there is no valid triangle. Otherwise, it's always possible to find required triangle. We will construct the answer with next algorithm. At first, if $k$ is even then divide it by $2$. Next, find ...
[ "geometry", "number theory" ]
1,800
#include<bits/stdc++.h> using namespace std; long long gcd(long long a, long long b){ return a? gcd(b % a, a) : b; } int main() { //freopen("input.txt", "r", stdin); long long n, m, k; cin >> n >> m >> k; bool isEven = k % 2 == 0; long long p = n * m; if(isEven) k /= 2; if(p % k != 0){ ...
1030
E
Vasya and Good Sequences
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(...
Since we can swap any pair of bits in the number, so all we need to know is just the number of ones in its binary representation. Let create array $b_1, b_2, \dots , b_n$, where $b_i$ is number of ones in binary representation of $a_i$. Forget about array $a$, we will work with array $b$. Let's find a way to decide whe...
[ "bitmasks", "dp" ]
2,000
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 9; int n; long long a[N]; int b[N]; int cnt[2][N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for(int i = 0; i <n; ++i){ cin >> a[i]; b[i] = __builtin_popcountll(a[i]); } long long res = 0; int sufSu...
1030
F
Putting Boxes Together
There is an infinite line consisting of cells. There are $n$ boxes in some cells of this line. The $i$-th box stands in the cell $a_i$ and has weight $w_i$. All $a_i$ are distinct, moreover, $a_{i - 1} < a_i$ holds for all valid $i$. You would like to put together some boxes. Putting together boxes with indices in the...
Firstly, let's prove that it's always optimal to leave one of the boxes untouched. By contradiction: if all boxes will move, so some left part will move right and right part will move left. Let the total cost of shifting the whole left part by one be equal to $S_l$ and cost of the right part be $S_r$. We can replace th...
[ "data structures" ]
2,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y ...
1030
G
Linear Congruential Generator
You are given a tuple generator $f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$, where $f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$ and $f^{(0)} = (x_1, x_2, \dots, x_n)$. Here $x \bmod y$ denotes the remainder of $x$ when divided by $y$. All $p_i$ are primes. One can see that with fixed sequences $x_i...
Each generator $f_i^{(k)}$ can be represented as functional graph so the number of different values equal to the legth of the cycle $c$ plus the length of pre-period $pp$. Generalizing on tuples leads to next observation: number of different tuples equals to $\max\limits_{i = 1..n}(pp_i) + \mathop{\text{lcm}}\limits_{i...
[ "number theory" ]
2,900
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int MOD = int(1e9) + 7; int mul(int a, int b) { return int(a * 1ll * b % MOD); } int binPo...
1031
A
Golden Plate
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into $w\times h$ cells. There should be $k$ gilded rings, the first one should go along the edge of the plate, the second one — $2$ cells away from the edge and so on. Each ring has a width of $1$ cell. Formally, the $i$-th ...
The number of gilded cells in the first (outer) ring is the number of border cells, that is, $2(w + h) - 4$, in the second ring - the number of border cells of the center rectangle with side lengths 4 less, that is, $2(w - 4 + h - 4) - 4$, and so on. This sum can be calculated in a single loop.
[ "implementation", "math" ]
800
null
1031
B
Curiosity Has No Limits
When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0 \le b_i \le 3$). Masha became interested if or not there is an integer sequence of...
Let's solve the problem for $0 \leq a_i, b_i, t_i \leq 1$, that is, for binary sequences. There are two options for $t_1$, the remaining part can be determined one number by one after this: If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 0$ then $t_2$ = 0; If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 1$ then there is no such $t_2$. If ...
[]
1,500
null
1031
C
Cram Time
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely. Lesha knows that today he can study for at most $a$ hours, and he will have $b$ hours to study tom...
Consider any answer with maximal $n + m$. If we used numbers $d_1, d_2, \ldots, d_k$ ($d_i \gt n + m$), then we didn't use some numbers $h_1, h_2, \ldots, h_k$ ($h_i \leq n + m$). Replacing all $d_i$ by $h_i$ ($1 \leq i \leq k$) doesn't violate the restriction. That means that we can assume that the answer consists of ...
[ "greedy" ]
1,600
null
1031
D
Minimum path
You are given a matrix of size $n \times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix. Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string ...
First, let's find the number of a-s in the beginning of the answer. To do this one can calculate dp[i][j] standing for the minimal number of non-a-s among all paths from the initial corner to (i, j). The number of a-s is simply the greatest $(i + j)$ among all pairs $(i, j)$ such that $dp[i][j]\le k$ (or $0$, if there ...
[ "greedy" ]
1,900
null
1031
E
Triple Flips
You are given an array $a$ of length $n$ that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: - Choose three integers $1 \le x < y < z \le n$, that form an arithmetic progression ($y - x = z - y$). - Flip the values $a_x, a_y, a_z$ (i.e. change ...
This problem has a lot of solutions including those ones which are difficult to prove. Let's describe one of the author's solutions. We can find answer with bruteforce if size of array is rather small. For example we can check all combinations of arithmetic progressions with length equals to three. We can find by hand ...
[ "constructive algorithms" ]
2,600
null
1031
F
Familiar Operations
You are given two positive integers $a$ and $b$. There are two possible operations: - multiply one of the numbers by some prime $p$; - divide one of the numbers on its prime factor $p$. What is the minimum number of operations required to obtain two integers having the same number of divisors? You are given several s...
Note that if $a = \prod\limits_{i=1}^{k} p_i ^ {x_i}$ then $d(a) = \prod\limits_{i=1}^{k}(x_i+1)$. This implies that we can map $a$ to vector $(x_1, x_2, \ldots, x_k)$, where $x_1 \ge x_2 \ge \ldots \ge x_k$, because the order of the powers doesn't matter. The operations correspond to adding 1 to some item or appending...
[ "brute force", "graphs", "math" ]
2,800
null
1032
A
Kitchen Utensils
The king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils. All types of utensils in the kingdom are numbered from $1$ to ...
Suppose we've found the minimum possible number $p$ of dishes served for each person. If the input contains utensils of $t$ types exactly, it's clear that the total number of utensils used is at least $p \cdot t \cdot k$ and the number of utensils stolen is at least $p \cdot t \cdot k - n$. Moreover, it's easy to const...
[]
900
null
1032
B
Personalized Cup
At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner. The nameplate is to be rectangular an...
Let's iterate over all possible pairs $(a, b)$ with $1 \leq a \leq 5$ and $1 \leq b \leq 20$ to find the optimal one satisfying the inequality $a \cdot b \geq |s|$. So now we need to place the characters of $s$ in the same relative order through the table. Possibly, several cells will remain unused, but we will distrib...
[]
1,200
null
1032
C
Playing Piano
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $a_1, a_2, \ldots, a_n$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard. Paul is very clever and knows that the essential t...
Let $dp[i][j]$ be $-1$ if we cannot play the first $i$ notes in such a way that the $i$-th note is played by the $j$-th finger, otherwise let this be the number of the previous finger in any of possible fingerings. This $dp$ can be easily calculated for about $5n\cdot 5$ operations.
[ "constructive algorithms", "dp" ]
1,700
null
1032
D
Barcelonian Distance
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind $x = c$ and $y = c$ for every integer $c$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Di...
One way is to handle some cases: intersect the line with the border of the bounding box of $(x_1, y_1)$ and $(x_2, y_2)$, and relax answer by some values depending on the mutual location of intersection points, as on the pics below. Another way is to intersect horizontal and vertical lines through $(x_1, y_1)$ and $(x_...
[ "geometry", "implementation" ]
1,900
null
1032
E
The Unbearable Lightness of Weights
You have a set of $n$ weights. You know that their masses are $a_1$, $a_2$, ..., $a_n$ grams, but you don't know which of them has which mass. You can't distinguish the weights. However, your friend does know the mass of each weight. You can ask your friend to give you exactly $k$ weights with the total mass $m$ (both...
Suppose the numbers $a_{1}, a_{2}, \ldots, a_{n}$ can have only up to two different values. Then we can unambiguously determine the masses of all the weights (e.g., suppose there are $t$ weights with a mass of $w$ each, then we can ask our friend about a set of $t$ weights with a total mass of $t \cdot w$; the only thi...
[ "dp", "math" ]
2,100
null
1032
F
Vasya and Maximum Matching
Vasya has got a tree consisting of $n$ vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there i...
Firstly let's understand when the maximum matching in the tree is unique - and it is unique if and only if it's perfect (i. e. every vertex having at least one incident edge is saturated). So the problem is reduced to counting the number of ways to split the tree so that each component having size $2$ or more has a per...
[ "dp", "trees" ]
2,400
null
1032
G
Chattering
There are $n$ parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely $r_i$. When a parrot with respect level $x$ starts chattering, $x$ neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, a...
Let us for a moment think that parrots stand in a line. We want to compute a series of values $r_{i, k}$ and $l_{i, k}$. $l_{i, k}$ is the index of the leftmost parrot that will chatter in $2^k$ seconds after the $i$-th parrot starts chattering. $r_{i, k}$ is defined similarly. Clearly, $l_{i, 0} = i - a_i$ and $r_{i, ...
[]
2,900
null
1033
A
King Escape
Alice and Bob are playing chess on a huge chessboard with dimensions $n \times n$. Alice has a single piece left — a queen, located at $(a_x, a_y)$, while Bob has only the king standing at $(b_x, b_y)$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to sei...
Imagine a two-dimensional plane with origin positioned on the black queen. We notice that the queen partitions the board into up to four connected components, with each quadrant being one of them. The answer is thus "YES" if and only if the source king position and the target position are in the same quadrant. This con...
[ "dfs and similar", "graphs", "implementation" ]
1,000
null
1033
B
Square Difference
Alice has a lovely piece of cloth. It has the shape of a \textbf{square} with a side of length $a$ centimeters. Bob also wants such piece of cloth. He would prefer a \textbf{square} with a side of length $b$ centimeters (where $b < a$). Alice wanted to make Bob happy, so she cut the needed square out of the corner of h...
The task looks simple enough, but there is a problem. The number we want to check might be very large - it might not even fit into 64-bit integer. Checking primality for it certainly cannot be performed naively. However, the input is no ordinary number. It is of form $A^2 - B^2$, which can be expressed as $(A-B)(A+B)$....
[ "math", "number theory" ]
1,100
null
1033
C
Permutation Game
After a long day, Alice and Bob decided to play a little game. The game board consists of $n$ cells in a straight line, numbered from $1$ to $n$, where each cell contains a number $a_i$ between $1$ and $n$. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating ...
The game is finite thanks to the first restriction on possible moves: the number on which the token lies must strictly increase with each turn. More importantly, this means that if we model the cells as vertices of a graph and create a directed edge between $i$ and $j$ if $i \rightarrow j$ is a valid move, the resultin...
[ "brute force", "dp", "games" ]
1,600
null
1033
D
Divisors
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Each of $a_i$ has between $3$ and $5$ divisors. Consider $a = \prod a_i$ — the product of all input integers. Find the number of divisors of $a$. As this number may be very large, print it modulo prime number $998244353$.
Given a prime factorisation $a = p_1^{e_1} \cdot p_2^{e_2} \cdot \dots \cdot p_k^{e_k}$, one can conclude that the number of divisors of $a$ is $\prod (e_i + 1)$. Note that we do not need to know the values of $p_i$. Can we perhaps find the exponents, without factorising all inputs? A number with between 3 and 5 diviso...
[ "interactive", "math", "number theory" ]
2,000
null
1033
E
Hidden Bipartite Graph
Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he as...
Denote by $e(A)$ the number of edges in a vertex set $A$, and by $e(A,B)$ the number of edges between $A$ and $B$. Note that $e(A,B) = e(A \cup B) - e(A) - e(B)$ can be answered by three queries. Now we learn how to find an edge in this graph in logarithmic time. Given two sets $X$ and $Y$, such that $e(X,Y) \neq 0$, w...
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "interactive" ]
2,800
null
1033
F
Boolean Computer
Alice has a computer that operates on $w$-bit integers. The computer has $n$ \textbf{registers} for values. The current content of the registers is given as an array $a_1, a_2, \ldots, a_n$. The computer uses so-called "number gates" to manipulate this data. Each "number gate" takes two registers as inputs and calcula...
First we count $C[i]$ the number of occurrences of $i$ in the input for each number between $0$ and $2^w - 1$. We can then notice that each bit gate $G$ maps between $1$ and $3$ two-bit patterns to $0$ (e.g. for xor gate, this is 00 and 11, for and gate this is 00, 01 and 10). This means that we can calculate the answe...
[ "bitmasks", "brute force", "fft", "math" ]
2,800
null
1033
G
Chip Game
Alice and Bob decided to play one ultimate game. They have $n$ piles, the $i$-th pile initially contain $v_i$ chips. Alice selects a positive integer $a$ from interval $[1, m]$, and Bob selects a number $b$ the same way. Then the game starts. In her turn, Alice can select any pile containing at least $a$ chips, and re...
Let's solve the task for a fixed tuple $(a, b)$. If $a = b$, this is a very simple symmetric game, where the parity of $\sum \lfloor \frac{v_i}{a} \rfloor$ determines the winner (regardless of the players' choices). Without loss of generality, let $a < b$ as the case where $a > b$ is symmetrical. It is obvious that Bob...
[ "games" ]
3,500
null
1034
A
Enlarge GCD
Mr. F has $n$ positive integers, $a_1, a_2, \ldots, a_n$. He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers. But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in ...
First we divide all numbers by GCD of them. Then we should find a subset with maximum number of integers GCD of which is bigger than $1$. We can enumerate a prime $p$ that GCD of the remaining integers can be divided by. And the number of integers can be divided by $p$ is the maximum size of the subset. We can use Siev...
[ "number theory" ]
1,800
#include<bits/stdc++.h> using namespace std; #define MN 300000 #define MX 15000000 int a[MN+5],u[MX+5],p[MX+5],pn,s[MX+5]; int gcd(int x,int y){return y?gcd(y,x%y):x;} int main() { int n,i,j,g,x,ans=0; for(i=2;i<=MX;++i) { if(!u[i])u[i]=p[++pn]=i; for(j=1;i*p[j]<=MX;++j){u[i*p[j]]=p[j];if(i%p[j]==0)break;} } s...
1034
B
Little C Loves 3 II
Little C loves number «3» very much. He loves all things about it. Now he is playing a game on a chessboard of size $n \times m$. The cell in the $x$-th row and in the $y$-th column is called $(x,y)$. Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan dist...
Following the rules in the problem, the $1 \times 6$, $2 \times 4$, $2 \times 5$ and $3 \times 4$ grids full of chessmen can be easily constructed. Let the number denote the time when the chessman placed. Grids of $1 \times 6$ : 1 2 3 1 2 3 Grids of $2 \times 4$ : 1 2 3 4 3 4 1 2 Grids of $2 \times 5$ : 1...
[ "brute force", "constructive algorithms", "flows", "graph matchings" ]
2,200
#include<bits/stdc++.h> using namespace std; int main() { int n,m; scanf("%d%d",&n,&m); if(n>m)swap(n,m); if(n==1)printf("%d",m/6*3+max(m%6-3,0)<<1); else if(n==2)printf("%d",m==2?0:m==3?4:m==7?12:m<<1); else printf("%lld",1LL*n*m/2*2); }
1034
C
Region Separation
There are $n$ cities in the Kingdom of Autumn, numbered from $1$ to $n$. People can travel between any two cities using $n-1$ two-directional roads. This year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level $1$. Each region of $i...
First, we try to find whether it's possible to separate the kingdom into $k$ regions of level-$2$ with the same sum of values. We calculate $S$, the sum of all the values, so each region should have sum $\mathbf{\Sigma}_{k}^{\infty}$. Let $s_{i}$ be the sum of values in the subtree of root $i$. We consider all the citi...
[ "combinatorics", "dp", "number theory", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define MN 1000000 #define MOD 1000000007 ll s[MN+5];int f[MN+5],p[MN+5],F[MN+5]; inline void rw(int&x,int y){if((x+=y)>=MOD)x-=MOD;} int main() { int n,i,j,ans=0; scanf("%d",&n); for(i=1;i<=n;++i)scanf("%lld",&s[i]); for(i=2;i<=n;++i)scanf("%d",&p[...
1034
D
Intervals of Intervals
Little D is a friend of Little C who loves intervals very much instead of number "$3$". Now he has $n$ intervals on the number axis, the $i$-th of which is $[a_i,b_i]$. Only the $n$ intervals can not satisfy him. He defines the value of an interval of intervals $[l,r]$ ($1 \leq l \leq r \leq n$, $l$ and $r$ are both ...
First we consider how to calculate the value of an interval of intervals $[l, r]$. We can consider intervals in order from $1$ to $n$ and, for each position on the axis, maintain a timestamp denoting the last time it was covered. When the $r$-th interval is taken into consideration, the timestamps for positions $[a_{r}...
[ "binary search", "data structures", "two pointers" ]
3,500
#include<bits/stdc++.h> using namespace std; #define MN 300000 #define p make_pair #define pb push_back #define A first #define B second set< pair<int,int> > st; set< pair<int,int> >::iterator it,tt; vector< pair<int,int> > v[MN+5]; int f[MN+5]; int main() { int n,m,i,j,k,l,r,x,X,t2;long long s1,s2,S1,S2,t1; scanf("...
1034
E
Little C Loves 3 III
Little C loves number «3» very much. He loves all things about it. Now he is interested in the following problem: There are two arrays of $2^n$ intergers $a_0,a_1,...,a_{2^n-1}$ and $b_0,b_1,...,b_{2^n-1}$. The task is for each $i (0 \leq i \leq 2^n-1)$, to calculate $c_i=\sum a_j \cdot b_k$ ($j|k=i$ and $j\&k=0$, w...
If we only need to calculate $c_{i}=\sum a_{j}\cdot b_{k}$ ($j|k = i$), we can do these: Let $A_{i}=\sum a_{j},B_{i}=\sum b_{j}$ ($j|i = i$). Let $A_{i}=\sum a_{j},B_{i}=\sum b_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \cdot Bi$, it can be found that $C_{i}=\sum c_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \cdot Bi$, it can be fo...
[ "bitmasks", "dp", "math" ]
3,200
#include<cstdio> typedef long long ll; #define MN (1<<21) char A[MN+5],B[MN+5]; int s[MN+5];ll a[MN+5],b[MN+5]; int main() { int n,i,j; scanf("%d%s%s",&n,A,B); for(i=0;i<1<<n;++i)s[i]=s[i>>1]+((i&1)<<1),a[i]=(ll)(A[i]-'0')<<s[i],b[i]=(ll)(B[i]-'0')<<s[i]; for(i=0;i<n;++i)for(j=0;j<1<<n;++j)if(j&(1<<i))a[j]+=a[j^(1<...
1036
A
Function Height
You are given a set of $2n+1$ integer points on a Cartesian plane. Points are numbered from $0$ to $2n$ inclusive. Let $P_i$ be the $i$-th point. The $x$-coordinate of the point $P_i$ equals $i$. The $y$-coordinate of the point $P_i$ equals zero (initially). Thus, initially $P_i=(i,0)$. The given points are vertices o...
It is easy to see that the area of the plot is the sum of areas of all triangles in this plot. Each move increases area by one. We cannot obtain the answer less than $\lceil\frac{k}{n}\rceil$ but we always can obtain such an answer.
[ "math" ]
1,000
n, k = map(int, input().split()) print((k + n - 1) // n)
1036
B
Diagonal Walking v.2
Mikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $(0, 0)$, he can go to any of the following points in one move: - $(1, 0)$; - $(1, 1)$; - $(0, 1)$; - $(-1, 1)$; - $(-1, 0)$; - $(-1, -1)$; -...
There are several cases in this problem. If $n < m$ then let's swap them. Let $\%$ be the modulo operator. Firstly, if $n \% 2 \ne m \% 2$ then let's decrease $k$ and $n$ by one. Otherwise if $n \% 2 \ne k \% 2$ let's decrease $n$, $m$ by one and $k$ by two. Now if $k < n$ then the answer is -1, otherwise the answer is...
[ "math" ]
1,600
q = int(input()) for i in range(q): n, m, k = map(int, input().split()) if (n < m): n, m = m, n if (n % 2 != m % 2): k -= 1 n -= 1 elif (n % 2 != k % 2): k -= 2 n -= 1 m -= 1 print(-1 if k < n else k)
1036
C
Classy Numbers
Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not. You are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \le x \le R$...
There are quite a few approaches to the problem. I'll describe the two of them which I actually implemented. First approach - combinatoric one: Problems of the form "count the number of beautiful numbers from $L$ to $R$" usually require counting the numbers on $[1; R]$ and $[1; L - 1]$ (or not inclusively $[1; R + 1)$ ...
[ "combinatorics", "dp" ]
1,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; vector<long long> res; void brute(int pos, int cnt, long long cur){ if (pos == 18){ res.push_back(cur); return; } brute(pos + 1, cnt, cur * 10); if (cnt < 3) for (int i...
1036
D
Vasya and Arrays
Vasya has two arrays $A$ and $B$ of lengths $n$ and $m$, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the ar...
Let's prove that next greedy solution works: each step we will find prefixes of minimal length of arrays $A$ and $B$ such that its sums are equal and we will cut them forming next block. If we will get valid partition in result so it is an optimal solution, otherwise there is no solution. Since length of prefix proport...
[ "greedy", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 300 * 1000 + 9; int n, m; int a[N], b[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); scanf("%d", &m); for(int i = 0; i < m; ++i) scanf("%d", b + i); long long sum = 0; for(int i = 0; i < n; ++i...
1036
E
Covered Points
You are given $n$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line. Count the number of distinct points with \textbf{integer coordinates}, which are covered by at least one segment.
I won't tell all the small geometric details, just cover some major points. The problem asks you the following thing. Sum up the total number of points covered by each segment and for each unique point subtract the number of segments covering it minus one. Let's reformulate it. For each segment add the number of points...
[ "fft", "geometry", "number theory" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 1000 + 7; struct seg{ int x1, y1, x2, y2; seg(){}; }; struct line{ long long A, B, C; line(){}; line(seg a){ A = a.y1 - a.y2; B = a.x2 - a.x1; C = -A * a.x1 - ...
1036
F
Relatively Prime Powers
Consider some positive integer $x$. Its prime factorization will be of form $x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dots$ Let's call $x$ elegant if the greatest common divisor of the sequence $k_1, k_2, \dots$ is equal to $1$. For example, numbers $5 = 5^1$, $12 = 2^2 \cdot 3$, $72 = 2^3 \cdot 3^2$ are elegant...
Whoops, it seems, this problem can be done in a similar manner as in problem $C$. Firstly, is some number $x$ has $GCD$ of the prime powers not equal to $1$, then you can take root $GCD$'th power from it. That is the same as dividing all powers by $GCD$. Now it turned out, there are really a small amount of these numbe...
[ "combinatorics", "math", "number theory" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int K = 100; const int N = 100 * 1000 + 13; const long long INF64 = 3e18; int mu[K]; void precalc(){ static bool prime[K]; static int lst[K]; memset(prime, false, sizeof(prime)); forn(i, K) ...
1036
G
Sources and Sinks
You are given an acyclic directed graph, consisting of $n$ vertices and $m$ edges. The graph contains no multiple edges and no self-loops. The vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source an...
Since the graph is acyclic, then for every vertex there exists a path to some sink, and to every vertex there exists a path from some source. So our problem can be reduced to the following: check that after running our algorithm, all vertices from the initial set of sources and sinks belong to the same strongly connect...
[ "bitmasks", "brute force", "dfs and similar" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 1000043; vector<int> g[N]; vector<int> gt[N]; vector<int> src; vector<int> snk; int reach[20]; int used[N]; void dfs(int x) { if(used[x]) return; used[x] = 1; for(auto y : g[x]) dfs(y); } int main() { int n, m; scanf("%d %d", &n, &m); ...
1037
A
Packets
You have $n$ coins, each of the same value of $1$. Distribute them into packets such that any amount $x$ ($1 \leq x \leq n$) can be formed using some (possibly one or all) number of these packets. Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the si...
The best possible way to distribute the coins is to create packets with coins $1, 2, 4, \ldots 2^k$ with maximum possible $k$ such that $2\cdot 2^k-1 \le n$. Using them, we can make all possible numbers which can be written using first $k+1$ bits in binary representation. For representing the remaining numbers, we must...
[ "constructive algorithms", "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int k=1,z=0; while(true) { if(n>0) z++; else break; n-=k; k*=2; } cout<<z; return 0; }
1037
B
Reach Median
You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$. The median of the array with odd leng...
For changing the median of the array, sort the given array and then the best possible candidate for making median is the middle element, because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger. Complexity: $O(NLog...
[ "greedy" ]
1,300
#include<bits/stdc++.h> using namespace std; int main() { int n,S; cin>>n>>S; vector<int> a(n); for(int i=0;i<n;i++) cin>>a[i]; long long z=LLONG_MAX; sort(a.begin(),a.end()); long long fh=0,sh=0; for(int i=0;i<n/2;i++) { if(a[i]>S) fh+=a[i]-S; if(a[n-1-i]<S) sh+=S-a[n-1-i]...
1037
C
Equalize
You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$: - Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$. - Select any arbi...
This can be seen that to minimize the cost, we should use the swap operation only when there are two consecutive positions(and with opposite values) to fix. For all other positions to fix, we can use the flip operation. Complexity: $O(N)$
[ "dp", "greedy", "strings" ]
1,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<ll,int> pli; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pll> vpll; #define F first #define S second typedef vector<pli> vpli; #define hell 1000...
1037
D
Valid BFS?
The BFS algorithm is defined as follows. - Consider an undirected graph with vertices numbered from $1$ to $n$. Initialize $q$ as a new queue containing only vertex $1$, mark the vertex $1$ as used. - Extract a vertex $v$ from the head of the queue $q$. - Print the index of vertex $v$. - Iterate in arbitrary order thr...
We can store the neighbors of the nodes in their adjacency lists. After that, we can sort the adjacency lists of all the nodes in the order in which they are present in the input BFS Sequence. Now we can do the standard BFS traversal starting from node $1$ and check if this BFS traversal is same as the input BFS Sequen...
[ "dfs and similar", "graphs", "shortest paths", "trees" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<ll,int> pli; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pll> vpll; #define F first #define S second typedef vector<pli> vpli; #define hell 1000...
1037
E
Trips
There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: -...
Scan the list of all the edges and create a set S of pair<int,int> (degree of node, id of node), now keep deleting elements from set till degree of smallest element of S is less than k, while deleting a node u, update the set S using adjacency list of u i.e. all elements v which are in S and adj(u) 1. delete (degree[v]...
[ "graphs" ]
2,200
/* [ C O D E T I L L I N F I N I T Y ] */ #include <set> #include <map> #include <list> #include <ctime> #include <deque> #include <queue> #include <bitset> #include <vector> #include <list> #include <stack> #include <random> #include <string> #include <numeric> ...
1037
F
Maximum Reduction
Given an array $a$ of $n$ integers and an integer $k$ ($2 \le k \le n$), where each element of the array is denoted by $a_i$ ($0 \le i < n$). Perform the operation $z$ given below on $a$ and print the value of $z(a,k)$ modulo $10^{9}+7$. \begin{verbatim} function z(array a, integer k): if length(a) < k: return 0 else:...
For each element $a[i]$, find maximum $r$ such that $a[i]>a[j]$ for every $i \leq j \leq r$ and minimum $l$ such that $a[i]>a[j]$ for every $l \leq j \leq i$. Now, let us count the no. of times $a[i]$ contributes to our answer, which can be calculated as (the no. of subsegments of length $k$ which contain $i$)+(the no....
[ "combinatorics", "data structures", "math" ]
2,500
#include <bits/stdc++.h> #define pb push_back #define hell 1000000007 #define endl '\n' #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; int n,k,A[1000005],l[1000005],r[1000005],ans; int mul(int x,int y){ return (1LL*x*y)%hell; } void solve(){ cin>>n>>k; rep(i,0,n){ ...
1037
G
A Game on Strings
Alice and Bob are playing a game on strings. Initially, they have some string $t$. In one move the first player selects the character $c$ present in $t$ and erases all it's occurrences in $t$, thus splitting $t$ into many smaller strings. The game then goes independently with each of the strings — to make the move pla...
Say, we have a string $s$. For each character, say $c$, $s$ has $c$ at $k$ positions $(a_1,a_2,...,a_k)$. Now, if we calculate grundy for strings $s[a_i+1:a_(i+1)-1]$ for $1 \leq i < k$, and also for every prefix and suffix for such strings, we can calculate the result using grundy. For a query $[l,r]$, we can iterate ...
[ "games" ]
3,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; const int M = 1e5 + 239; const int alf = 26; int n, q; string s; int posr[alf][M], posl[alf][M], dpl[alf][M], dpr[alf][M], z[alf][M]; int k, kols[alf], id[M]; inline int gett_slow(int l, int r) { int ...
1037
H
Security
Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings. Initially, they have a string $s$ consisting of lowercase English letters. Now they want to choose $q$ strings using the following steps, and you are to help them. -...
The solution does the following: 1. Build the suffix tree of the whole string (we can construct a suffix tree in $O(|S|log|S|)$ time using Suffix Array and LCP Array or in O($|S|$) using any well known algorithm like Ukkonen's algorithm). 2. Note that in a suffix tree, any path from root to leaf is a suffix of the give...
[ "data structures", "string suffix structures" ]
3,200
#include <cstring> #include <vector> #include <algorithm> #include <map> #include <iostream> using namespace std; #define ve vector #define MaxN 500010 #pragma warning(disable:4996) /* Persistent segment tree */ int Slen=100001; const int SZ = MaxN * 21; int seg_tree[SZ], L_ptr[SZ], R_ptr[SZ], Next = 1; int add(int c, ...
1038
A
Equality
You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase. A subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "...
First we need to find the frequencies of the first $k$ alphabets in the string. Let the minimum frequency among these frequencies be $m$. Then we cannot select $m+1$ characters of one kind, and we can definitely select $m$ characters of each kind, hence the answer is given by $\mathrm{min}$(frequency of first $k$ chara...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" int n, k; string s; int f[26]; int32_t main() { IOS; cin>>n>>k>>s; for(auto &it:s) f[it-'A']++; int ans=f[0]; for(int i=0;i<k;i++) ans=min(ans, f[i]); ans*=k; cout<<ans; return...
1038
B
Non-Coprime Partition
Find out if it is possible to partition the first $n$ positive integers into two \textbf{non-empty} disjoint sets $S_1$ and $S_2$ such that: \begin{center} $\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$ \end{center} Here $\mathrm{sum}(S)$ denotes the sum of all elements present in set $S$ and $\mathrm{gcd}$...
There are many ways to solve this question. The easiest way perhaps was to note that the sum of first $n$ numbers is given by $\frac{n*(n+1) }{2}$, and one of $\frac{n}{2}$ or $\frac{n+1}{2}$ has to be an integer, suppose $k$. Then we can partition the numbers into two sets, one containing $k$ and the other containing ...
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1e5+5; int32_t main() { IOS; int n; cin>>n; if(n<=2) { cout<<"No"; return 0; } else { cout<<"Yes"<<endl; int k=(n%2==0)?(n/2):((n+1)/2); ...
1038
C
Gambling
Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an ele...
This problem was greedy. First, it is obvious that both the players will try to either take their own maximum value or remove the opponent's maximum value. Hence, the arrays should be sorted and two pointers should be maintained to keep track of how many elements from each array have been counted/removed already. In ev...
[ "greedy", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1e5+5; int n; int a[N], b[N]; int32_t main() { IOS; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) cin>>b[i]; sort(a+1, a+n+1);...
1038
D
Slime
There are $n$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it. Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $x$ eats a slime with a value $y$, the eaten slime disappears,...
For every slime, its value will either be added in the final answer or subtracted. Let us give each slime a sign $+$ or $-$ to denote whether its value will be added or subtracted. The key observation to solving the problem is that any combination of $+$ and $-$ is obtainable, except where all signs are $+$ or all are ...
[ "dp", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=5e5+5; int n, minval=1e9, ans=0; int a[N]; bool checkpos=0, checkneg=0; int32_t main() { IOS; cin>>n; if(n==1) { int k; cin>>k; cout<...
1038
E
Maximum Matching
You are given $n$ blocks, each of them is of the form [color$_1$|value|color$_2$], where the block can also be flipped to get [color$_2$|value|color$_1$]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is va...
Create a graph with $4$ nodes $1-4$ representing the colors. Then the value of a block serves as an edge between the two colors of that block. Then the question reduces to finding an euler tour in the graph with the maximum sum of edges traveled. An euler tour may not exist with all the given edges, so the question is:...
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs" ]
2,400
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1005; const int M=16; struct data { int c1, c2, val, idx; bool operator<(data &b) { return val<b.val; } }; int n, sum=0, ans=0; bool ban[N], vis...
1038
F
Wrap Around
You are given a binary string $s$. Find the number of distinct cyclical binary strings of length $n$ which contain $s$ as a substring. The cyclical string $t$ contains $s$ as a substring if there is some cyclical shift of string $t$, such that $s$ is a substring of this cyclical shift of $t$. For example, the cyclic...
The idea was to solve the problem using Dynamic Programming. The constraints of the question were set low to allow even the most basic Dynamic Programming approaches to pass (see the author's solution to see an easy, but time-costly implementation). The solution idea was to use $2n^4$ DP with 4 states: $DP[A][B][C][D]$...
[ "dp", "strings" ]
2,900
// 2018, Sayutin Dmitry. #include <bits/stdc++.h> using std::cin; using std::cout; using std::cerr; using std::vector; using std::map; using std::array; using std::set; using std::string; using std::pair; using std::make_pair; using std::min; using std::abs; using std::max; using std::unique; using std::sor...
1039
A
Timetable
There are two bus stops denoted A and B, and there $n$ buses that go from A to B every day. The shortest path from A to B takes $t$ units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route. At each station one can find a sorted list of moments of time wh...
If there is at least one valid ordering $p$'s (and it surely exists since the $x$ is defined), then the ordering $p_i = i$ is also valid. Hence if for some $i$ doesn't hold $x_i \ge i$ then the answer is no. Also, from this follows that $b_i \ge a_i + t$. Otherwise, what it means that $x_i = c$? It means that there is ...
[ "constructive algorithms", "data structures", "greedy", "math" ]
2,300
null
1039
B
Subway Pursuit
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontr...
Notice that we can make segment in which we are located small enough using binary search. Let $[l; r]$ be the last segment about which we knew for sure that train is in it (at the beginning it's $[1; n]$). Let $m = \frac{l + r}{2}$. Let's ask about segment $[l; m]$. If we receive answer <<YES>>, after this query train ...
[ "binary search", "interactive", "probabilities" ]
2,100
null
1039
C
Network Safety
The Metropolis computer network consists of $n$ servers, each has an encryption key in the range from $0$ to $2^k - 1$ assigned to it. Let $c_i$ be the encryption key assigned to the $i$-th server. Additionally, $m$ pairs of servers are directly connected via a data communication channel. Because of the encryption algo...
Consider a virus containing a fixed number $x$. Let's investigate two servers connected by a data communication channel, denoting their encryption keys equal as $a$ and $b$ respectively. Since $a \neq b$, it follows that $a \oplus x \neq b \oplus x$. Therefore, if the servers are infected simultaneously the channel rem...
[ "dfs and similar", "dsu", "graphs", "math", "sortings" ]
2,200
null
1039
D
You Are Given a Tree
A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths $k$-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly $k$ vertices. You are given a tree with $n$ vertices. For each ...
Let's examine a solution in $O(n^2)$ first. Introudce a dynamic programming on subtree, the dp of the vertex is the number of paths, which can be taken from the subtree and the maximum length of incomplete path, which ends exactly in vertex v. Notice that this dp can be maximised as pair - the more of complete paths th...
[ "data structures", "dp", "trees" ]
2,800
null
1039
E
Summer Oenothera Exhibition
While some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there. The exhibition consists of $l = 10^{100}$ Oenothera species arranged in a row and consec...
Let's reconsider this task in terms of segments: we need to split sequence of photos-segments into minimum number of contiguous groups such that there exists a subsegment in each group of length $k$, which contains inside of each segment of the group. It's easy to see that if we move right edge of each segment to the l...
[ "data structures" ]
3,400
null
1040
A
Palindrome Dance
A group of $n$ dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future. O...
Consider a pair of dancers located symmetrically with respect to the center of the stage. If they already have different suits, the answer is definitely "impossible". If they both have same suits, they are fine. If one of them doesn't have a suit, buy him a matching one. Finally, if both don't have suits, buy them two ...
[ "greedy" ]
1,000
null
1040
B
Shashlik Cooking
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over. This time Miroslav laid out $n$ skewers parallel to each other, and enumerated them with consecutive integers from $1$ to $n$ in order from left...
The funny thing about this problem that it is entirely based on real facts, in the real life the $k$ was equal to $1$ and one skewer really turned two more. So it is easy to see, that answer is at least $\lceil \frac{n}{2k + 1} \rceil$ (because in smaller number of operations we wouldn't simply able to touch all skewer...
[ "dp", "greedy", "math" ]
1,300
null
1041
A
Heist
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number $x$. For example, if $x = 4$ and there were $3$ keyboards in the store, then the devices had indices $4$, $5$ and $6$, and if $x = 10$ and there were $7$ of them the...
Let $x$ - the minimal number from the given numbers and $y$ - the maximal. So we consider that $x$ and $y$ were minimal and maximal keyboard numbers before the heist. All given numbers are distinct, so the answer is $y - x + 1 - n$ (initial number of the keyboards is $(y - x + 1)$ minus the remaining number of keyboard...
[ "greedy", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; int mn = 1e9, mx = 0; for (int i = 1; i <= n; i++){ int x; cin >> x; mn = min(mn, x); mx = max(mx, x); } cout << max(0, (...
1041
B
Buying a TV Set
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $...
Firstly let's make $x$ and $y$ coprime. To do so, we calculate $g = gcd(x, y)$ and then divide both numbers by $g$. Then the pair $(w, h)$ is included in the answer if the following conditions are met: $w \le a$, $h \le b$, and there exists some positive integer $k$ such that $w = kx$ and $h = ky$. Furthermore, each su...
[ "math" ]
1,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll a, b, c, d; cin >> a >> b >> c >> d; ll gc = __gcd(c, d); c /= gc; d /= gc; cout << min(a/c, b/d); }
1041
C
Coffee Break
Recently Monocarp got a job. His working day lasts exactly $m$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $n$ minutes $a_1, a_2, \dots, a_n$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one min...
Let put in set the pairs in the following format: $a_i$ - the time for $i$-th break and the number of this break in the input data. So, we got pairs sorted by $a_i$. While set contains elements we will determine the breaks, which should be done in a single day. For the next day the first break should be dine in the tim...
[ "binary search", "data structures", "greedy", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 200100; set<pair<int, int> > q; int ans[N], n, a[N], m, k; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m >> k; for (int i = 1; i <= n; i++){ cin >> a[i]; q.insert({a[i], i}); }...
1041
D
Glider
A plane is flying at a constant height of $h$ meters above the ground surface. Let's consider that it is flying from the point $(-10^9, h)$ to the point $(10^9, h)$ parallel with $Ox$ axis. A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may star...
At first, let's prove that it is always optimal to jump out at the beginning of any ascending air flows: if his point of jump is out of any air flow, he can move his point to $+1$ - answer will not decrease, in the same way, if his point of jump in some air flow but not in its beginning, he can move his point to $-1$. ...
[ "binary search", "data structures", "two pointers" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; const int N = 200 * 1000 + 555...
1041
E
Tree Reconstruction
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this ...
First of all, if there exists some $b_i < n$, then the answer is clearly NO. Then let's consider that every $b_i = n$ and analyze only the values of $a_i$ (and furthermore, let's sort all values of $a_i$ beforehand). Suppose that we have constructed a tree satisfying all the requirements and rooted it at vertex $n$. Th...
[ "constructive algorithms", "data structures", "graphs", "greedy" ]
1,900
#include<bits/stdc++.h> using namespace std; const int N = 200043; int cnt[N]; int main() { int n; scanf("%d", &n); for(int i = 0; i < n - 1; i++) { int x, y; scanf("%d %d", &x, &y); if(y != n) { puts("NO"); return 0; } cnt[x]++; } int cur = 0; for(int i = 1; i < n; i++) { ...
1041
F
Ray in the tube
You are given a tube which is reflective inside represented as two non-coinciding, but parallel to $Ox$ lines. Each line has some special integer points — positions of sensors on sides of the tube. You are going to emit a laser ray in the tube. To do so, you have to choose \textbf{two} integer points $A$ and $B$ on th...
At first, $y$ coordinates don't matter. Let $dx$ be signed difference between $x$ coordinates of $B$ and $A$, then on the first line all points with coordinates $x_A + dx \cdot (2k)$ will be chosen, and on the second line all points with coordinates $x_A + dx \cdot (2k + 1)$ will be chosen. Let's prove that it is alway...
[ "data structures", "divide and conquer", "dp", "math" ]
2,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e...
1042
A
Benches
There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available. Let $k$ be the maximum number of people sitting on one bench after additiona...
The maximum value of $k$ should be determined in the following way: let's find the maximum number of people already sitting on the same bench (i. e. the maximum value in the array $a$). Let this number be $t$. Then if all additional $m$ people will seat on this bench, we will get the maximum value of $k$, so the answer...
[ "binary search", "implementation" ]
1,100
#include <set> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <cassert> using namespace std; const int N = 100 + 13; int n, m; int a[N]; int main() { cin >> n >> m; for (int i = 0; i < n; i++) { cin >> a[i]; } int ans2 = *max_element(a, a + n) + m; ...
1042
B
Vitamins
Berland shop sells $n$ kinds of juices. Each juice has its price $c_i$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it. Petya knows that he needs all three types of vitamin...
Let's calculate the minimum cost of the juice containing only the vitamin "A", only the vitamin "B" and only the vitamin "C". Also let's calculate the minimum cost of the juice containing all three vitamins. If there is at least one juice containing only the vitamin "A", at least one juice containing only the vitamin "...
[ "bitmasks", "brute force", "dp", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int n; map<string, int> was; inline void read() { cin >> n; for (int i = 0; i < n; i++) { int c; string s; cin >> c >> s; sort(s.begin(), s.end()); if (was.count(s) == 0) { was[s] = c; } else { was[s] = min(was[s], c); } } } ...
1042
C
Array Product
You are given an array $a$ consisting of $n$ integers. You can perform the following operations with it: - Choose some positions $i$ and $j$ ($1 \le i, j \le n, i \ne j$), write the value of $a_i \cdot a_j$ into the $j$-th cell and \textbf{remove the number} from the $i$-th cell; - Choose some position $i$ and \textbf...
There are several cases in the problem. Let the number of zeroes in the array be $cntZero$ and the number of negative elements be $cntNeg$. Also let $maxNeg$ be the position of the maximum negative element in the array, or $-1$ if there are no negative elements in the array. Let the answer part be the product of all th...
[ "constructive algorithms", "greedy", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); int cntneg = 0; int cntzero = 0; vector<int> used(n); int po...
1042
D
Petya and Array
Petya has an array $a$ consisting of $n$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array. Now he wonders what is the number of segments in his ...
Let's reformulate the problem. Now the problem is to calculate the difference between the prefix sums to the right border and to the left border instead of the sum on the segment. Let $pref[i] = \sum\limits_{j=1}^{i} a[j]$, a $pref[0] = 0$. Then the answer to the problem is $\sum\limits_{L=1}^{n}\sum\limits_{R=L}^{n} p...
[ "data structures", "divide and conquer", "two pointers" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; int n; long long T; int a[N]; int f[N]; void upd(int x){ for (int i = x; i < N; i |= i + 1) ++f[i]; } int get(int x){ int res = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) ...
1042
E
Vasya and Magic Matrix
Vasya has got a magic matrix $a$ of size $n \times m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $m$ from left to right. Let $a_{ij}$ be the element in the intersection of the $i$-th row and the $j$-th column. Vasya has also got a chip. Initially, the ...
Let's iterate over all the elements of the matrix in order of increasing their values and calculate the expected value for these elements to solve the problem. Suppose that now we consider the element at intersection of the $R$-th row and the $C$-th column. Let the elements having value less than the value of the curre...
[ "dp", "math", "probabilities" ]
2,300
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 1009; int mul(int a, int b){ return int(a * 1LL * b % MOD); } void upd(int &a, int b){ a += b; while(a >= MOD) a -= MOD; while(a < 0) a += MOD; } int bp(int a, int n){ int res = 1; for(; n > 0; n >>= 1){ if(n & 1) res = m...
1042
F
Leaf Sets
You are given an undirected tree, consisting of $n$ vertices. The vertex is called a leaf if it has exactly one vertex adjacent to it. The distance between some pair of vertices is the number of edges in the shortest path between them. Let's call some set of leaves beautiful if the maximum distance between any pair ...
Let's use the following technique, which is pretty common for tree problems. Let the root of the tree be some none-leaf vertex. Run dfs from the root and let the vertex yield all the resulting sets in the optimal answer for its subtree. For each vertex you iterate over its children and merge the yielded sets. The first...
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy", "sortings", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(a) int((a).size()) const int N = 1000 * 1000 + 13; int n, k; vector<int> g[N]; int ans; int dfs(int v, int p = -1){ if (g[v].size() == 1) return 0; vector<int> cur; for (auto u : g[v]){ if (u == p)...
1043
A
Elections
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are $n$ students in the school. Each student has exactly $k$ votes and is obligated to use all of them. So Awruk knows that if a person gives $a_i$ votes for Elodreip, than he will get exactly $k - a_i$ vote...
We can observe that result cannot exceed $201$ - Awruk gets at least $101$ votes from one person and Elodreip cannot get more than $100$ votes from one person. So we can iterate over every possible integer from $1$ to $201$ and check if Awruk wins with $k$ set to this integer. We have to remember that $k$ - $a_{i}$ is ...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int n; int mx = 0, sum = 0; int main(){ scanf("%d", &n); for(int i = 1; i <= n; ++i){ int a; scanf("%d", &a); mx = max(mx, a); sum += a; } sum *= 2; sum += n; sum /= n; printf("%d", max(sum, mx)); return 0; }
1043
B
Lost Array
Bajtek, known for his unusual gifts, recently got an integer array $x_0, x_1, \ldots, x_{k-1}$. Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $a$ of length ...
First, let's observe that we can replace array $a_{i}$ with array $b_{i}$ = $a_{i}$ $-$ $a_{i - 1}$, because all we care about are differences between neighboring elements. Now, we can see that our lost array can have length $d$ if and only if for every $j$ such that $j$ $+$ $d$ $ \le $ $n$, $b_{j}$ $=$ $b_{j + d}$. So...
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int N = 1007; int n; int in[N]; bool ok(int d){ for(int i = 0; i + d < n; ++i) if(in[i + 1] - in[i] != in[i + d + 1] - in[i + d]) return false; return true; } int main(){ scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", &in[i]); vector <int>...
1043
C
Smallest Word
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting. Today, when IA looked at the fridge, she noticed that...
Basically in problem we are given a word in which for every $i$ we can reverse prefix of first $i$ elements and we want to get the smallest lexicographically word. We will show that we can always achieve word in form $a^{j}b^{n - j}$. Let's say that we solved our problem for prefix of length $i$ and for this prefix we ...
[ "constructive algorithms", "greedy", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 1007; string s; bool write[N]; int main(){ cin >> s; for(int i = 1; i < s.size(); ++i) if(s[i] == 'a'){ write[i - 1] ^= 1; write[i] = 1; } for(int i = 0; i < s.size(); ++i) printf("%d%c", write[i], i + 1 == (int)s.size() ? '\n' : ' '); re...
1043
D
Mysterious Crime
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients...
Deleting prefix and suffix is nothing more than taking a subarray. If subarray is common for all permutations then it has to appear in first permutation. We renumber all permutations such that first permutation is $1$, $2$, ..., $n$ $-$ $1$, $n$. Now for every $i$ in every permutation we count how long is subarray star...
[ "brute force", "combinatorics", "math", "meet-in-the-middle", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; typedef long long int LL; const int N = 1e5 + 7; int n, m; int mn[N]; int ren[N]; int perm[15][N]; int main(){ scanf("%d %d", &n, &m); for(int i = 1; i <= m; ++i) for(int j = 1; j <= n; ++j) scanf("%d", &perm[i][j]); for(int i = 1; i <= n; ++i) ren[perm[1][...
1043
E
Train Hard, Win Easy
Zibi is a competitive programming coach. There are $n$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems. Rules of scoring also a...
Let's compute result if there are no edges, we can add them later. If there are no edges then result for pair ($i$, $j$) is min($x_{i}$ $+$ $y_{j}$, $x_{j}$ $+$ $y_{i}$). First let's fix $i$ for which we want to compute result. Then calculate result with all pairs $j$ such that $x_{i}$ $+$ $y_{j}$ $ \le $ $x_{j}$ $+$ $...
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long int LL; #define st first #define nd second #define PII pair <int, int> const int N = 3e5 + 7; int n, m; PII diff[N]; int place[N]; vector <int> G[N]; LL ans[N]; int x[N], y[N]; LL pref[N], suf[N]; int main(){ scanf("%d %d", &n, &m); for(int i = 1;...
1043
F
Make It One
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $n$ integers $a_i$. It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected e...
First let's observe that if there exists valid subset then it's size is at most $7$ (because product of $7$ smallest primes is bigger then $3 * 10^{5}$). Let's define $dp[i][j]$ - number of ways to pick $i$ different elements such that their gcd is equal to $j$. We can use inclusion--exclusion principle to calculate it...
[ "bitmasks", "combinatorics", "dp", "math", "number theory", "shortest paths" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 7; int n; int cnt[N]; int roz[N]; int dist[N]; queue <int> Q; vector <int> dv[N]; int base(int a){ int ret = 1; while(a > 1){ if(ret%roz[a] != 0) ret *= roz[a]; a /= roz[a]; } return ret; } void getEdges(int u, int d){ vector <int> cur...
1043
G
Speckled Band
Ildar took a band (a thin strip of cloth) and colored it. Formally, the band has $n$ cells, each of them is colored into one of $26$ colors, so we can denote each color with one of the lowercase letters of English alphabet. Ildar decided to take some segment of the band $[l, r]$ ($1 \le l \le r \le n$) he likes and cu...
Let's solve the problem for some string $s$ for any time. Let's say, that partition of string $s$ into $k$ strings $s_{1s}_{2}... s_{i1}, s_{i1 + 1}... s_{i2}, ..., {s_{ik - 1 + 1}}... s_{ik}$ is good if at least one pair of this strings are equal. We want to find a minimal possible number of different strings in all g...
[ "data structures", "divide and conquer", "hashing", "string suffix structures", "strings" ]
3,500
#include <bits/stdc++.h> using namespace std; #define TIME (clock() * 1.0 / CLOCKS_PER_SEC) const int BIG = 1e9 + 239; const int M = 2 * 1e5 + 239; const int L = 19; const int A = 30; const int T = (1 << 19); const int two = 2; int flm[two][M]; inline void z_function(string &s, int c) { int n = s.length(); flm[c...
1044
A
The Tower is Going Home
On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the...
Observation 1. If we remove all the horizontal spells, than the rook can move straightforward up to the upper side of the field. So the only purpose of removing the vertical spells is to reduce the number of horizontal spells to be removed. Observation 2. If we want to remove the $i$-th vertical spell, then we should a...
[ "binary search", "two pointers" ]
1,700
null
1044
B
Intersecting Subtrees
You are playing a strange game with Li Chen. You have a tree with $n$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you \textbf{independently} labeled the vertices from $1$ to $n$. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e.,...
I'll split this into two parts, first is the solution, second is why it works. The intended solution only uses two questions. Choose an arbitrary $y_j$, and ask "B y_j". Let the response be $R$. Find a node $x_i$ that is the closest to node $R$. This can be done with a BFS or DFS. Ask "A x_i". Let the response be $Q$. ...
[ "dfs and similar", "interactive", "trees" ]
1,900
null
1044
C
Optimal Polygon Perimeter
You are given $n$ points on the plane. The polygon formed from all the $n$ points is \textbf{strictly convex}, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1$ to $n$, in clockwise order. We define the distance between two ...
I will show 2 solutions, both of which work in $\mathcal{O}(n)$ time. First, it is not hard to notice that we can only consider polygons that are convex. Observation: For a convex polygon, the given definition of "polygon perimeter" is equivalent to the perimeter of the bounding rectangle (aligned with the axis), of ou...
[ "dp", "geometry" ]
2,100
null
1044
D
Deduction Queries
There is an array $a$ of $2^{30}$ integers, indexed from $0$ to $2^{30}-1$. Initially, you know that $0 \leq a_i < 2^{30}$ ($0 \leq i < 2^{30}$), but you do not know any of the values. Your task is to process queries of two types: - 1 l r x: You are informed that the \textbf{bitwise xor} of the subarray $[l, r]$ (ends...
First, let's learn how to handle information we have not recieved in updates. Let the function $W(l, r)$ be equal to the xor of the subarray $[l, r]$. Also, we define $W(l, r) = W(r, l)$. Assume 3 indicies $a \leq b \leq c$. There are 2 rules: $W(a, b) \oplus W(b + 1, c) = W(a, c)$. $W(a, c) \oplus W(b, c) = W(a, b - 1...
[ "data structures", "dsu" ]
2,400
null
1044
E
Grid Sort
You are given an $n \times m$ grid. Each grid cell is filled with a unique integer from $1$ to $nm$ so that each integer appears exactly once. In one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the followin...
The solution is more of a coding one than an algorithmic one. There are many different approaches, and it's important to be careful in how it is implemented. I'll explain one of the implementations. First, we can always move a particular block left, up, down, or right with an appropriate 2x2 square around it. Let's cod...
[ "implementation" ]
3,100
null
1044
F
DFS
Let $T$ be a tree on $n$ vertices. Consider a graph $G_0$, initially equal to $T$. You are given a sequence of $q$ updates, where the $i$-th update is given as a pair of two distinct integers $u_i$ and $v_i$. For every $i$ from $1$ to $q$, we define the graph $G_i$ as follows: - If $G_{i-1}$ contains an edge $\{u_i, ...
Let's consider an arbitrary run of DFS producing some tree. Let's root the tree at the starting vertex. It can be shown that on a directed graph, there are only two types of edges. The first are the tree edges (those are the ones that are used to visit a new vertex). The second are edges which, upon being traversed, le...
[ "data structures" ]
2,700
null
1047
A
Little C Loves 3 I
Little C loves number «3» very much. He loves all things about it. Now he has a positive integer $n$. He wants to split $n$ into $3$ positive integers $a,b,c$, such that $a+b+c=n$ and none of the $3$ integers is a multiple of $3$. Help him to find a solution.
If $n - 2$ is not a multiple of $3$, $a = 1, b = 1, c = n - 2$ is OK. Otherwise, $a = 1, b = 2, c = n - 3$ is OK.
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d",&n); if((n-2)%3)printf("1 1 %d",n-2); else printf("1 2 %d",n-3); }
1047
B
Cover Points
There are $n$ points on the plane, $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$. You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the tri...
To cover a point $(x_{i}, y_{i})$, the length of the shorter side of the triangle should be at least $x_{i} + y_{i}$. So the answer is $max(x_{i} + y_{i})$.
[ "geometry", "math" ]
900
#include<bits/stdc++.h> using namespace std; int main() { int n,x,y,ans=0; scanf("%d",&n); while(n--)scanf("%d%d",&x,&y),ans=max(ans,x+y); printf("%d",ans); }
1051
A
Vasya And Password
Vasya came up with a password to register for EatForces — a string $s$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits. But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin...
There are just a few general cases in the task to consider: If the password $s$ is already valid, nothing has to be changed, just print $s$. Try to change exactly one character, iterate over all positions in $s$ and all three options for character (any digit, any lowercase or uppercase Latin letter). After the replacem...
[ "greedy", "implementation", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; string s; bool ok(string t){ int msk = 0; for(int i = 0; i < int(t.size()); ++i){ if(isupper(t[i])) msk |= 1; if(islower(t[i])) msk |= 2; if(isdigit(t[i])) msk |= 4; } return msk == 7; } int main() { //freopen("input.txt", "r", stdin); ...
1051
B
Relatively Prime Pairs
You are given a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \le 3 \cdot 10^5$ and $(r - l)$ is always odd. You want to split these numbers into exactly $\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number ...
Numbers with the difference of $1$ are always relatively prime. That's the only thing I should mention for this editorial. Overall complexity: $O(r - l)$.
[ "greedy", "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int main() { long long l, r; scanf("%lld%lld", &l, &r); puts("YES"); forn(i, (r - l) / 2 + 1) printf("%lld %lld\n", l + i * 2, l + i * 2 + 1); }
1051
C
Vasya and Multisets
Vasya has a multiset $s$ consisting of $n$ integer numbers. Vasya calls some number $x$ nice if it appears in the multiset exactly once. For example, multiset $\{1, 1, 2, 3, 3, 3, 4\}$ contains nice numbers $2$ and $4$. Vasya wants to split multiset $s$ into two multisets $a$ and $b$ \textbf{(one of which may be empty...
Write down all the numbers, which appear exactly once, let there be $k$ of them. If $k$ is even, put the first $\frac{k}{2}$ of them into the first multiset and put the other $\frac{k}{2}$ into the second multiset. All the other numbers (which appear more than once) also go into the first multiset. The only nice number...
[ "brute force", "dp", "greedy", "implementation", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 109; int n; int a[N]; map<int, int> m; set <int> s[2]; int main() { int n; cin >> n; for(int i = 0; i < n; ++i){ cin >> a[i]; m[a[i]]++; } int pos = 0; for(auto p : m) if(p.second == 1){ s[pos].insert(p.first); pos = 1 - pos; } if...
1051
D
Bicolorings
You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white. Two cells are considered neighbours if they have a \textbf{common border} and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a n...
The problem is about counting the number of some combinatoric objects. Thus, dynamic programming is always the answer. Let $dp[i][j][mask]$ be the number of beautiful bicolorings of the first $i$ columns such that $j$ components are already created and can't be modified and the colors of the $i$-th column are determine...
[ "bitmasks", "dp" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 1000 + 7; const int MOD = 998244353; int dp[N][2 * N][4]; int add(int a, int b){ return (a + b) % MOD; } bool full(int mask){ return (mask == 0 || mask == 3); } int get(int mask, int nmask){ int cn...
1051
E
Vasya and Big Integers
Vasya owns three big integers — $a, l, r$. Let's define a partition of $x$ such a sequence of strings $s_1, s_2, \dots, s_k$ that $s_1 + s_2 + \dots + s_k = x$, where $+$ is a concatanation of strings. $s_i$ is the $i$-th element of the partition. For example, number $12345$ has the following partitions: ["1", "2", "3"...
Let's use dynamic programming to solve the problem. Let $dp_x$ be the number of correct partitions for the long integer $a_x a_{x+1} \dots a_{n}$. It's easy to see that if we have two big integers without leading zeroes, we know the lengths of these integers, and these lengths are not equal, then we can determine which...
[ "binary search", "data structures", "dp", "hashing", "strings" ]
2,600
#include<bits/stdc++.h> using namespace std; #define sz(a) (int)(a.size()) const int N = int(1e6) + 9; const int MOD = 998244353; int n; string s, l, r; int dp[N]; int sumDP[N]; int sum(int a, int b){ a += b; if(a >= MOD) a -= MOD; return a; } vector <int> z_function(string s){ int n = sz(s); vector <int> z(...
1051
F
The Shortest Statement
You are given a weighed undirected \textbf{connected} graph, consisting of $n$ vertices and $m$ edges. You should answer $q$ queries, the $i$-th query is to find the shortest distance between vertices $u_i$ and $v_i$.
Firstly let's find any spanning tree and root it at any vertex. For each vertex we calculate the distance to the root (let it be $h_v$ for vertex $v$). There are no more than $21$ edges that don't belong to the tree. For each of these edges, let's run Dijkstra's algorithm from some vertex incident to this edge. Suppose...
[ "graphs", "shortest paths", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 300 * 1000 + 9; const int LOGN = 19; const int M = 21; const long long INF64 = 1e18; int n, m, q; vector <pair<int, int> > g[N]; int p[LOGN][N]; int tin[N], tout[N], T; long long h[N]; set <pair<int, int> > badEdges; long long d[M + M][N]; bool u[N]; void ...
1051
G
Distinctification
Suppose you are given a sequence $S$ of $k$ pairs of integers $(a_1, b_1), (a_2, b_2), \dots, (a_k, b_k)$. You can perform the following operations on it: - Choose some position $i$ and \textbf{increase} $a_i$ by $1$. That can be performed only if there exists at least one such position $j$ that $i \ne j$ and $a_i = ...
Let's firstly try to come up with some naive solution. Suppose we have a list $S$ and want to calculate $f(S)$ for it. Let's sort this list, comparing the pairs by their values of $a_i$, and then process them one-by-one. We will divide this list into some parts (we will call them components) with the following process:...
[ "data structures", "dsu", "greedy" ]
2,900
#include <bits/stdc++.h> using namespace std; #define x first #define y second typedef long long li; mt19937 rnd(time(NULL)); struct node { int x; int y; li sum; int siz; node* l; node* r; node() {}; node(int x, int y, li sum, int siz, node* l, node* r) : x(x), y(y), sum(sum), siz(siz), l(l), r(r) {}; }; ...
1053
E
Euler tour
Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as $n$ acorns connected by $n - 1$ branches, such that there is exactly one way between each pair of acorns. Let's enumerat...
First let's try to find some conditions whether it is possible to recover correct euler tour. Of course for every euler tour $a_i$ $\neq$ $a_{i+1}$ and $a_1$ $=$ $a_{2n-1}$ (because we start and finish in root). Moreover if there exist four index $i_1$ $<$ $i_2$ $<$ $i_3$ $<$ $i_4$ such that $a_{i_1}$ $=$ $a_{i_3}$ and...
[ "constructive algorithms", "trees" ]
3,500
#include <bits/stdc++.h> using namespace std; #define st first #define nd second #define PII pair <int, int> const int N = 1e6 + 7; int n; int in[N]; int ans[N]; bool used[N]; vector <int> unused; int cnt; deque <PII> cur; vector <PII> getEqual; set <int> S; vector <int> place[N]; vector <pair <int, int> > order;...
1054
A
Elevator or Stairs?
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $x$, Egor on the floor $y$ (not on the same floor with Masha). The house has a staircase and an elevator. If Mas...
The time needed if we use stairs is $|x - y| \cdot t_1$. The time needed if we use elevator is $|z - x| \cdot t_2 + |x - y| \cdot t_2 + 3 \cdot t_3$. We can simply compute this values and compare them. Time complexity: $O(1)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int x, y, z, t1, t2, t3; int main() { cin >> x >> y >> z >> t1 >> t2 >> t3; if (abs(z - x) * t2 + abs(x - y) * t2 + 3 * t3 <= abs(x - y) * t1) cout << "YES"; else cout << "NO"; return 0; }
1054
B
Appending Mex
Initially Ildar has an empty array. He performs $n$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest \textbf{non-negative} integer not presented in the multiset. For example, the mex of the m...
Ildar has written an array correctly if there exists numbers $0, 1, \ldots, a_i-1$ to the left of $a_i$ for all $i$. This is equivalent to $a_i \leq max(-1, a_1, a_2, \ldots, a_{i-1}) + 1$ for all $i$. If this condition is false for some $i$ we made a mistake. So the solution is to check that $a_i \leq max(-1, a_1, a_2...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int n, a, m; int main() { ios::sync_with_stdio(0); cin >> n; m = -1; for (int i = 0; i < n; i++) { cin >> a; if (a > m + 1) { cout << i + 1; return 0; } m = max(m, a); } cout << -1; return 0; }
1054
C
Candies Distribution
There are $n$ children numbered from $1$ to $n$ in a kindergarten. Kindergarten teacher gave $a_i$ ($1 \leq a_i \leq n$) candies to the $i$-th child. Children were seated in a row in order from $1$ to $n$ from left to right and started eating candies. While the $i$-th child was eating candies, he calculated two number...
Let's note that for any $i$, the value of $(l_i + r_i)$ is equal to the number of children who got more candies than $i$-th. So, $(n - l_i - r_i)$ is equal to the number of children who got less or equal number of candies than $i$-th (including himself). So, if there exists an array $a$ satisfying the conditions, then ...
[ "constructive algorithms", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int M = 1010; int n, a[M], l[M], r[M]; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> l[i]; for (int i = 0; i < n; i++) cin >> r[i]; for (int i = 0; i < n; i++) a[i] = (n - l[i] - r[i]); for (int i = 0; i < n; i++) for (int j = 0; j < ...
1054
D
Changing Array
At a break Vanya came to the class and saw an array of $n$ $k$-bit integers $a_1, a_2, \ldots, a_n$ on the board. An integer $x$ is called a $k$-bit integer if $0 \leq x \leq 2^k - 1$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anythin...
We need to maximize the number of segments with XOR-sum of its elements not equal to 0. Let's note that the total number of segments is (n+12)=n \cdot (n+1)/2 so we need to minimize the number of segments with XOR-sum of its elements equal to 0. Let's call such segments bad. Consider the prefix XOR sums of array a. Let...
[ "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n, k; ll gett(int k) { return ((ll)k * (ll)(k - 1)) / 2LL; } int main() { cin.sync_with_stdio(0); cin >> n >> k; int a = 0; ll ans = 0; map<int, int> kol; kol[0] = 1; for (int i = 1; i <= n; i++) { int b; cin >> b; a ^= mi...
1054
E
Chips Puzzle
Egor came up with a new chips puzzle and suggests you to play. The puzzle has the form of a table with $n$ rows and $m$ columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip...
Our usual operation - is to move the last character of a string in one cell to the beginning of a string in another cell. If we do the reverse operation - to move the first character of a string in one cell to the end of a string in another cell, then it's like we will do our operation for reversed strings and at the e...
[ "constructive algorithms", "implementation", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; const int two = 2; const int N = 310; const int S = 200100; int n, m; string s[two][N][N]; int k[two]; tuple<int, int, int, int> ans[two][S]; queue<char> in[N][N]; void func(int c) { k[c] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { while ...
1054
F
Electric Scheme
Pasha is a young technician, nevertheless, he has already got a huge goal: to assemble a PC. The first task he has to become familiar with is to assemble an electric scheme. The scheme Pasha assembled yesterday consists of several wires. Each wire is a segment that connects two points on a plane with integer coordinat...
Let's reduce this problem to the problem of finding the minimum vertex cover in a bipartite graph. We need to build the following graph: in one part all horizontal segments between adjacent points by x from the set of points having the same y, in the other part all vertical segments between adjacent points by y from th...
[ "flows", "graph matchings" ]
2,700
#include <bits/stdc++.h> using namespace std; const int M = 1010; int n; vector<pair<int, int> > pt; vector<int> vx, vy; vector<int> gx[M], gy[M]; vector<tuple<int, int, int> > sh, sv; int pa[M], pb[M], ln, lm; vector<int> v[M]; bool used[M], used1[M]; vector<int> dx[M], dy[M]; bool dfs(int p) { used[p] = true...