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
1054
G
New Road Network
The king of some country $N$ decided to completely rebuild the road network. There are $n$ people living in the country, they are enumerated from $1$ to $n$. It is possible to construct a road between the house of any citizen $a$ to the house of any other citizen $b$. There should not be more than one road between any ...
Let us denote for Ai the set of sets (or secret comunities, as in our problem), which contains i-th vertex. Note that if some set Ai contains an element that does not belong to any other set Aj, it can be thrown out and it will not affect to the answer. Let's make this. Let the tree exist. Then it has a leaf (let this ...
[ "constructive algorithms", "greedy", "math" ]
3,300
#include <iostream> #include <tuple> #include <sstream> #include <vector> #include <cmath> #include <ctime> #include <bitset> #include <cassert> #include <cstdio> #include <queue> #include <set> #include <map> #include <fstream> #include <cstdlib> #include <string> #include <cstring> #include <algorithm> #include <nume...
1054
H
Epic Convolution
You are given two arrays $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{m-1}$, and an integer $c$. Compute the following sum: $$\sum_{i=0}^{n-1} \sum_{j=0}^{m-1} a_i b_j c^{i^2\,j^3}$$ Since it's value can be really large, print it modulo $490019$.
The given modulo 490019 is a prime one. Note, that value of c(i2j3), according to the Fermat's theorem, depends only on the (i2j3)mod(490019-1). The main idea is that we want to end up with something like polynomial \sum ctxt, where t would be (i2j3)mod(490019-1) and ct is sum of corresponding aibj. If we have such a ...
[ "chinese remainder theorem", "fft", "math", "number theory" ]
3,500
// 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::tuple; using std::make_tuple; using std::get; using std::min; using st...
1055
A
Metro
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home. In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $n$ stations numbered from $1$ to $n$. Bob lives near the station with number $1$, whil...
Either Bob may go directly to Alice's station, or if his train doesn't stop there, he will need to change trains as soon as possible to go in the opposite direction. It's not hard to prove that he may only need to change the trains once. If neither of the options are possible, then Bob can't come to Alice by train.
[ "graphs" ]
900
null
1055
B
Alice and Hairdresser
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic... To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice'...
Let's consider number of current non-expandable segments that have all elements more than $l$. When an element (in this case a hairline) grows up, we can recalculate this number of segments looking at the neighbours.
[ "dsu", "implementation" ]
1,300
null
1055
C
Lucky Days
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days $[l_a; r_a]$ are lucky, then there are some unlucky days: $[r_a ...
All possible shifts of Alice's and Bobs' pattern periods are the multiples of $\mathrm{gcd}(t_a, t_b)$. You want to use such a shift that the start of their lucky days is as close as possible. Also if they can't coincide precisely, you need to try shifting in such way that Alice's lucky days start before Bob's, and the...
[ "math", "number theory" ]
1,900
null
1055
D
Refactoring
Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in jus...
Let's take all variable names that have changed. First observation is that if you trim coinciding prefixes and suffixes from the original variable names and the resulting name, you will find the part that needs to be changed. We will call it "the core" of the replacement. All those parts need to be exactly the same. Ho...
[ "greedy", "implementation", "strings" ]
2,400
null
1055
E
Segments on the Line
You are a given a list of integers $a_1, a_2, \ldots, a_n$ and $s$ of its segments $[l_j; r_j]$ (where $1 \le l_j \le r_j \le n$). You need to select exactly $m$ segments in such a way that the $k$-th order statistic of the multiset of $a_i$, where $i$ is contained in at least one segment, is the smallest possible. If...
Let's find the answer using binary search. Sort segments in the order of increasing right ends. Now we are solving the following problem: how many numbers $\le x$ we cover by $m$ segments. This may be solved with a DP along the scan line. We count how many numbers can we cover using at most $j$ of the first $i$ segment...
[ "binary search", "dp" ]
2,500
null
1055
F
Tree and XOR
You are given a connected undirected graph without cycles (that is, a tree) of $n$ vertices, moreover, there is a non-negative integer written on every edge. Consider all pairs of vertices $(v, u)$ (that is, there are exactly $n^2$ such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers ...
First observation is that we may first assign a number to each vertex that is equal to xor of all values on the path from this vertex to the root (the root itself will be assigned $0$). Then the value of any path will be equal to xor of the values written in its first and last vertices. Since the order of those values ...
[ "strings", "trees" ]
2,900
null
1055
G
Jellyfish Nightmare
Bob has put on some weight recently. In order to lose weight a bit, Bob has decided to swim regularly in the pool. However, the day before he went to the pool for the first time he had a weird dream. In this dream Bob was swimming along one of the pool's lanes, but also there were some jellyfish swimming around him. It...
First of all, we will solve a simpler problem: you need to check if it is possible for Bob to swim along the whole lane without any jellyfish stinging him. The position of Bob is identified by the location of his first vertex. Let's find out what are the prohibited areas for it. If a jellyfish had no activity zone and ...
[]
3,500
null
1056
A
Determine Line
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in. During his ride, Arkady woke up several time...
This is a simple implementation problem. A tram line is suitable if it appears at all stops, i.e. exactly $n$ times. Make an array of $100$ integers and count how many times each integer appears. Then just output each index where the array hits $n$.
[ "implementation" ]
800
null
1056
B
Divide Candies
Arkady and his friends love playing checkers on an $n \times n$ field. The rows and the columns of the field are enumerated from $1$ to $n$. The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friend...
We are asked to count the number of pairs $(i, j)$ so that $(i^2 + j^2) \bmod m = 0$. Note that $(i^2 + j^2) \bmod m = ((i \bmod m)^2 + (j \bmod m)^2) \bmod m$. Thus the answer is equal for all pairs $(i, j)$ that have equal values $(i \bmod m, j \bmod m) = (x, y)$. Let's loop through all possible pairs of $(x, y)$ (th...
[ "math", "number theory" ]
1,600
null
1056
C
Pick Heroes
\begin{quote} Don't you tell me what you think that I can be \end{quote} If you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each playe...
First suppose we have the first turn. Let's look at what total power we can grab. There are two types of heroes: those who have a special pair and those who don't. In each pair, one of the heroes will go into your team and one into the other. So the maximum we can get here is the sum of powers of the best in correspond...
[ "greedy", "implementation", "interactive", "sortings" ]
1,700
null
1056
D
Decorate Apple Tree
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root. A subtree of a junction $v$ is a set...
I'll try two describe two different approaches to this problem. A more intuitive solution. We are asked to output the number of colors for all $k$, let's reverse the problem and count the maximum $k$ for all possible number of colors $c$. We can see that if we a junction is happy then all junctions in its subtree are a...
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "greedy", "sortings", "trees" ]
1,600
null
1056
E
Check Transcription
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$. The original signal $s...
The solution builds on one key observation. Suppose we know the length of $r_0$. Then, since the number of '0' and '1' is fixed and the length of the resulting string is also fixed, we know the length of $r_1$ (or know, that there is no integer-sized $r_1$ possible). So let's bruteforce the length of $r_0$, calculate t...
[ "brute force", "data structures", "hashing", "strings" ]
2,100
null
1056
F
Write The Contest
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $n$ problems and lasts for $T$ minutes. Each of the problems is defined by two positive integers $a_i$ and $p_i$ — its difficulty and the score awarded by its solution. Polycarp's experience sugge...
Firstly, if we fix some set of problems to solve, it's always optimal to solve them from the hardest one to the easiest one. That implies a solution which processes all problems and decides which of them will be solved in sorted order. Secondly, suppose Polycarp doesn't train at all, and for some fixed set of $k$ probl...
[ "binary search", "dp", "math" ]
2,500
null
1056
G
Take Metro
Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city. Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from $1$ to $n$ and there is a tunnel between any pair of consecutive stat...
There were a variety of approaches to this problem. In all of them you first have to note that there are only $n^2$ different positions describes as pairs (station, $T \bmod n$). Now if you manually perform several first steps to make $T \bmod n = 0$, you will have to perform $T / n$ large steps, each of them is to hav...
[ "brute force", "data structures", "graphs" ]
2,900
null
1056
H
Detect Robots
You successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question. There are $n$ crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without ...
The solution is sqrt decomposition. Let's divide the rides into two groups: with length greater than $R$ and with length smaller than $R$. Now let's reformulate the problem a bit: for each pair of paths you have to check the following: for each $a$ and $b$ that appear in this order in both paths, the next crossroads af...
[ "data structures", "strings" ]
3,200
null
1059
A
Cashier
Vasya has recently got a job as a cashier at a local store. His day at work is $L$ minutes long. Vasya has already memorized $n$ regular customers, the $i$-th of which comes after $t_{i}$ minutes after the beginning of the day, and his service consumes $l_{i}$ minutes. It is guaranteed that no customer will arrive whil...
There are only $n + 1$ possible segments of time when Vasya can take breaks: between the consecutive clients, before the first client, and after the last client. If the length of the $i$-th such segment is $s$, Vasya may take at most $\left \lfloor \frac{s}{a}\right\rfloor$ breaks, so we just sum those values over the ...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int n, L, a; int t[maxn], l[maxn]; int main(){ scanf("%d%d%d", &n, &L, &a); for(int i = 0; i < n; i++){ scanf("%d%d", &t[i], &l[i]); } int start = 0; int ans = 0; for(int i = 0; i < n; i++){ ans += (t[i] - start)/a; start = t[i] + l...
1059
B
Forgery
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of ...
Each empty cell forbids to put a pen into every neighbor. Also, the border of the grid is forbidden. Let's mark all the forbidden cells. Now we have to check if for each filled cell there is at least one non-forbidden neighbor. Time complexity is $O(nm)$.
[ "implementation" ]
1,300
#include<bits/stdc++.h> using namespace std; const int maxn = (int)1e3 + 3; int n, m; char a[maxn][maxn]; bool can[maxn][maxn]; vector<int> must_have[maxn][maxn]; inline bool inside(int x, int y){ return x >= 0 && y >= 0 && x < n && y < m; } int main(){ scanf("%d%d", &n, &m); for(int i = 0; i < n; i++) for(in...
1059
C
Sequence Transformation
Let's call the following process a transformation of a sequence of length $n$. If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a seq...
The answers for $n \le 3$ are given in the samples. Now suppose that $n \ge 4$. The maximum result must have the earliest appearance of an integer different from $1$. If $n \ge 4$, the earliest integer that may appear is $2$. So initially we must remove all odd integers and for each of them append $1$ to the answer. Bu...
[ "constructive algorithms", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 6; int seq[maxn]; int ans[maxn]; int ptr = 0; void solve(int n, int mul){ if(n == 1){ans[ptr++] = mul; return;} if(n == 2){ans[ptr++] = mul; ans[ptr++] = mul * 2; return;} if(n == 3){ans[ptr++] = mul; ans[ptr++] = mul; ans[ptr++] = mul * 3; ret...
1059
D
Nature Reserve
There is a forest that we model as a plane and live $n$ rare animals. Animal number $i$ has its lair in the point $(x_{i}, y_{i})$. In order to protect them, a decision to build a nature reserve has been made. The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through...
If there are both positive and negative $y_i$, the answer is $-1$. Now assume that $y_i > 0$. Key observation: the answer can be binary searched. How to check if there is a valid circle with radius $R$? Firstly, the center of such circle is on the line $y = R$. Every point must be not farther than $R$ from the center. ...
[ "binary search", "geometry", "ternary search" ]
2,200
#include<bits/stdc++.h> using namespace std; typedef long double dbl; const dbl eps = 1e-9; inline bool gt(const dbl & x, const dbl & y){ return x > y + eps; } inline bool lt(const dbl & x, const dbl & y){ return y > x + eps; } inline dbl safe_sqrt(const dbl & D){ return D < 0 ? 0 : sqrt(D); } struct pt{ dbl...
1059
E
Split the Tree
You are given a rooted tree on $n$ vertices, its root is the vertex number $1$. The $i$-th vertex contains a number $w_i$. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than $L$ vertices and the sum of integers $w_i$ on each path does not exceed $S$. Each vert...
There are two solutions. Both of them find the answer for each subtree in dfs: firstly for children, then for the vertex itself. In both solutions, we firstly calculate for each vertex how far up a vertical path starting at this vertex may go. It can be done with binary lifting in $O(n\log n)$. Now let's describe the f...
[ "binary search", "data structures", "dp", "greedy", "trees" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 5; const int lg = 20; const ll inf = 1e18; int n, L; ll S; int w[maxn]; vector<int> down[maxn]; ll sum[maxn]; int up[maxn]; int h[maxn]; int p[maxn][lg]; int path[maxn]; inline ll get_sum(int v){ return v == -1 ? 0 : sum[v];...
1061
A
Coins
You have unlimited number of coins with values $1, 2, \ldots, n$. You want to select some set of coins having the total value of $S$. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum $S$?
Notice that using maximum value coin whenever possible will be always optimal. Hence, we can use $floor(S / n)$ coins of value $n$. Now, if $S \mod n$ is not equal to $0$, then we need to use one more coin of valuation $S \mod n$. Hence, our answer can be written as $ceil(S / n)$. Overall Complexity: $O(1)$
[ "greedy", "implementation", "math" ]
800
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long s = sc.nextLong(); long ans = (s - 1) / n + 1; System.out.print(ans); } }
1061
B
Views Matter
You came to the exhibition and one exhibit has drawn your attention. It consists of $n$ stacks of blocks, where the $i$-th stack consists of $a_i$ blocks resting on the surface. The height of the exhibit is equal to $m$. Consequently, the number of blocks in each stack is less than or equal to $m$. There is a camera ...
Let's sort the array in increasing order and find the minimum number of blocks $X$ required to retain the same top and right views. Then, the answer would be $\sum_{i=1}^{n} A_i - X$. For every $i$ from $1$ to $N$, we need to keep at least $1$ block for this stack to retain the top view. Thus, $X = X + 1$ for every $i$...
[ "greedy", "implementation", "sortings" ]
1,400
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long totalBlocks = 0; long a[] = new long[n]; for(int i = 0; i < n; ++i) { a[i] = sc.nex...
1061
C
Multiplicity
You are given an integer array $a_1, a_2, \ldots, a_n$. The array $b$ is called to be a subsequence of $a$ if it is possible to remove some elements from $a$ to get $b$. Array $b_1, b_2, \ldots, b_k$ is called to be good if it is not empty and for every $i$ ($1 \le i \le k$) $b_i$ is divisible by $i$. Find the numbe...
Let's introduce the following dynamic programming approach, $dp[n][n]$, where $dp[i][j]$ indicates the number of ways to select a good subsequence of size $j$ from elements $a_1, a_2, ..., a_i$. Our final answer will be $\sum_{i=1}^{n} dp[n][i]$. $dp[i][j] = \begin{cases} dp[i - 1][j] + dp[i - 1][j - 1] & \quad \text{i...
[ "data structures", "dp", "implementation", "math", "number theory" ]
1,700
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextInt(); int divCnt[] = new int[1000001]; for(i...
1061
D
TV Shows
There are $n$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $i$-th of the shows is going from $l_i$-th to $r_i$-th minute, both ends inclusive. You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is poss...
Solution: Sort the TV shows on the basis of their starting time. Now, we start allocating TVs greedily to the shows. For any show $i$, we allocate a new TV only if there is no old TV where the show ends at $r_o$, such that $r_o < l_i$ and $(l_i - r_o) \cdot y <= x$. Also, if there are many such old TVs, then we use the...
[ "data structures", "greedy", "implementation", "sortings" ]
2,000
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long x = sc.nextLong(); long y = sc.nextLong(); Show show[] = new Show[n]; for(int i = 0; i < n; ++i) show[i...
1061
E
Politics
There are $n$ cities in the country. Two candidates are fighting for the post of the President. The elections are set in the future, and both candidates have already planned how they are going to connect the cities with roads. Both plans will connect all cities using $n - 1$ roads only. That is, each plan can be viewe...
Let's create a graph with a source, sink and two layers. Let the left layer denote the nodes of tree $1$ and right layer denote the nodes of tree $2$. Let's denote $x_i$ as the demand of the $i^{th}$ node. For a demand $(k, x)$ in tree 1, we add an edge from source to node $k$ in the left layer with $cost = 0$ and $cap...
[ "flows", "graphs" ]
2,600
import java.util.*; import static java.lang.Math.*; public class MainE { static int dfs(int i, int par, int[] flow, int[] col, int curCol) { if(req[i] != -1) curCol = i; col[i] = curCol; int cost = 0; for(int j : adj[i]) { if(j != par) co...
1061
F
Lost Root
The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect $k$-ary tree if each vertex is either a leaf (has no children) or has exactly $k$ children. Also, in perfect $k$-ary tree all leafs must have same depth. For example, the picture ...
This solution had many randomized approaches, some with higher probability of passing and some with lower probability of passing. The author's solution (there exist better solutions with even lower probability of failure - comment yours below) is as follows: Part 1: Checking if a node is a leaf node: It can be done in ...
[ "interactive", "probabilities" ]
2,400
import java.util.*; public class Main { static HashMap<Long, Boolean> map = new HashMap<>(); static long getHash(long a, long b, long c) { return (long)(n + 1) * (long)(n + 1) * a + (long)(n + 1) * b + c; } static boolean check(int a, int b, int c) { long hashV = getHash(a, b, c); ...
1062
A
A Prank
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array $a_1$, $a_2$, ..., $a_n$ of integers, such that $1 \le a_1 < a_2 < \ldots < a_n \le 10^3$, and then went to the bathroom. JATC decided to prank his friend by erasing some \textbf{consecutive elemen...
Since $1 \le a_i \le 10^3$ for all $i$, let set $a_0=0$ and $a_{n+1}=1001$. For every $i,j$ such that $0 \le i<j \le n+1$, if $a_j-j=a_i-i$ then we can erase all the elements between $i$ and $j$ (not inclusive). So just check for all the valid pairs and maximize the answer. Time complexity: $O(n^2)$.
[ "greedy", "implementation" ]
1,300
null
1062
B
Math
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $n$, you can perform the following operations zero or more times: - mul $x$: multiplies $n$ by $x$ (where $x$ is an arbitrary positive integer). - sqrt: replaces $n$...
By factorizing $n$ we get $n={p_1}^{a_1}{p_2}^{a_2}\dots{p_k}^{a_k}$ ($k$ is the number of prime factors). Because we can't get rid of those prime factors then the smallest $n$ is ${p_1}{p_2}\dots{p_k}$. For each $a_i$, let $u_i$ be the positive integer so that $2^{u_i} \ge a_i>2^{u_i-1}$. Let $U$ be $max(u_i)$. It's c...
[ "greedy", "math", "number theory" ]
1,500
null
1062
C
Banh-mi
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into $n$ parts, places them on a row and numbers them from $1$ through $n$. For each part $i...
For each part that we choose, we need to calculate how many times that element is added to our score. You can see that, the first element that we choose is added $2^{k-1}$ times in our score ($k=r-l+1$), the second element is added $2^{k-2}$ times and so on. Therefore, we just need to choose all the $1s$ first and then...
[ "greedy", "implementation", "math" ]
1,600
null
1062
D
Fun with Integers
You are given a positive integer $n$ greater or equal to $2$. For every pair of integers $a$ and $b$ ($2 \le |a|, |b| \le n$), you can transform $a$ into $b$ if and only if there exists an integer $x$ such that $1 < |x|$ and ($a \cdot x = b$ or $b \cdot x = a$), where $|x|$ denotes the absolute value of $x$. After suc...
For every integer $x$ $(1 \le x \le n)$, let's call $D$ the set of integers that are able to be transformed into $x$. As you can see, if $a$ could be transformed into $b$ then $-a$ could also be transformed into $b$. Therefore $|D|$ is always even. Let's build a graph consists of $2n-2$ nodes, numbered $-n$ through $n$...
[ "dfs and similar", "graphs", "implementation", "math" ]
1,800
null
1062
E
Company
The company $X$ has $n$ employees numbered from $1$ through $n$. Each employee $u$ has a direct boss $p_u$ ($1 \le p_u \le n$), except for the employee $1$ who has no boss. It is guaranteed, that values $p_i$ form a tree. Employee $u$ is said to be in charge of employee $v$ if $u$ is the direct boss of $v$ or there is ...
Let's call $in_u$ the time that we reach the node $u$ in depth first search and $out_u=max(in_{v1}, in_{v2}, \cdots, in_{vk})$ where $v_i$ is a child of $u$. If node $u$ is in charge of node $v$ ($u$ is an ancestor of $v$) then $in_u \le in_v \le out_u$. Suppose we don't have to ignore any node then the answer to each ...
[ "binary search", "data structures", "dfs and similar", "greedy", "trees" ]
2,300
null
1062
F
Upgrading Cities
There are $n$ cities in the kingdom $X$, numbered from $1$ through $n$. People travel between cities by some \textbf{one-way} roads. As a passenger, JATC finds it weird that from any city $u$, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an...
The main idea of this problem is to calculate $in_u$ and $out_u$ for every node $u$, where $in_u$ denotes the number of nodes that can reach $u$ and $out_u$ denotes the number of nodes that can be reached by $u$. If $in_u+out_u=N+1$ then $u$ is important or $N$ if $u$ is semi-important. However, it may not possible to ...
[ "dfs and similar", "graphs" ]
2,900
null
1063
A
Oh Those Palindromes
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not. A string is called a substring of another string, if it can be obtained from that string by dropping some (possi...
One possible solution is just to sort the string. Why so? Note that each palindrome have equal character at their ends. Suppose this character is $c$ with $x$ number of occurences. Then there are at most $x(x + 1)/2$ palindromes with this character. So we have a clear upper bound on answer. It is easy to see, that the ...
[ "constructive algorithms", "strings" ]
1,300
null
1063
B
Labyrinth
You are playing some computer game. One of its levels puts you in a maze consisting of $n$ lines, each of which contains $m$ cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row $r$ and column $c$. In one step you can move one square up, left, down or right, if the target cell ...
Suppose we started in cell $(i_{0}, j_{0})$ and examining whether we can reach cell $(i_{1}, j_{1})$. Let's denote the number of taken moves to the right as $R$ and number of moves to the left as $L$ Clearly, $j_{0} + R - L = j_{1}$ That is, $R - L = j_{1} - j_{0} = const$. Or, put otherwise $R = L + const$, where $con...
[ "graphs", "shortest paths" ]
1,800
null
1063
C
Dwarves, Hats and Extrasensory Abilities
\textbf{This is an interactive problem.} In good old times dwarves tried to develop extrasensory abilities: - Exactly $n$ dwarves entered completely dark cave. - Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. - Dwarves went o...
The solution is just.. binary search! We will use just a single line to put our points on. Let's maintain an invariant that all white colored points are on the left and all black colored on the right. Put a new point in the middle of the gap between white points and black points. Depending on the color said by jury shr...
[ "binary search", "constructive algorithms", "geometry", "interactive" ]
1,900
null
1063
D
Candies for Children
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly $k$ candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends...
Solution works in $min(n^2, k / n)$ time. Also I will drop the case about the last person being sweet tooth and eating one candy instead of two. This adds few more cases but the idea stays the same. Basically in the formulas below just few $-1$ will appear, however there must be condition that there is at least one swe...
[ "brute force", "math" ]
2,600
null
1063
E
Lasers and Mirrors
Oleg came to see the maze of mirrors. The maze is a $n$ by $n$ room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze. ...
The answer is always $n$ (if the permutation is identity) lasers or $n - 1$ (otherwise). Clearly, we can't have more than $n - 1$ matching lasers if the permutation is not identity. Consider just the very first line with mirrors. If the first mirror in this line is <<\>> then we miss the laser below this mirror, if the...
[ "constructive algorithms", "math" ]
3,000
null
1063
F
String Journey
We call a sequence of strings $t_{1}, ..., t_{k}$ a journey of length $k$, if for each $i > 1$ $t_{i}$ is a substring of $t_{i - 1}$ and length of $t_{i}$ is strictly less than length of $t_{i - 1}$. For example, ${ab, b}$ is a journey, but ${ab, c}$ and ${a, a}$ are not. Define a journey on string $s$ as journey $t_{...
This problem required quite a lot of nice observations! Observation 1. We can only consider journeys in which neighboring strings differ exactly by removing one symbol. All other journeys can be modified a bit to match the criterion above. Observation 2. If it is possible to start a journey at the symbol $i$ with lengt...
[ "data structures", "dp", "string suffix structures" ]
3,300
null
1064
A
Make a triangle!
Masha has three sticks of length $a$, $b$ and $c$ centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks. What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assem...
Suppose $c$ is the largest stick. It is known, that we can build a triangle iff $c \le a + b - 1$. So if we can build a triangle the answer is zero. Otherwise we can just increase $a$ or $b$ until the inequality above holds. So the answer is $max(0, c - (a + b - 1))$. Another approach: just bruteforce all possible tria...
[ "brute force", "geometry", "math" ]
800
null
1064
B
Equations of Mathematical Magic
\begin{quote} Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for. \hfill Arkadi and Boris Strugatsky. Monday starts on Saturday \end{quote} Reading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $a - (a \oplus x) - x = ...
Rewriting equation we have $a \oplus x = a - x$. If you look in the xor definition, it is easy to see, that $a \oplus x \ge a - x$, no matter $a$ and $x$ (just look at the each bit of the $a \oplus x$). And the equality handles only if bits of $x$ form a subset of bits of $a$. So the answer is $2^t$, where $t$ is the n...
[ "math" ]
1,200
null
1065
A
Vasya and Chocolate
There is a special offer in Vasya's favourite supermarket: if the customer buys $a$ chocolate bars, he or she may take $b$ additional bars for free. This special offer can be used any number of times. Vasya currently has $s$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $c$ rou...
Number of chocolate bars Vasya can buy without offer is $cnt = \lfloor \frac{s}{c} \rfloor$. Number of "bundles" with $a$ bars $x = \lfloor \frac{cnt}{a} \rfloor$. Then number of additional bars $add = x \cdot b$. In result, total number of bars is $add + cnt$.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int s, a, b, c; int t; cin >> t; for(int i = 0; i < t; ++i){ cin >> s >> a >> b >> c; s /= c; int x = s / a; s %= a; long long res = x * 1LL * (a + b); res += s; cout <<...
1065
B
Vasya and Isolated Vertices
Vasya has got an undirected graph consisting of $n$ vertices and $m$ edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edg...
Vasya can decrease number of isolated vertices up to $2$ using one edge and pairing them. So minimum number of isolated vertices is $max(0, n - 2m)$. To calculate maximum number of isolated vertices let's keep number of non-isolated vertices knowing that each pair connected by edge (i.e. size of clique). Let we have si...
[ "constructive algorithms", "graphs" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int n; long long m; cin >> n >> m; long long cur = 1; long long rem = m; while(rem > 0){ long long d = min(cur, rem); rem -= d; ++cur; } assert(rem == 0); long long res = n; if(cur > 1) res ...
1065
C
Make It Equal
There is a toy building consisting of $n$ towers. Each tower consists of several cubes standing on each other. The $i$-th tower consists of $h_i$ cubes, so it has height $h_i$. Let's define operation slice on some height $H$ as following: for each tower $i$, if its height is greater than $H$, then remove some top cube...
Let's iterate over height $pos$ of slice in decreasing order. All we need to know is a number of towers with height more than $pos$ (name it $c$) and sum of its heights $sum$. Current slice on height $pos$ is good if $k \ge sum - c \cdot pos$. Let's greedily decrease value $pos$ while slice on $pos$ is good keeping cor...
[ "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n, k, h; int need = int(1e9); int cnt[N]; int main() { scanf("%d %d", &n, &k); for(int i = 0; i < n; ++i){ int x; scanf("%d", &x); h = max(h, x); need = min(need, x); ++cnt[x]; } ...
1065
D
Three Pieces
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily $8 \times 8$, but it still is $N \times N$. Each square has some number written on it, all the numbers are from $1$ to $N^2$ and all the numbers are pairwise distinct. The $j$-th square in the $i$-th row has a number $A_{ij}$...
There are a lot of different solutions for the problem. Most of them have the similar structure. The first part is to find the shortest distance between the states $(x_1, y_1, p_1)$ and $(x_2, y_2, p_2)$, where $x$ and $y$ are the coordinates of the square and $p$ is the current piece. This can be done with 0-1 bfs, Fl...
[ "dfs and similar", "dp", "shortest paths" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define mp make_pair #define x first #define y second using namespace std; typedef pair<int, int> pt; const int N = 12; const int M = 305; const int INF = 1e9; int n; int a[N][N]; pt pos[N * N]; pt dist[M][M]; pt operator +(const pt &a, ...
1065
E
Side Transmutations
Consider some set of distinct characters $A$ and some string $S$, consisting of exactly $n$ characters, where each character is present in $A$. You are given an array of $m$ integers $b$ ($b_1 < b_2 < \dots < b_m$). You are allowed to perform the following move on the string $S$: - Choose some valid $i$ and set $k =...
Let's take a look at any operation. You can notice that each letter can only go from position $i$ to $n - i - 1$ ($0$-indexed). Then, doing some operation twice is the same as doing that operation zero times. Now consider some set of operations $l_1, l_2, \dots, l_k$, sorted in increasing order. Actually, they do the f...
[ "combinatorics", "strings" ]
2,300
#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; const int MOD = 998244353; int n, m, A; int b[N]; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b){ return (a * 1ll * b) ...
1065
F
Up and Down the Tree
You are given a tree with $n$ vertices; its root is vertex $1$. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is $v$, then you make any of the following two possible moves: - move down to any \textbf{leaf} in subtree of $v$; - if ver...
Let's calculate answer in two steps. At first, let's calculate for each vertex $v$ $drev(v)$ - what we can gain if we must return from subtree of $v$ in the end. We need only pair of values: minimal possible depth we can acquire to move up from subtree of $v$ and maximal number of different leaves we can visit. Note, t...
[ "dfs and similar", "dp", "trees" ]
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; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out...
1065
G
Fibonacci Suffix
Let's denote (yet again) the sequence of Fibonacci strings: $F(0) = $ 0, $F(1) = $ 1, $F(i) = F(i - 2) + F(i - 1)$, where the plus sign denotes the concatenation of two strings. Let's denote the \textbf{lexicographically sorted} sequence of suffixes of string $F(i)$ as $A(F(i))$. For example, $F(4)$ is 01101, and $A(...
Suppose we added all the suffixes of $F(n)$ into a trie. Then we can find $k$-th suffix by descending the trie, checking the sizes of subtrees to choose where to go on each iteration. The model solution actually does that, but computes the sizes of subtrees without building the whole trie. Recall that if we insert all ...
[ "strings" ]
2,700
#include <bits/stdc++.h> using namespace std; typedef long long li; const li INF64 = li(1e18); li add(li x, li y) { return min(x + y, INF64); } const int N = 243; int A1[N][2]; li A2[N][N]; int A3[N][N]; int n, m; li k; int z; int p[N]; void build(const string& s) { z = (int)(s.size()); p[0] = 0; ...
1066
A
Vova and Train
Vova plans to go to the conference by train. Initially, the train is at the point $1$ and the destination point of the path is the point $L$. The speed of the train is $1$ length unit per minute (i.e. at the first minute the train is at the point $1$, at the second minute — at the point $2$ and so on). There are lante...
What is the number of lanterns Vova will see from $1$ to $L$? This number is $\lfloor\frac{L}{v}\rfloor$. Now we have to subtract the number of lanters in range $[l; r]$ from this number. This number equals to $\lfloor\frac{r}{v}\rfloor - \lfloor\frac{l - 1}{v}\rfloor$. So the answer is $\lfloor\frac{L}{v}\rfloor$ - $\...
[ "math" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int i = 0; i < t; ++i) { int L, v, l, r; cin >> L >> v >> l >> r; cout << L / v - r / v + (l - 1) / v << endl; } return 0; }
1066
B
Heaters
Vova's house is an array consisting of $n$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $i$-th element of the array is $1$ if there is a heater in the position $i$, otherwise the $i$-th element of the array is $0$. Each hea...
Let's solve this problem greedily. Let $last$ be the last position from the left covered by at least one heater. Initially, $last$ equals -1. While $last < n - 1$, lets repeat the following process: firstly, we have to find the rightmost heater in range $(max(-1, last - r + 1); last + r]$. It can be done in time $O(n)$...
[ "greedy", "two pointers" ]
1,500
#include <vector> #include <iostream> #define forn(i,n) for (int i=0; i<int(n); i++) using namespace std; const int N = 2e5; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, r; cin >> n >> r; vector<int> a(n); vector<int> cnt(n); int ans = 0; forn(i, n) { cin >> a[i...
1066
C
Books Queries
You have got a shelf and want to put some books on it. You are given $q$ queries of three types: - L $id$ — put a book having index $id$ on the shelf to the left from the leftmost existing book; - R $id$ — put a book having index $id$ on the shelf to the right from the rightmost existing book; - ? $id$ — calculate th...
Let imagine our shelf as an infinite array. Let's carry the rightmost free position from the left of our shelf (let it be $l$ and initially it equals to $0$) and the leftmost free position from the right of our shelf (let it be $r$ and initially it equals to $0$). Also let's carry the array $pos$ of length $2 \cdot 10^...
[ "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int M = 200 * 1000 + 11; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; vector<int> pos(M); int curl = 0; int curr = 0; for (int i = 0; i < q; ++i) { string type; int id; ...
1066
D
Boxes Packing
Maksim has $n$ objects and $m$ boxes, each box has size exactly $k$. Objects are numbered from $1$ to $n$ in order from left to right, the size of the $i$-th object is $a_i$. Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goe...
The first solution is some kind of a straight-forward understanding the problem. Let's do binary search on the answer. So our problem is to find the smallest $x$ such that the suffix of the array $a$ starting from the position $x$ can be packed in boxes. It is easy to see that if we can do it for some $x$ then we alway...
[ "binary search", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } reverse(a.begin(), a.end()); int rem = 0; for (int i =...
1066
E
Binary Numbers AND Sum
You are given two huge binary integer numbers $a$ and $b$ of lengths $n$ and $m$ respectively. You will repeat the following process: if $b > 0$, then add to the answer the value $a~ \&~ b$ and divide $b$ by $2$ rounding down (i.e. remove the last digit of $b$), and repeat the process again, otherwise stop the process....
To solve this problem let's take a look which powers of $2$ in $a$ will be affected by powers of $2$ in $b$. Firstly, let's reverse numbers. Let's carry the current power of $2$ (let it be $pw$), the current sum of powers of $2$ in $a$ from the position $0$ to the current position inclusive (let it be $res$) and the an...
[ "data structures", "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int a, int b) { a += b; if (a < 0) a += MOD; if (a >= MOD) a -= MOD; return a; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; string s, t;...
1066
F
Yet another 2D Walking
Maksim walks on a Cartesian plane. Initially, he stands at the point $(0, 0)$ and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point $(0, 0)$, he can go to any of the following points in one move: - $(1, 0)$; - $(0, 1)$; - $(-1, 0)$; - $(0, -1...
The main idea is that we don't need more than $2$ border points on each level. So if we consider than the point $p = (x_p, y_p)$ is less than point $q = (x_q, y_q)$ when $p_x < q_x$ or $p_x = q_x$ and $p_y > q_y$ then let's distribute all the points by their levels using std::map or something like it, sort points on ea...
[ "dp" ]
2,100
#include <bits/stdc++.h> using namespace std; const long long INF64 = 1e18; long long dist(pair<int, int> a, pair<int, int> b) { return abs(a.first - b.first) + abs(a.second - b.second); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; map<int...
1067
A
Array Without Local Maximums
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $n$ numbers from $1$ to $200$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: $a_{1} \le a_{2}$, $a_{n} \le a_{n-1}$ and $a_{i} \...
Let's find solution with complexity $O(n \cdot a^2)$. We can count $dp[prefix][a][flag]$ - quantity of ways to restore element from $1$ to $pref$ with last element equalls to $a$, $flag = 0$ means that previous element is less then the last or last element is first, $flag = 1$ - the opposite. So $dp[pref][a][0] = \sum_...
[ "dp" ]
1,900
null
1067
B
Multihedgehog
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog. Let us define $k$-multihedgehog ...
Solution 1: Firstly let's find all vertices with degree $1$. Now we can delete them and all, verticies which were incident to them must became verticies with degree $1$. And also for each new veretice with degree $1$ we must have already deleted not less then $3$ verticies. If initial graph was $k$-multihedgehog, after...
[ "dfs and similar", "graphs", "shortest paths" ]
1,800
null
1067
C
Knights
Ivan places knights on infinite chessboard. Initially there are $n$ knights. If there is free cell which is under attack of at least $4$ knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in th...
If after some loops of the process we will have two neighboring lines with length $x$ total complexity of knights would be not less than $O( \frac{x^2}{4} )$. In this construction: $0$ - initial placement. $1, \,\, 2$ - added knights. Would be two neighboring lines with length $O(\frac{2 \cdot n}{3})$ so total complexi...
[ "constructive algorithms" ]
2,600
null
1067
D
Computer Game
Ivan plays some computer game. There are $n$ quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has $3$ parameters $a_{i}$, $b_{i}$, $p_{i}$: reward for completing quest before upgrade, reward for completing quest after upgrade ($a_{i} < b_{i}$) and probability...
Let's denote $max(b_{i} p_{i})$ as $M$. Independent of our strategy we cannot get more than $M$ in one second (in expected value). But if we could upgrade one quest, we would upgrade the quest which maximizes $b_{i} p_{i}$ and then try to complete only this quest each second, thus getting $+M$ to expected value each se...
[ "dp", "greedy", "math", "probabilities" ]
3,100
null
1067
E
Random Forest Rank
Let's define rank of undirected graph as rank of its adjacency matrix in $\mathbb{R}^{n \times n}$. Given a tree. Each edge of this tree will be deleted with probability $1/2$, all these deletions are independent. Let $E$ be the expected rank of resulting forest. Find $E \cdot 2^{n-1}$ modulo $998244353$ (it is easy t...
I'll try to explain how to come up with this solution rather than just state the fact. For those who are more interested in getting AC, here is your fact: rank of a forest is twice the size of maximal matching. When we see expected value, we usually want to somehow rewrite the thing under the expected value, apply line...
[ "dp", "graph matchings", "math", "trees" ]
2,800
null
1068
A
Birthday
Ivan is collecting coins. There are only $N$ different collectible coins, Ivan has $K$ of them. He will be celebrating his birthday soon, so all his $M$ freinds decided to gift him coins. They all agreed to three terms: - Everyone must gift as many coins as others. - All coins given to Ivan must be different. - Not le...
To get $L$ new coins irrespective of the Ivan's collection he must get not less than $L+K$ coins as a present. Therefore each friend should gift at least $X = \lceil \frac{L+K}{M} \rceil$ coins. But it may be not possible for all friends to gift $X$ coins if $X \cdot M > N$. Complexity is $O(1)$.
[ "math" ]
1,400
null
1068
B
LCM
Ivan has number $b$. He is sorting through the numbers $a$ from $1$ to $10^{18}$, and for every $a$ writes $\frac{[a, \,\, b]}{a}$ on blackboard. Here $[a, \,\, b]$ stands for least common multiple of $a$ and $b$. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers...
$\frac{[a, \,\, b]}{a} = \frac{b}{(a, \,\, b)}$, here $(a, \,\, b)$ is greatest common divisor. Let's see how many different values can have $c = (a, \,\, b)$. All values $c$ that divides $b$ are reachable if $a = c$ and every value of $(a, \,\, b)$ divides $b$. So answer is number of divisors of $b$. It can be calcula...
[ "math", "number theory" ]
1,200
null
1068
C
Colored Rooks
Ivan is a novice painter. He has $n$ dyes of different colors. He also knows exactly $m$ pairs of colors which harmonize with each other. Ivan also enjoy playing chess. He has $5000$ rooks. He wants to take $k$ rooks, paint each of them in one of $n$ colors and then place this $k$ rooks on a chessboard of size $10^{9}...
Let's put rooks with color $i$ just on line number $i$. Then, obviously, for any color the set of rooks of this color would be connected. Let's put rooks on positions $(i, \,\, i)$ for $i$ from $1$ to $n$. After that for any color there is a rook of this color on a board and for any two different colors $a$ $b$ union o...
[ "constructive algorithms", "graphs" ]
1,700
null
1071
E
Rain Protection
A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles. The workplace of the mechanism is a part of plane just abo...
First, let's find out if we can catch all raindrops for a fixed speed $v$. Assume that the endpoints are at $(e_1, 0)$ and $(e_2, h)$ at any moment. Consider the point $(e_1, e_2)$ for this state (we call it the state point for this state). From now on we work with these points. We know that this state point can move w...
[ "binary search", "geometry" ]
3,500
null
1073
A
Diverse Substring
You are given a string $s$, consisting of $n$ lowercase Latin letters. A substring of string $s$ is a continuous segment of letters from $s$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length $n$ diverse...
Notice that the string of two distinct letter is already diverse. That implies that the answer is "NO" if and only if all the letters in the string are the same. Otherwise you can check all pairs of adjacent letters in $O(n)$. Overall complexity: $O(n)$.
[ "implementation", "strings" ]
1,000
n = int(input()) s = input() for i in range(n - 1): if (s[i] != s[i + 1]): print("YES") print(s[i], s[i + 1], sep="") exit(0) print("NO")
1073
B
Vasya and Books
Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one — $a_2$, and so on. The book at the bottom of the stack has number $a_n$. \textbf{All numbers are distinct}. Vasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he want...
Let's maintain the pointer $pos$ to the topmost non-deleted book and whether each book whether is removed from the stack or not. Initially, all books are in a stack, and $pos$ is 0 (if we store the array 0-indexed). We will process the array $B$ in the order $b_1, b_2, \dots b_n$. If the current book $b_i$ is removed f...
[ "implementation", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n; int a[N]; int b[N]; bool u[N]; int main() { // freopen("input.txt", "r", stdin); scanf("%d", &n); for(int i = 0; i < n; ++i) { scanf("%d", a + i); } for(int i = 0; i < n; ++i){ scanf("%d", b + i); } int po...
1073
C
Vasya and Robot
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations: - U — move from $(x, y)$ to $(x, y + 1)$; - D — move from $(x, y)$ to $(x, y - 1)$; - L — move from $(x, y)$ to $(x - 1, y)$; - R — move from $(x, y)$ to $(x...
Denote $d = |x| + |y|$. If $d > n$, then the answer is -1, since the robot will not have the time to reach $(x, y)$ cell in $n$ steps. Also, if $d$ and $n$ have different parity, then the answer is also -1, as in one move the robot changes the parity of the sum of its coordinates. In all other cases, the answer exists....
[ "binary search", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = int(1e5) + 9; string s; int n; int x, y; void upd(pair<int, int> &pos, char mv, int d){ if(mv == 'U') pos.second += d; if(mv == 'D') pos.second -= d; if(mv == 'L') pos.first -= d; if(mv == 'R') pos.first += d; } bool can(pair<int, int> u, pair...
1073
D
Berland Fair
XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $n$ booths, arranged in a circle. The booths are numbered $1$ through $n$ clockwise with $n$ being adjacent to $1$. The $i$-th booths sells some candies for the price of $a_i$ burles per item. Each booth has an unlimited supply of candies. P...
Let's code the following process. Go one circle across the booths, calculate the total cost $C$ of sweets bought and the number $S$ of sweets bought. Now you can decrease you money down to $T = T~mod~C$ and add $S \cdot (T~div~C)$ to answer. It represents that you went maximum number of such circles. The later circles ...
[ "binary search", "brute force", "data structures", "greedy" ]
1,700
#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; typedef long long li; int n; int a[N]; void get(li T, li& pr, li& cnt){ pr = 0, cnt = 0; forn(i, n){ if (T >= a[i]){ T -= a[i]; pr += a[i]; ++cnt; } } } int main() { l...
1073
E
Segment Sum
You are given two integers $l$ and $r$ ($l \le r$). Your task is to calculate the sum of numbers from $l$ to $r$ (including $l$ and $r$) such that each number contains \textbf{at most} $k$ different digits, and print this sum modulo $998244353$. For example, if $k = 1$ then you have to calculate all numbers from $l$ t...
Let's calculate the answer as the sum of suitable numbers in range $[1; r]$ minus the sum of suitable numbers in range $[1; l - 1]$. Now our problem is to calculate the sum of suitable numbers in range $[1; n]$. The main approach for this problem is digit DP. Let's calculate two dynamic programmings $dp_{pos, mask, f}$...
[ "bitmasks", "combinatorics", "dp", "math" ]
2,300
#include <bits/stdc++.h> using namespace std; #define x first #define y second typedef pair<long long, int> pt; const int N = 20; const int M = 1 << 10; const int MOD = 998244353; int k; int pw10[N]; int bitCnt[M]; pt dp[N][M][2]; int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; r...
1073
F
Choosing Two Paths
You are given an undirected unweighted tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges. Your task is to choose two pairs of vertices of this tree (all the chosen vertices \textbf{should be distinct}) $(x_1, y_1)$ and $(x_2, y_2)$ in such a way that neither $x_1$ ...
Firstly, let's call a path from $u$ to $v$ good, if $u$ is a leaf, $v$ is a vertex of degree at least $3$ (the number of their neighbors is at least $3$) and there are no other vertices of degree at least $3$ on this path expect the vertex $v$. The first step of the solution is to remove all the good paths from $u$ to ...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define size(a) int((a).size()) typedef pair<int, int> pt; const int N = 200 * 1000 + 11; int n; vector<int> g[N]; int p[N]; int dist[N]; bool bad[N]; int value[N]; pt res[N]; vector<pt> best[N]; void dfs(int v, int par = -1, int d =...
1073
G
Yet Another LCP Problem
Let $\text{LCP}(s, t)$ be the length of the longest common prefix of strings $s$ and $t$. Also let $s[x \dots y]$ be the substring of $s$ from index $x$ to index $y$ (inclusive). For example, if $s = $ "abcde", then $s[1 \dots 3] =$ "abc", $s[2 \dots 5] =$ "bcde". You are given a string $s$ of length $n$ and $q$ queri...
At first, implement your favourite string suffix structure for comparing pair of suffixes lexicographically fast enough. For example, it's a Suffix Array + linear LCP + Sparse Table. Now we can compare two suffixes $i$ and $j$ by finding $l = lcp(i, j)$ and comparing $s[i + l]$ with $s[j + l]$. We will process queries ...
[ "data structures", "string suffix structures" ]
2,600
#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; template<class A, class B> ostream& operator <<(ostream &out, const pair<A, B> &p) { return out << ...
1075
A
The King's Race
On a chessboard with a width of $n$ and a height of $n$, rows are numbered from bottom to top from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. Therefore, for each cell of the chessboard, you can assign the coordinates $(r,c)$, where $r$ is the number of the row, and $c$ is the number of the col...
Let's find the minimum time needed for the white king to reach the coin. It is obvious that it is always optimal to move only towards the coin. In case of white king it means that we should move only up, right or up-right diagonally. During one move we can only add $1$ or $0$ to any of our coordinates (or to both of th...
[ "implementation", "math" ]
800
null
1075
B
Taxi drivers and Lyft
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5. Lyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the rest of the city residents — $n$ riders. Each resident (including taxi drivers) of ...
Let's find for each rider the taxi driver that will get his call. To do this we can find for each rider the nearest taxi driver at right and the nearest taxi driver at left. Let's define the nearest taxi driver at left for $i$-th citizen as $l_i$ and at the right as $r_i$. The computations can be done with the followin...
[ "implementation", "sortings" ]
1,200
null
1076
A
Minimizing the String
You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to remove \textbf{at most one} (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String $s = s_1 s_2 \dots s...
By the definition of lexicographical comparing we can see that if we can remove one character we always have to do it. Besides, we have to remove the character from the leftmost position $i$ such that $i < n$ and $s_i > s_{i + 1}$ or from the position $n$ if there is no such $i$.
[ "greedy", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int n; string s; cin >> n >> s; int pos = n - 1; for (int i = 0; i < n - 1; ++i) { if (s[i] > s[i + 1]) { pos = i; break; } } cout << s.substr(0, pos) + s.substr(pos + 1) << endl; return 0; }
1076
B
Divisor Subtraction
You are given an integer number $n$. The following algorithm is applied to it: - if $n = 0$, then end algorithm; - find the smallest \textbf{prime} divisor $d$ of $n$; - subtract $d$ from $n$ and go to step $1$. Determine the number of subtrations the algorithm will make.
Notice that once the number becomes even, it never stops being even as subtracting $2$ doesn't change parity. Thus, the task is to find the smallest divisor, subtract it and print $1 + \frac{n - d}{2}$. Overall complexity: $O(\sqrt{n})$.
[ "implementation", "math", "number theory" ]
1,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; long long get(long long n){ for (long long i = 2; i * i <= n; ++i) if (n % i == 0) return i; return n; } int main() { long long n; scanf("%lld", &n); long long cnt = 0; if (n % 2 != 0){ n -= get(n); ++cn...
1076
C
Meme Problem
Try guessing the statement from this picture: You are given a non-negative integer $d$. You have to find two non-negative real numbers $a$ and $b$ such that $a + b = d$ and $a \cdot b = d$.
To solve this problem we need to use some math and solve the equation on the paper. If $a + b = d$ then $a = d - b$ and $a \cdot b = d$ transforms to $b (d - b) = d$ or $db - b^2 - d = 0$. Then $a, b = (d \pm \sqrt{D}) / 2$ where $D = d^2 - 4d$. So if $d = 0$ then $a = b = 0$, or if $0 < d < 4$ there is no answer. Sinc...
[ "binary search", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) typedef long long li; typedef double ld; typedef pair<int, int> pt; li d; inline bool read() { if(!(cin >> d)) return false; return true; } inline void solve() { if(d == 0) { cout << "Y " << 0.0 << " " <...
1076
D
Edge Deletion
You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$. You have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ \textbf{good} if there still exists a p...
Let's understand how many good vertices we may get if only $k$ edges remain. This value is not greater than $k + 1$, since an edge an add only one good vertex, and for $k = 0$ we have a good vertex with index $1$. This is an upper bound; let's try to find a solution getting exactly $k + 1$ good vertices (or, if $k + 1>...
[ "graphs", "greedy", "shortest paths" ]
1,800
#include <bits/stdc++.h> using namespace std; vector<pair<int, pair<int, int> > > g[300043]; int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); for(int i = 0; i < m; i++) { int x, y, w; scanf("%d %d %d", &x, &y, &w); --x; --y; g[x].push_back(make_pair(y, make_pair(w, i))); g[y].push_back(make_p...
1076
E
Vasya and a Tree
Vasya has a tree consisting of $n$ vertices with root in vertex $1$. At first all vertices has $0$ written on it. Let $d(i, j)$ be the distance between vertices $i$ and $j$, i.e. number of edges in the shortest path from $i$ to $j$. Also, let's denote $k$-subtree of vertex $x$ — set of vertices $y$ such that next two ...
To solve this problem we can use a data structure which allows to add some value on segment and get a value from some point (Fenwick tree, segment tree or anything you are familliar with). Let's run DFS from the root while maintaining current depth. When entering a vertex $u$ on depth $h$, let's consider all queries ha...
[ "data structures", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 9; int n, m; vector <int> g[N]; vector <pair<int, int> > q[N]; long long add[N]; long long res[N]; void dfs(int v, int pr, int h, long long sum){ for(auto p : q[v]){ int l = h, r = h + p.first; add[l] += p.second; if(r + 1 < N) add[r + 1...
1076
F
Summer Practice Report
Vova has taken his summer practice this year and now he should write a report on how it went. Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly $n$ pages and the $i$-th page will include $x_i$ tables and $y_i$ formulas. The p...
Let's intruduce the following dynamic programming approach. $dp[N][2]$, $dp[i][j]$ is the smallest number of elements of type $j$ page $i$ can end with. If we learn to recalculate it, the answer will be "YES" if $dp[n][0] \le k$ or $dp[n][1] \le k$. I will try to prove it on the fly. Let's look into the constructing of...
[ "dp", "greedy" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef long long li; const int N = 300 * 1000 + 13; const int INF = 1e9; int dp[N][2]; int n, k; int a[N], b[N]; int get(int pa, int pb, int a, int b){ int ans = INF; if (pa <= k){ int tot = pa + a; int cnt...
1076
G
Array Game
Consider a following game between two players: There is an array $b_1$, $b_2$, ..., $b_k$, consisting of positive integers. Initially a chip is placed into the first cell of the array, and $b_1$ is decreased by $1$. Players move in turns. Each turn the current player has to do the following: if the index of the cell w...
Suppose there is only one query, i. e. we are given some array and we want to know who is the winner if the game is played on this array. One of the obvious solutions is $dp[i][x]$ - will the current player win if the chip is currently in the cell $i$ and the number in cell $i$ is $x$. We can already see that we don't ...
[ "data structures", "games" ]
3,000
#include <bits/stdc++.h> using namespace std; const int N = 200043; typedef long long li; int n, m; li a[N]; int q; int f[N * 4]; vector<int> T[4 * N]; vector<int> T2[4 * N]; int mask; int cur; vector<int> combine(const vector<int>& a, const vector<int>& b) { vector<int> c(1 << m); for(int i = 0; i < (1 << m); i...
1077
A
Frog Jumping
A frog is currently at the point $0$ on a coordinate axis $Ox$. It jumps by the following algorithm: the first jump is $a$ units to the right, the second jump is $b$ units to the left, the third jump is $a$ units to the right, the fourth jump is $b$ units to the left, and so on. Formally: - if the frog has jumped an ...
With each pair of jumps of kind "to the right - to the left" the frog jumps $a - b$. So the answer is almost $(a - b) \cdot \lfloor\frac{k}{2}\rfloor$. Almost because there can be one more jump to the right. So if $k$ is odd then we have to add $a$ to the answer.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int i = 0; i < t; ++i) { int a, b, k; cin >> a >> b >> k; cout << (a - b) * 1ll * (k / 2) + a * (k & 1) << endl; } return 0; }
1077
B
Disturbed People
There is a house with $n$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $n$ integer numbers $a_1, a_2, \dots, a_n$, where $a_i = 1$ if in the $i$-th flat the light is on and $a_i = 0$ otherwise. Vova thinks that people in the $i$-th ...
The first observation is that we are interested only in patterns of kind "101". All other patterns don't make sense at all. So, let's build a greedy approach. Let's iterate over the given array from the left to the right and maintain that the prefix of the given answer is already correct. If now we are at some position...
[ "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans = 0; for (int i = 1; i < n - 1; ++i) { if (a[i] == 0 && a[i -...
1077
C
Good Array
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $a=[1, 3, 3, 7]$ is good because there is the element $a_4=7$ which equals to the sum $1 + 3 + 3$. You are given an array $a$ consisting of $n$ integers. Your task is to print all indices $...
The first part: calculate the sum of the whole array: $sum = \sum\limits_{i = 1}^n a_i$ (be careful, it can be $2 \cdot 10^{11}$!). The second part: let's maintain an array $cnt$ of size $10^6 + 1$ where $cnt_i$ will be equal to the number of elements in the given array equals to $i$. The third part: iterate over the a...
[]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 1e6; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); vector<int> cnt(MAX + 1); for (int i = 0; i < n; ++i) { cin >> a[i]; ++cnt[a[i]]; } long long ...
1077
D
Cutting Out
You are given an array $s$ consisting of $n$ integers. You have to find \textbf{any} array $t$ of length $k$ such that you can cut out maximum number of copies of array $t$ from array $s$. Cutting out the copy of $t$ means that for each element $t_i$ of array $t$ you have to find $t_i$ in $s$ and remove it from $s$. ...
Let's solve the problem using binary search by the answer. It is easy to see that if we can construct the answer for some number of copies $val$ then we also can do it for $val - 1$. The only thing we need is to write the function $can(val)$ which will say can we cut off $val$ copies of some array $t$ from $s$ or not. ...
[ "binary search", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; const int MAX = 200 * 1000 + 1; int n, k; vector<int> s, t; vector<int> cnts(MAX); bool can(int cnt) { t.clear(); for (int i = 0; i < MAX; ++i) { int need = min(cnts[i] / cnt, k - int(t.size())); for (int j = 0; j < need; ++j) { t.push_back(i); } } return i...
1077
E
Thematic Contests
Polycarp has prepared $n$ competitive programming problems. The topic of the $i$-th problem is $a_i$, and some problems' topics may coincide. Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and \textbf{all contests should have pairwise distinct topics}. He may n...
The first thing: we don't need the problems, we need their counts. So let's calculate for each topic the number of problems with this topic and sort them in non-decreasing order. The counting can be done with std::map or another one sorting. The second thing: the answer is not exceed $n$ (very obviously). So let's iter...
[ "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; map<int, int> cnt; for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x]; } vector<int> cnts; for (auto it : cnt) { cnts.push_...
1077
F1
Pictures with Kittens (easy version)
\textbf{The only difference between easy and hard versions is the constraints.} Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others:...
Let's solve the problem using dynamic programming. Let $dp_{i, j}$ be the maximum total beauty of pictures if Vova is at the $i$-th picture now, the number of remaining reposts is $j$ and Vova reposted the $i$-th picture. Initially, $dp_{0, x} = 0$ and all other values of $dp$ are $-\infty$. Let's learn to do some tran...
[ "dp" ]
1,900
#include <bits/stdc++.h> using namespace std; const long long INF64 = 1e18; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k, x; cin >> n >> k >> x; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<vector<long long>> d...
1077
F2
Pictures with Kittens (hard version)
\textbf{The only difference between easy and hard versions is the constraints.} Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others:...
Let's use dynamic programming described in the previous tutorial to solve this problem too. But its complexity is $O(nkx)$ so we have to improve some part of the solution. Let's see how we do transitions in this dp: for $p \in [i-k; i-1]$ $dp_{i, j} = max(dp_{i, j}, dp_{p, j + 1} + a_i)$. What can we do to optimize it?...
[ "data structures", "dp" ]
2,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair typedef long long li; typedef pair<li, li> pll; const li INF64 = 1e18; struct myQueue { stack<pll> s1, s2; int size() { return s1.size() + s2.size(); } bool isEmpty() { return size() == 0; } long lon...
1078
E
Negative Time Summation
Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time! More specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The mach...
Disclaimer: there seem to be solutions much simpler than the author's. You can read some passed codes. Let's define our workplace as follows: we will take 6 rows, containing (in order from up to down): carry bits, bits of $a$, bits of $b$, two lines of some buffer garbage and the line with the answer. Consequently, the...
[ "constructive algorithms" ]
3,400
null
1080
A
Petya and Origami
Petya is having a party soon, and he has decided to invite his $n$ friends. He wants to make invitations in the form of origami. For each invitation, he needs \textbf{two} red sheets, \textbf{five} green sheets, and \textbf{eight} blue sheets. The store sells an infinite number of notebooks of each color, but each not...
Let's calculate how many notebooks we need for each color separately, and the answer, obviously, will be their sum. We need $2 \cdot n$ red sheets, $5 \cdot n$ green sheets, and $8 \cdot n$ blue sheets. So we need $\lceil \frac {2n}{k} \rceil$ notebooks with red sheets, $\lceil \frac{5n}{k} \rceil$ and $\lceil \frac{8n...
[ "math" ]
800
# include <iostream> # include <cmath> # include <algorithm> # include <stdio.h> # include <cstdint> # include <cstring> # include <string> # include <cstdlib> # include <vector> # include <bitset> # include <map> # include <queue> # include <ctime> # include <stack> # include <set> # include <list> # include <random> ...
1080
B
Margarite and the best present
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them. Recently, she was presented with an array $a$ of the size of $10^9$ elements that is filled as follows: - $a_1 = -1$ - $a_2 = 2$ - $a_3 = -3$ - $a_4 = 4$ - $a_5 = -5$ - And so on ... That is...
At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements of the array that have indices from $1$ to $x$ inclusive. In order to calculate the function in a fast and easy way let's split the task into two parts: If $x$ is even, then the sum is equal to: $f(x) = -1 + 2 - 3 + 4 ...
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; long long F(long long x) { if(x % 2 == 0) return x / 2; else return -x + F(x-1); } int main() { int t; cin >> t; while(t--) { int l,r; cin >> l >> r; cout << F(r) - F(l-1) << '\n'; } return 0; }
1080
C
Masha and two friends
Recently, Masha was presented with a chessboard with a height of $n$ and a width of $m$. The rows on the chessboard are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. Therefore, each cell can be specified with the coordinates $(x,y)$, where $x$ is the \textbf{...
At first let's define a function $w(a,b)$, which returns the number of white cells on the subrectangle, the left bottom corner of which has coordinates $(1,1)$ and the top right one has coordinates $(a,b)$. (I will tell you how to implement the function later). How do we solve the problem using this function? Let's def...
[ "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; long long cdiv(long long x, long long y) { return x / y + (x%y>0); } long long w(long long a, long long b) { return cdiv(a,2) * cdiv(b,2) + (a/2) * (b/2); } long long W(long long x1, long long y1, long long x2, long long y2) { return w(x2,y2) - w(x2,y1-1) ...
1080
D
Olya and magical square
Recently, Olya received a magical square with the size of $2^n\times 2^n$. It seems to her sister that one square is boring. Therefore, she asked Olya to perform \textbf{exactly} $k$ splitting operations. A Splitting operation is an operation during which Olya takes a square with side $a$ and cuts it into 4 equal squ...
At first let's check if the value of $k$ is not too large. This can be done greedily in the folllowing way: First splitting operation would be applied on the only existing inital square. After that we have $4$ squares with sides $2^{n-1}$. Now we will do $4$ spliiting operations each on one of them. Then we will have $...
[ "constructive algorithms", "implementation", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; inline long long getLen(long long n, long long k) { long long divisions = 1; k--; long long len = 1; while(divisions < n && k >= 4 * len - 1) { k -= 4 * len - 1; len *= 2; divisions++; } return n - divisions; } int mai...
1080
E
Sonya and Matrix Beauty
Sonya had a birthday recently. She was presented with the matrix of size $n\times m$ and consist of lowercase Latin letters. We assume that the rows are numbered by integers from $1$ to $n$ from bottom to top, and the columns are numbered from $1$ to $m$ from left to right. Let's call a submatrix $(i_1, j_1, i_2, j_2)...
Suppose we have a submatrix and we want to check whether it is beautiful. First, each line must have a maximum of one character that occurs an odd number of times. Why is this enough to ensure that each line can be made a palindrome by reordering the characters in it? If there is exactly one character that occurs an od...
[ "strings" ]
2,400
# include <iostream> # include <cmath> # include <algorithm> # include <stdio.h> # include <cstdint> # include <cstring> # include <string> # include <cstdlib> # include <vector> # include <bitset> # include <map> # include <queue> # include <ctime> # include <stack> # include <set> # include <list> # include <random> ...
1080
F
Katya and Segments Sets
It is a very important day for Katya. She has a test in a programming class. As always, she was given an interesting problem that she solved very fast. Can you solve that problem? You are given $n$ ordered segments sets. Each segment can be represented as a pair of two integers $[l, r]$ where $l\leq r$. Each set can c...
Let's have an array in which we will store each segment and the number of the set to which it belongs. Sort this array in the non-decreasing order of the left border. If the left border is equal, we sort in random order. Now consider any query $a$ $b$ $x$ $y$. We should find the first position where the left border of ...
[ "data structures", "interactive", "sortings" ]
2,400
# include <iostream> # include <cmath> # include <algorithm> # include <stdio.h> # include <cstdint> # include <cstring> # include <string> # include <cstdlib> # include <vector> # include <bitset> # include <map> # include <queue> # include <ctime> # include <stack> # include <set> # include <list> # include <random> ...
1081
A
Definite Game
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following op...
1 sounds like the minimum value we can get. Why? Is it always true? When $n \le 2$, we can do nothing. When $n \ge 3$, since $1\,<\,\frac{n}{n-1}<2$, $n - 1$ isn't a divisor of $n$, so we can choose it and get $1$ as the result.
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); if (n == 2) { puts("2"); } else { puts("1"); } return 0; }
1081
B
Farewell Party
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced. Chouti remembered that $n$ persons took part in that party. To make the party funnier, each person wore one hat among $n$ kinds...
Consider the number of people wearing hats of the same color. let $b_{i} = n - a_{i}$ represent the number of people wearing the same type of hat of $i$-th person. Notice that the person wearing the same type of hat must have the same $b$s. Suppose the number of people having the same $b_{i}$ be $t$, there would be exa...
[ "constructive algorithms", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int maxn = 100010; int n; pair<int,int> a[maxn]; int Ans[maxn],cnt; int main(){ ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++){ cin>>a[i].first; a[i].first=n-a[i].first; a[i].second=i; } sort(a+1,a+n+1); for(...
1081
C
Colorful Bricks
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard. There are $n$ bricks lined in a row on the ground. Chouti has got $m$ paint buckets of different colors at hand, so he painted each brick in one of those $m$ colors. Having finished painting all bricks, Chouti...
No hint here :) Let $f[i][j]$ be the ways that there're $j$ bricks of a different color from its left-adjacent brick among bricks numbered $1$ to $i$. Considering whether the $i$-th brick is of the same color of $i - 1$-th, we have $f[i][j] = f[i - 1][j] + f[i - 1][j - 1](m - 1)$. $f[1][0] = m$ and the answer is $f[n][...
[ "combinatorics", "dp", "math" ]
1,500
//linear #include <bits/stdc++.h> using namespace std; const int MOD=998244353; typedef long long ll; ll fac[2333],rfac[2333]; ll qp(ll a,ll b) { ll x=1; a%=MOD; while(b) { if(b&1) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } int n,m,k; int main() { scanf("%d%d%d",&n,&m,&k); fac[0]=1; for(int i=1;i<=n;++i) ...
1081
D
Maximum Distance
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago. You are given a connected undirected graph with $n$ vertices and $m$ weighted edges. There are $k$ special vertices: $x_1, x_2, \ldots, x_k$. Let's define the cost of the path as the \textbf{maximum} weight of t...
Consider the MST of the graph. Consider the minimum spanning tree formed from the $n$ vertexes, we can find that the distance between two vertexes is the maximum weight of edges in the path between them in the minimum spanning tree (it's clear because of the correctness of Kruskal algorithm). Take any minimum spanning ...
[ "dsu", "graphs", "shortest paths", "sortings" ]
1,800
#include<bits/stdc++.h> #define L long long #define vi vector<int> #define pb push_back using namespace std; int n,m,t,f[100010],p; bool a[100010]; inline int fa(int i) { return f[i]==i?i:f[i]=fa(f[i]); } struct edge { int u,v,w; inline void unit() { u=fa(u); v=fa(v); if(u!=v) ...
1081
E
Missing Numbers
Chouti is working on a strange math problem. There was a sequence of $n$ positive integers $x_1, x_2, \ldots, x_n$, where $n$ is even. The sequence was very special, namely for every integer $t$ from $1$ to $n$, $x_1+x_2+...+x_t$ is a square of some integer number (that is, a perfect square). Somehow, the numbers wit...
How to solve $n = 2$? Let $s_{i}=\sum_{j=1}^{t}x_{j}=t_{i}^{2}$, $x_{max} = 2 \times 10^{5}$. Since $x_{2i} = s_{2i} - s_{2i - 1} = t_{2i}^{2} - t_{2i - 1}^{2} \ge (t_{2i - 1} + 1)^{2} - t_{2i - 1}^{2} = 2t_{2i - 1} + 1$, so $2t_{2i - 1} + 1 \le x_{max}$, $t_{2i - 1} < x_{max}$. For every $x\in[1,x_{m a x}]$, we ...
[ "binary search", "constructive algorithms", "greedy", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n; vector<int> d[200099]; ll su[100099],x[100099]; int main() { for(int i=1;i<=200000;++i) for(int j=i;j<=200000;j+=i) d[j].push_back(i); scanf("%d",&n); for(int i=2;i<=n;i+=2) scanf("%lld",x+i); for(int i=2;i<=n;i+=2) { for(auto j:d[...
1081
F
Tricky Interactor
\textbf{This is an interactive problem.} Chouti was tired of studying, so he opened the computer and started playing a puzzle game. Long long ago, the boy found a sequence $s_1, s_2, \ldots, s_n$ of length $n$, kept by a tricky interactor. It consisted of $0$s and $1$s only and the number of $1$s is $t$. The boy know...
What about parity? Assuming the number of $1$s changed from $a$ to $b$ after flipping a range of length $s$. Let the number of $1$s in the range before this flip be be $t$, then $b - a = (l - t) - t = s - 2t$, so $b-a\equiv s({\mathrm{mod}}\ 2)$. So if we made a query $l, r$, the parities of the lengths of $[1, r]$ and...
[ "constructive algorithms", "implementation", "interactive" ]
2,600
#include <bits/stdc++.h> using namespace std; int n,ss[10005],sn=0,q[333]; bool tf(int l,int r) { cout<<"? "<<l<<" "<<r<<endl<<flush; cin>>ss[++sn]; return (ss[sn]-ss[sn-1])&1; } int main() { cin>>n>>ss[0]; q[n]=ss[0]; for(int i=1;i<n;++i) { int j=i-n%2; if(j==0) { int t[2]={0,0},u=ss[sn]; while(t[0]!...