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 ⌀ |
|---|---|---|---|---|---|---|---|
848 | A | From Y to Y | From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of $n$ lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length $1$, and repeat the following operation $n - 1$ times:
- Remove any two elements $s$... | For a given string, how to calculate the cost? With several experiments, you may have found that the "minimum cost" doesn't make sense - the cost is always the same no matter how the characters are concatenated. Precisely, the cost of the process for a multiset of $c_{1}$ a's, $c_{2}$ b's, ... and $c_{26}$ z's, is $\te... | [
"constructive algorithms"
] | 1,600 | #include <cstdio>
#include <vector>
static const int MAXK = 100002;
static const int INF = 0x3fffffff;
int f[MAXK];
int pred[MAXK];
int main()
{
f[0] = 0;
for (int i = 1; i < MAXK; ++i) f[i] = INF;
for (int i = 0; i < MAXK; ++i) pred[i] = -1;
for (int i = 0; i < MAXK; ++i) if (f[i] != INF) {
... |
848 | B | Rooter's Song | Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size $w × h$, represented by a rectangle with corners $(0, 0)$, $(w, 0)$, $(w, h)$ and $(0, h)$. It can be seen that no collisions will happen before one enters the stage.
On the ... | How to deal with "waiting time"? Move every dancer $t_{i}$ units backwards in the first place, that is to $(x_{i} - t_{i}, 0)$ for the vertical-moving group, and $(0, y_{i} - t_{i})$ for the horizontal-moving group. Then start the time, making everyone start moving immediately. When do dancers collide? What changes and... | [
"constructive algorithms",
"data structures",
"geometry",
"implementation",
"sortings",
"two pointers"
] | 1,900 | #include <cstdio>
#include <algorithm>
#include <vector>
static const int MAXN = 100004;
static const int MAXW = 100003;
static const int MAXT = 100002;
int n, w, h;
int g[MAXN], p[MAXN], t[MAXN];
std::vector<int> s[MAXW + MAXT];
int ans_x[MAXN], ans_y[MAXN];
int main()
{
scanf("%d%d%d", &n, &w, &h);
for (in... |
848 | C | Goodbye Souvenir | I won't feel lonely, nor will I be sorrowful... not before everything is buried.
A string of $n$ beads is left as the message of leaving. The beads are numbered from $1$ to $n$ from left to right, each having a shape numbered by integers between $1$ and $n$ inclusive. Some beads may have the same shapes.
The \underli... | Let's look at segment $[l, r]$. Let's $p_{1}^{x} < p_{2}^{x} < ... < p_{k}^{x}$ - positions of all occurences of shape $x$ at segment $[l, r]$. Then memory of shape $x$ at segment $[l, r]$ is $p_{k}^{x} - p_{1}^{x} = (p_{k}^{x} - p_{k - 1}^{x}) + (p_{k - 1}^{x} - p_{k - 2}^{x}) + ... + (p_{2}^{x} - p_{1}^{x})$. Then we... | [
"data structures",
"divide and conquer"
] | 2,600 | #include <bits/stdc++.h>
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
#define all(a) (a).begin(), (a).end()
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define mp make_pair
#define pb push_back
#define x first
#define y second
using namespace std;
template<... |
848 | D | Shake It! | A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.
A \underline{world} is an unordered graph $G$, in whose vertex set $V(G)$ there are two special vertices $s(G)$ and $t(G)$. An \underline{initial world} has vertex set ${s(G), t(G)}$ and an edge between them.
A total of $n$ changes ... | Use DP. Let's try to find "subproblems" in this. A graph can be expressed as: an edge, in parallel with an unordered multiset of zero or more ordered pair of two graphs. That is, "graph = edge [// (graph + graph) [// (graph + graph) [...]]]". A graph can be represented by two parameters: number of operations needed to ... | [
"combinatorics",
"dp",
"flows",
"graphs"
] | 2,900 | #include <cstdio>
#include <cstring>
typedef long long int64;
static const int MAXN = 53;
static const int MODULUS = 1e9 + 7;
#define _ % MODULUS
#define __ %= MODULUS
int n, m;
// f[# of operations][mincut] -- total number of graphs
// g[# of operations][mincut] -- number of ordered pairs of two graphs
int64 f[MAXN... |
848 | E | Days of Floral Colours | The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.
On the rim of the Floral Clock are $2n$ flowers, numbered from $1$ to $2n$ clockwise, each of which has a colour among all $n$ possible ones. For each col... | tl;dr Just look at recurrences of $g$, $f_{0}$, $f_{1}$ and $f_{2}$ and the part after $f_{2}$'s recurrence. Break the circle down into semicircles. We're basically pairing flowers under the restrictions. It's hard to deal with the whole circle, let's consider something simpler. Consider an arc of length $i$ (segment o... | [
"combinatorics",
"divide and conquer",
"dp",
"fft",
"math"
] | 3,400 | #include <cstdio>
#include <cstring>
typedef long long int64;
static const int LOGN = 18;
static const int MAXN = 1 << LOGN;
static const int MODULUS = 998244353;
static const int PRIMITIVE = 2192;
#define _ % MODULUS
#define __ %= MODULUS
template <typename T> inline void swap(T &a, T &b) { static T t; t = a; a = b;... |
849 | A | Odds and Ends | Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence $a_{1}, a_{2}, ..., a_{n}$ of length $n$. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numb... | What will the whole array satisfy if the answer is Yes? An odd number of segments, each having an odd length. Thus the whole array needs to have an odd length. All segments starts and ends with odd numbers, so the array begins and ends with odd numbers as well. Is that a sufficient condition? Yes, because for an array ... | [
"implementation"
] | 1,000 | #include <cstdio>
static const int MAXN = 102;
int n;
int a[MAXN];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
puts((n % 2 == 1) && (a[0] % 2 == 1) && (a[n - 1] % 2 == 1) ? "Yes" : "No");
return 0;
} |
849 | B | Tell Your World | Connect the countless points with lines, till we reach the faraway yonder.
There are $n$ points on a coordinate plane, the $i$-th of which being $(i, y_{i})$.
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on \textbf{exactly one} of them, and each... | First way: consider the first three points. What cases are there? Denote them as $P_{1}(1, y_{1})$, $P_{2}(2, y_{2})$ and $P_{3}(3, y_{3})$. A possible Yes solution falls into one of these three cases: one of the lines pass through $P_{1}$ and $P_{2}$; passes through $P_{1}$ and $P_{3}$; or passes through $P_{2}$ and $... | [
"brute force",
"geometry"
] | 1,600 | #include <cstdio>
#include <algorithm>
static const int MAXN = 1004;
int n;
int y[MAXN];
bool on_first[MAXN];
bool check()
{
for (int i = 1; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if ((long long)i * (y[j] - y[0]) == (long long)j * (y[i] - y[0]))
on_first[j] = true;
... |
850 | A | Five Dimensional Points | You are given set of $n$ points in 5-dimensional space. The points are labeled from $1$ to $n$. No two points coincide.
We will call point $a$ bad if there are different points $b$ and $c$, not equal to $a$, from the given set such that angle between vectors $\;{\vec{a}}{\vec{b}}$ and ${\vec{a c}}$ is acute (i.e. stri... | It's easier to visualize this in 2D first. Fix a point $p$. If all other points form angles that are 90 degrees or greater, they must all be in different quadrants, so there can be at most 4 such points. In k dimension, this generalizes to 2*k such points, so for five dimensions, there can only be at most 10 other poin... | [
"brute force",
"geometry",
"math"
] | 1,700 | null |
850 | B | Arpa and a list of numbers | Arpa has found a list containing $n$ numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is $1$.
Arpa can perform two types of operations:
- Choose a number and delete it with cost $x$.
- Choose a number and increase it by $1$ with cost $... | Let's define $cost(g)$ the cost if we want gcd of the array becomes $g$. The answer is $min cost(g)$ for $g > 1$. Now, let's see how to calculate $cost(g)$. For each number like $c$, we can delete it with cost $x$ or we can add it till $g$ divides it. So, we must pay $\operatorname*{min}(x,y\times(\lceil{\frac{\epsilon... | [
"implementation",
"number theory"
] | 2,100 | null |
850 | C | Arpa and a game with Mojtaba | Mojtaba and Arpa are playing a game. They have a list of $n$ numbers in the game.
In a player's turn, he chooses a number $p^{k}$ (where $p$ is a prime number and $k$ is a positive integer) such that $p^{k}$ divides at least one number in the list. For each number in the list divisible by $p^{k}$, call it $x$, the pla... | The problem is separate for each prime, so we will calculate Grundy number for each prime and xor these number to find the answer. Now let's solve the problem for some prime like $p$. Let's show the game with a $mask$, $i$-th bit of $mask$ is true if and only if there is a number in the list such that it is divisible b... | [
"bitmasks",
"dp",
"games"
] | 2,200 | null |
850 | D | Tournament Construction | Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex.
Yesterday Ivan learned Landau's criterion: there is tournament with scores $d_{1} ≤ d_{2} ≤ ...... | Let $n$ be the number of players participating in the tournament. First of all, note that $n \le 61$, since the total number of wins must be $\textstyle{\frac{n\times(n-1)}{2}}$, and there can be no more than $30 \times n$, therefore ${\frac{n\times(n-1)}{2}}\leq30\times n$, hence $n \le 61$. Next, we find an app... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"math"
] | 2,800 | null |
850 | E | Random Elections | The presidential election is coming in Bearland next year! Everybody is so excited about this!
So far, there are three candidates, Alice, Bob, and Charlie.
There are $n$ citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, ... | $b_{k}(x)$ denotes $i$-th bit of $x$. ${\mathrm{pop}}(x)$ denotes number of bits in $x$. Count number of ways where Alice wins. Suppose Alice wins in first round with mask $x$ and in third round with mask $y$ (so, $b_{i}(x) = 1$ or $b_{i}(y) = 1$ if $i$ voter preferred Alice in corresponding round). Necessary condition... | [
"bitmasks",
"brute force",
"divide and conquer",
"fft",
"math"
] | 2,800 | null |
850 | F | Rainbow Balls | You have a bag of balls of $n$ different colors. You have $a_{i}$ balls of the $i$-th color.
While there are at least two different colored balls in the bag, perform the following steps:
- Take out two random balls without replacement one by one. These balls might be the same color.
- Color the second ball to the col... | First, let's fix the final color of the balls. After fixing the final color, we can see the other colors don't matter. Define an "interesting" draw as one where we choose a ball of the final color and one of a different color. Once we do an interesting draw, we can see there is an equal probability of increasing or dec... | [
"math"
] | 2,800 | null |
851 | A | Arpa and a research in Mexican wave | Arpa is researching the Mexican wave.
There are $n$ spectators in the stadium, labeled from $1$ to $n$. They start the Mexican wave at time $0$.
- At time $1$, the first spectator stands.
- At time $2$, the second spectator stands.
- $...$
- At time $k$, the $k$-th spectator stands.
- At time $k + 1$, the $(k + 1)$-t... | Another solution: just print $min(t, k, n + k - t)$. | [
"implementation",
"math"
] | 800 | null |
851 | B | Arpa and an exam about geometry | Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points $a, b, c$.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of $a$ is the same as the old position of $b$, and the new position of $b$ is the same as the old positi... | If $a, b, c$ are on the same line or $dis(a, b) \neq dis(b, c)$, the problem has not any solution. | [
"geometry",
"math"
] | 1,400 | null |
853 | A | Planning | Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are $n$ flights that must depart today, the $i$-th of them is planned to depart at the $i$-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. Thi... | We will show that following greedy is correct: let's for each moment of time use a plane, which can depart in this moment of time (and didn't depart earlier, of course) with minimal cost of delay. Proof is quite simple: it's required to minimize $\sum_{i=1}^{n}c_{i}\cdot(t_{i}-i)=\sum_{i=1}^{n}c_{i}\cdot t_{i}-\sum_{i=... | [
"greedy"
] | 1,500 | null |
853 | B | Jury Meeting | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are $n + 1$ cities consecutively numbered from $0$ to $n$. City $0$ is Metropolis that is the meeting p... | Obviously, each member of the jury needs to buy exactly two tickets - to the capital and back. Sort all flights by the day of departure. Now go through flights to the capital (forward flights) and one by one assume it is the last forward flight in answer (let's say it is scheduled on day $d$). Thus you are assuming tha... | [
"greedy",
"sortings",
"two pointers"
] | 1,800 | null |
853 | C | Boredom | Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.
First Ilya has drawn a grid of size $n × n$ and marked $n$ squares on it, such that no two marked squar... | We can't iterate over all interesting rectangles. Let's count number of rectangles that are not intersecting our rectangle. To do it let's calculate number of rectangles to the left, right, up and down of rectangle in query. It can be easily done in $O(1)$ time: suppose we have rectangle with corners $(i;p_{i})$ and $(... | [
"data structures"
] | 2,100 | null |
853 | D | Michael and Charging Stations | Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.
Michael's day starts from charging his electric car for getting to the work and back. He spends $1000$ burles on charge if he goes to the first job, and $2000$ burles... | Before solving problem one observation is required: suppose at day $i$ we have $x_{i}$ bonuses. Then exists optimal solution, which spends $0$ or $min(a_{i}, x_{i})$ bonuses every day. It's quite easy to proof: suppose we have some optimal solution and $i$ is a first day, when neither $0$ nor $min(a_{i}, x_{i})$ bonuse... | [
"binary search",
"dp",
"greedy"
] | 2,400 | null |
853 | E | Lada Malina | After long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines.
Consider car as a point in $Oxy$ plane. Car is equipped wi... | In the original contest there were subtasks for this problem and it's more convinient to understand the editorial going through these subtasks, so we will leave them here. The key part of a solution is to understand what are the locations that may be accessed from the origin in $T$ seconds. First observation is that we... | [
"data structures",
"geometry"
] | 3,400 | null |
854 | A | Fraction | Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction $\frac{a}{b}$ is called proper iff its numerator is smaller than its denominator ($a < b$) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have posit... | It's possible to look over all possible values of the numerator $1\leqslant a\leqslant\lfloor{\frac{n}{2}}\rfloor$. For the current value of $a$ we have to compute denominator as $b = n - a$, check that there are no common divisors (except $1$) of $a$ and $b$ (it also could be done by a linear search of possible common... | [
"brute force",
"constructive algorithms",
"math"
] | 800 | null |
854 | B | Maxim Buys an Apartment | Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has $n$ apartments that are numbered from $1$ to $n$ and are arranged in a row. Two apartments are adjacent if their indices differ by $1$. Some of the apartments can already be inhabited, others are available for sale.
Maxim often ... | Minimum number of good apartments is almost always $1$, since rooms with indices from $1$ to $k$ could be inhabited. Exceptions are cases in which $k = 0$ and $k = n$, in these cases both minimum and maximum number of good rooms is $0$ since there is no inhabitant or vacant apartments. Maximum number of good apartments... | [
"constructive algorithms",
"math"
] | 1,200 | null |
855 | A | Tom Riddle's Diary | Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | For each string $s_{i}$ iterate $j$ from $1$ to $i - 1$. Check if $s_{i} = s_{j}$ for any value of $j$. If it is output "YES", otherwise output "NO". Output will always be "NO" for the first string. The expected complexity was $O(n^{2}\cdot\operatorname*{max}_{1\leq i\leq n}(|s_{i}|))$ | [
"brute force",
"implementation",
"strings"
] | 800 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,int... |
855 | B | Marvolo Gaunt's Ring | Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he... | There can be two approaches: First solution : Create a dynamic programming table of size $n \cdot 3$. In this, $dp[i][0]$ stores maximum of value $p \cdot a_{x}$ for $x$ between $1$ and $i$. Similarly $dp[i][1]$ stores the maximum value of $p \cdot a_{x} + q \cdot a_{y}$ such that $x \le y \le i$ and $dp[i][2]$ sto... | [
"brute force",
"data structures",
"dp"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define pi pair<int,int>
#define pii pair<pi,int>
#define mp make_pair
int minleft... |
855 | C | Helga Hufflepuff's Cup | Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank.
The Wizarding bank is in the form of a tree with total $n$ vaults where each vault h... | This problem can be solved by using the concept of dp on trees. The dp table for this problem will be of the size $n \cdot 3 \cdot x$. We can assume any one node as the root and apply dfs while computing the dp array. Let the root be $1$. Here, $dp[curr][0][cnt]$ represent the number of ways of assigning type to each n... | [
"dp",
"trees"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,int... |
855 | D | Rowena Ravenclaw's Diadem | Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her.
Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry i... | In this problem, the relations "is a part of" and "is a special case of" were transitive. And also, if some object "a" had "b" as its special case and "c" as its part, "c" was also a part of "b". Now, when we need to process the queries, we use the concept of lowest common ancestor (lca). For query $1 u v$, answer will... | [
"trees"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define pi pair<int,int>
#define pii pair<pi,int>
#define mp make_pair
vector<int>... |
855 | E | Salazar Slytherin's Locket | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts... | This problem can be solved using precomputation of dp table $dp[base][mask][len]$. This stores the number of integers in base $b$ and length $len$ that forms the given $mask$ in their representation. The $mask$ is defined as having $i - th$ bit as $1$, if the digit $i - 1$ occurs odd number of times in the representati... | [
"bitmasks",
"dp"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%lld",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,i... |
855 | F | Nagini | Nagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school.
Hogwarts' entrance can be imagined as a straight line (x-axis) from $1$ to $10^{5}$. Nagini is launching various snakes at the Hogwarts entrance. Each snake ... | This problem can be solved by using the concept of square root decomposition. Let us divide the total range of x-axis, that is, from $1$ to $10^{5}$ in $\sqrt{10^{5}}$. Then, blockSize = $\sqrt{10^{5}}$, and number of blocks, $n_{b}$ = $10^{5} / blockSize$. Now, we maintain the following structures: An array $ans$ that... | [
"binary search",
"data structures"
] | 3,100 | #include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define fi first
#define se second
#define pi pair<int,int>
#define pii pair<pi,in... |
855 | G | Harry Vs Voldemort | After destroying all of Voldemort's Horcruxes, Harry and Voldemort are up for the final battle. They each cast spells from their wands and the spells collide.
The battle scene is Hogwarts, which can be represented in the form of a tree. There are, in total, $n$ places in Hogwarts joined using $n - 1$ undirected roads.... | At first let's solve the problem for the initial tree. You can use dynamic programming. The second part of the problem was to realize that we need to count the triple $(u, v, w)$ if and only if the following condition holds: $w$ is in a edge-2-connectivity component that is on the path from the edge-2-connectivity comp... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
#ifdef WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
#define pb push_back
#define mp make_pair
#define all(x) (x... |
856 | A | Set Theory | Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set $A$ containing $n$ different integers $a_{i}$ on a blackboard. Now he asks Masha to create a set $B$ containing $n$ different integers $b_{j}$ such that all $n^{2}$ integers that can be obtained by summing up $a_{i}$ and $b_{j}$... | First let us prove that the answer is always YES. Let us iterate over $b_{j}$ and check if summing it up with all $a_{i}$ values don't result in values that we already have. If no conflict is found, add the corresponding $b_{j}$ to $B$. Let us give some estimate for the maximum element of $B$. The reason that we cannot... | [
"brute force",
"constructive algorithms"
] | 1,600 | null |
856 | B | Similar Words | Let us call a non-empty sequence of lowercase English letters a \underline{word}. \underline{Prefix} of a word $x$ is a word $y$ that can be obtained from $x$ by removing zero or more last letters of $x$.
Let us call two words \underline{similar}, if one of them can be obtained from the other by removing its first let... | Let us consider the following similarity graph: the vertices are the prefixes of the given words, two vertices are connected by an edge if the corresponding words are similar. Note that the set of vertices in this graph is the same as in the trie for the given words, so it doesn't exceed the sum of lengths of words. Le... | [
"dp",
"hashing",
"strings",
"trees"
] | 2,300 | null |
856 | C | Eleventh Birthday | It is Borya's eleventh birthday, and he has got a great present: $n$ cards with numbers. The $i$-th card has the number $a_{i}$ written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers $1$, $31$, and $12$, and he puts them in a row in this order, he wo... | Let us use divisibility rule for eleven. The number is divisible by eleven if the sum of digits at odd positions is equal to the sum of digits at even positions modulo 11. So for each number on a card there are only two parameters that we care about: the sign interchanging sum of its digits with digits at odd positions... | [
"combinatorics",
"dp",
"math"
] | 2,400 | null |
856 | D | Masha and Cactus | Masha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.
Recall that \underline{tree} is a connected undirected graph that has no cycles. \underline{Cactus} is a connected undirected graph such that each vertex belongs to at most one cycle.... | Let us use dynamic programming for a rooted tree and some data structures. Denote as $f_{v}$ the maximal total beauty of edges that have both ends in a subtree of $v$, such that if we add them all to the subtree it would be a cactus. To calculate $f_{v}$ let us consider two cases: $v$ belongs to some cycle, or it doesn... | [
"dp",
"trees"
] | 2,400 | null |
856 | E | Satellites | Real Cosmic Communications is the largest telecommunication company on a far far away planet, located at the very edge of the universe. RCC launches communication satellites.
The planet is at the very edge of the universe, so its form is half of a circle. Its radius is $r$, the ends of its diameter are points $A$ and ... | Any point $X$ can be given by two angles $ \alpha = XAB$ and $ \beta = XBA$. The point $( \alpha _{2}, \beta _{2})$ is in coverage area of a satellite at the point $( \alpha _{1}, \beta _{1})$, if $ \alpha _{2} \le \alpha _{1}$ and $ \beta _{2} \le \beta _{1}$. Let two satellites that want to create a communi... | [] | 3,100 | null |
856 | F | To Play or not to Play | Vasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he pla... | Let us introduce coordinates $y(x)$, where $x = exp_{1} - exp_{2}$, and $y = exp_{1}$ ($exp_{1}$, $exp_{2}$ - experience of the first and the second player, respectively). Let us proceed with time, and keep the set of possible states at this plane. It is a polygon. Lemma 1: in the optimal solution if at some moment bot... | [
"greedy"
] | 3,000 | null |
858 | A | k-rounding | For a given positive integer $n$ denote its $k$-rounding as the minimum positive integer $x$, such that $x$ ends with $k$ or more zeros in base $10$ and is divisible by $n$.
For example, $4$-rounding of $375$ is $375·80 = 30000$. $30000$ is the minimum integer such that it ends with $4$ or more zeros and is divisible ... | Notice that the number $x$ ends with $k$ or more zeros if the maximal power of $2$ that is a divisor of $x$ is at least $k$ and the maximal power of $5$ that is a divisor of $x$ is at least $k$. Let's calculate the maximal powers of $2$ and $5$ that are divisors of $n$. If any of the powers is less than $k$ then multip... | [
"brute force",
"math",
"number theory"
] | 1,100 | null |
858 | B | Which floor? | In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from $1$ from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are... | We will store our current answer in some variable $ans$. Initially it is -1. Let's iterate over the quantity of the flats on each floor (it will be from 1 to 100 inclusive). Let it be $cf$. Then we have to check that this quantity coincides with given input. If $\textstyle\left[{\frac{k_{i}}{c f}}\right]\neq f_{i}$ for... | [
"brute force",
"implementation"
] | 1,500 | null |
858 | C | Did you mean... | Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr... | We will solve the problem greedily. Let's find the leftmost typo. It will be three consecutive characters $s_{i - 1}, s_{i}$ and $s_{i + 1}$ such that all of them are consonants and there are at least two diffirent letters. It is clear that we can cut this string after position $i$, because prefix will be correct and w... | [
"dp",
"greedy",
"implementation"
] | 1,500 | null |
858 | D | Polycarp's phone book | There are $n$ phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from $0$. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for... | Find the shortest substring of each string such that it doesn't appear in any other string as a substring. For each substring let's store the index of the string which contains this substring or $- 1$ if there are more than one such string. Iterate over all substrings which have values that are not $- 1$ and update the... | [
"data structures",
"implementation",
"sortings"
] | 1,600 | null |
858 | E | Tests Renumeration | The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to re... | Firstly we will get rid of all tests that are already named correctly. After this, let's call samples "tests of 1 type", and system tests "tests of 2 type". Let's denote "free positions" such indices $i\ (i\in[1..n])$ such that there is currently no test with the name $i$. If there are no any free positions, then we ca... | [
"greedy",
"implementation"
] | 2,200 | null |
858 | F | Wizard's Tour | All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!
It is well-known that there are $n$ cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that ... | Obviously the task can be solved independently for each component. Here is the algorithm that allows you to reach exactly $\lfloor{\frac{m}{2}}\rfloor$ tours, where $m$ is the number of edges in the component. Let's take arbitrary tree built by depth-first search. While exiting vertex $v$, we can process all the edges ... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,300 | null |
859 | A | Declined Finalists | This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible ... | If all ranks are 25 or less, then the answer is 0, since it's possible that all of the top 25 accepted the invitation. Otherwise, notice that the highest invited rank is initially 25, and increases by 1 every time a contestant declines. Therefore the answer is simply the highest rank minus 25. | [
"greedy",
"implementation"
] | 800 | null |
859 | B | Lazy Security Guard | Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly $N$ city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly $N$ blocks. Your friend is quite ... | Let's ask the problem a different way. For a fixed perimeter, what's the maximum number of city blocks we can fit in it? The maximum will always be achieved by a rectangle, because that's the only shape that doesn't contain any $270^{\circ}$ angles. A $270^{\circ}$ angle is not allowed because there would be a way to a... | [
"brute force",
"geometry",
"math"
] | 1,000 | null |
859 | C | Pie Rules | You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ... | Denote $Score(L)$ as the total sizes of slices that will be eaten by whoever holds the decider token, for a list of pies $L$, and denote $Total(L)$ as the total size of all slices, and $Rest(L)$ as the list of pies formed by removing the first pie. Note that the total sizes of slices eaten by whoever doesn't hold the d... | [
"dp",
"games"
] | 1,500 | null |
859 | D | Third Month Insanity | The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of $2^{N}$ teams participating in the tournament, numbered from $1$ to $2^{N}$. The tournament lasts $N$ rounds, with each round eliminating half the teams. The first round con... | Denote $opp(r, t)$ as the set of teams that could play against team $t$ in round $r$, and $w[t][u]$ is the probability that team $t$ defeats team $u$. We would first like to compute the probability that team $t$ wins a game in round $r$, and call this $p[r][t]$. Set $p[0][t] = 1$ for all teams for convenience. Then for... | [
"dp",
"probabilities",
"trees"
] | 2,100 | null |
859 | E | Desk Disorder | A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at,... | Consider an undirected graph where the desks are vertices and the engineers are edges. For each engineer an edge connects their current desk to their desired desk. Each connected component of this graph can be assigned independently, with the final result being the product of the number of assignments over the individu... | [
"combinatorics",
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,100 | null |
859 | F | Ordering T-Shirts | It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top $C$ contestants are going to be awarded T-shirts, but we obviously d... | Let us first describe how to tell if a given set of T-shirts is sufficient to award the competitors. For any set of T-shirt sizes, it clearly must be the case that the total number of T-shirts ordered of sizes in the set must be at least as large as the maximum number of competitors that could require a T-shirt size fr... | [
"greedy"
] | 2,800 | null |
859 | G | Circle of Numbers | $n$ evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number $k$. Then you may repeatedly select a set of $2$ or more points which are evenly spaced, and either increase all numbers at points in the set by $k$ or decrease all numbers a... | Construct polynomial $P(x) = s_{i} \cdot x^{i}$. For $p|n$ denote $Q_{p}(x) = 1 + x^{n / p} + x^{2n / p} + ... + x^{(p - 1)n / p} = (x^{n} - 1) / (x^{n / p} - 1)$. Our task is to determine if $P(x)$ can be written as a linear combination of $Q_{i}(x)$ polynomials. Bézout's Identity tells us that a solution exists if th... | [
"math"
] | 3,000 | null |
860 | E | Arkady and a Nobody-men | Arkady words in a large company. There are $n$ employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees.
Each employee has an integer rank. The CEO has rank ... | First of all, $ans[v] = ans[parent[v]] + depth[v] + ans'[v]$, where $ans'[v]$ is the sum of (number of descendants of the rank depth[v]) for all predecessors of $v$. All we need is to compute $ans'[v]$ now. Let's make a dfs in the graph. Let the dfs(v) return a vector $ret[v]$ such that $ret[v][d]$ is the following tup... | [
"data structures",
"dfs and similar",
"trees"
] | 2,700 | null |
862 | A | Mahmoud and Ehab and the MEX | Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of $n$ integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly $x$. the MEX... | One can see that in the final set all the elements less than $x$ should exist, $x$ shouldn't exist and any element greater than $x$ doesn't matter, so we will count the number of elements less than $x$ that don't exist in the initial set and add this to the answer, If $x$ exists we'll add 1 to the answer because $x$ sh... | [
"greedy",
"implementation"
] | 1,000 | "#include <iostream>\nusing namespace std;\nbool b[105];\nint main()\n{\n\tint n,x;\n\tscanf(\"%d%d\",&n,&x);\n\twhile (n--)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tb[a]=1;\n\t}\n\tint ans=b[x];\n\tfor (int i=0;i<x;i++)\n\tans+=!b[i];\n\tprintf(\"%d\",ans);\n}" |
862 | B | Mahmoud and Ehab and the bipartiteness | Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into $2$ sets in such a way, that for each edge $(u, v)$ that belongs to the graph, $u... | The tree itself is bipartite so we can run a dfs to partition the tree into the 2 sets (called bicoloring), We can't add an edge between any 2 nodes in the same set and we can add an edge between every 2 nodes in different sets, so let the number of nodes in the left set be $l$ and the number of nodes in the right set ... | [
"dfs and similar",
"graphs",
"trees"
] | 1,300 | "#include <iostream>\n#include <vector>\nusing namespace std;\nvector<int> v[100005];\nlong long cnt[2];\nvoid dfs(int node,int pnode,int color)\n{\n\tcnt[color]++;\n\tfor (int i=0;i<v[node].size();i++)\n\t{\n\t\tif (v[node][i]!=pnode)\n\t\tdfs(v[node][i],node,!color);\n\t}\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&... |
862 | C | Mahmoud and Ehab and the xor | Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer $x$. He asks Mahmoud and Ehab to... | $n = 2, x = 0$ is the only case with answer "NO" . Let $pw = 2^{17}$ . First print $1, 2, ..., n - 3$ (The first $n - 3$ positive integers), Let their bitwise-xor sum be $y$, If $x = y$ You can add $pw, pw * 2$ and $p w\oplus(p w*2)$, Otherwise you can add $0, pw$ and $p w\oplus x\oplus y$, We handled the case $x = y$ ... | [
"constructive algorithms"
] | 1,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int pw1=(1<<17);\nconst int pw2=(1<<18);\n\nint main()\n{\n\tint n,x;\n\tcin >> n >> x;\n\tif(n==1)\n\t\tcout << \"YES\\n\"<<x<<\"\\n\";\n\telse if(n==2&&x==0)\n\t\tcout << \"NO\\n\";\n\telse if(n==2)\n\t\tcout << \"YES\\n0 \"<<x<<\"\\n\";\n\telse\n\t{\n\t\tint... |
862 | D | Mahmoud and Ehab and the binary string | Mahmoud and Ehab are in the fourth stage now.
Dr. Evil has a hidden binary string of length $n$. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr... | In the editorial we suppose that the answer of some query is the number of correct guessed positions which is equal to $n$ minus hamming distance, The solutions in this editorial consider the answer of a query as $n$ minus real answer, For convenience. Common things : Let $zero(l, r)$ be a function that returns the num... | [
"binary search",
"divide and conquer",
"interactive"
] | 2,000 | "#include <iostream>\nusing namespace std;\nchar s[1005];\nint ans,pos0,pos1,n;\nvoid send()\n{\n\tprintf(\"? %s\\n\",s);\n\tfflush(stdout);\n\tscanf(\"%d\",&ans);\n\tans=n-ans;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\ts[i]='1';\n\tsend();\n\tint mans=ans;\n\ts[0]='0';\n\tsend();\n\tif (mans>a... |
862 | E | Mahmoud and Ehab and the function | Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array $a$ of length $n$ and array $b$ of length $m$. He introduced a function $f(j)$ which is defined for integers $j$, which satisfy $0 ≤ j ≤ m - n$. Suppose, $c_{i} = a_{i} - b_{i + j}$. Then $f(j) = |c_{1} - c_{2} + c_{3} - c_{4}... c_{n}|$. M... | Let's write $f(j)$ in another way:- $f(j)=\vert\sum_{i=1}^{n}(-1)^{i-1}*(a_{i}-b_{i+j})\vert=\vert\sum_{i=1}^{n}(-1)^{i-1}*a_{i}+(-1)^{i}*b_{i+j}\vert$ $=\left|\sum_{i=1}^{n}(-1)^{i-1}\ast a_{i}+\sum_{i=1}^{n}(-1)^{i}\ast b_{i+j}\right|$ Now we have 2 sums, The first one is constant (doesn't depend on $j$), For the sec... | [
"binary search",
"data structures",
"sortings"
] | 2,100 | "#include <iostream>\n#include <set>\nusing namespace std;\nint sign(int x)\n{\n\tif (x%2)\n\treturn -1;\n\treturn 1;\n}\nlong long absll(long long x)\n{\n\tif (x>0)\n\treturn x;\n\treturn -x;\n}\nset<long long> s;\nint b[100005];\nlong long ans(long long x)\n{\n\tset<long long>::iterator it=s.lower_bound(x);\n\tif (it... |
862 | F | Mahmoud and Ehab and the final stage | Mahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they ... | First, Let's get rid of the $LCP$ part . observation: $L C P(s t r_{1},s t r_{2},\cdot\cdot\cdot,s t r_{k})=\operatorname*{min}_{i=1}^{k-1}L C P(s t r_{i},s t r_{i+1})$, That could make us transform the $LCP$ part into a minimization part by making an array $lcp$ where $lcp_{i} = LCP(s_{i}, s_{i + 1})$, You could calcu... | [
"data structures",
"strings"
] | 2,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\nconst int BUBEN = (int)110;\n\nstruct Data {\n int goLeft[BUBEN], goRight[BUBEN];\n int res;\n int length;\n Data(int x) {\n x = min(x, BUBEN - 1);\n res = x;\n length = 1;\n for (int i = 0; i < BUBEN;... |
863 | A | Quasi-palindrome | Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String $t$ is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers $131$ and $2010200$ are quasi-palindromic, they can be transformed to ... | You can check if the given is quasi-palindromic by removing all the trailing zeros and checking if resulting string is a palindrome. | [
"brute force",
"implementation"
] | 900 | null |
863 | B | Kayaking | Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are $2·n$ people in the group (including Vadim), and they have exact... | Firstly let's learn how to split persons in pairs as if there are no single kayaks. Let there be people with weights $a$, $b$, $c$ and $d$ ($a \le b \le c \le d$). Obviously, the lowest instability you can achieve is $max(b - a, d - c)$. Swapping any two elements will only make the result greater. This greedy str... | [
"brute force",
"greedy",
"sortings"
] | 1,500 | null |
863 | C | 1-2-3 | Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
... | Notice that there are only $9$ possible patterns in this game. You can used in a following way. Simulate games till one of the patterns get repeated. Games between this pair of occurences will get you the same total outcome no matter when they are played. Let the distance between the games with the same pattern is $dif... | [
"graphs",
"implementation"
] | 1,800 | null |
863 | D | Yet Another Array Queries Problem | You are given an array $a$ of size $n$, and $q$ queries to it. There are queries of two types:
- $1$ $l_{i}$ $r_{i}$ — perform a cyclic shift of the segment $[l_{i}, r_{i}]$ to the right. That is, for every $x$ such that $l_{i} ≤ x < r_{i}$ new value of $a_{x + 1}$ becomes equal to old value of $a_{x}$, and new value ... | One can guess from the constraits that complexity of the algorithm should be either $O(nm + q)$ or $O(qm)$. And there is a solution with the second one. Let's try to solve the reversed problem - answer what position will some number be at after all the queries. Check the impact of some query on position $pos$. Let the ... | [
"data structures",
"implementation"
] | 1,800 | null |
863 | E | Turn Off The TV | Luba needs your help again! Luba has $n$ TV sets. She knows that $i$-th TV set will be working from moment of time $l_{i}$ till moment $r_{i}$, inclusive.
Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of \textbf{integer} momen... | Firstly let's compress the moments of time. Note that storing only $l$ and $r$ isn't enough (consider pairs ($[1, 2], [3, 4]$) and ($[1, 2], [4, 5]$)), you also should take $(l - 1)$. Now moments of time are up to $6 \cdot 10^{5}$. For every moment calculate the number of segments to cover it (make $cnt_{l} + = 1$ and ... | [
"data structures",
"sortings"
] | 2,000 | null |
863 | F | Almost Permutation | Recently Ivan noticed an array $a$ while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.
Ivan clearly remembers that there were $n$ elements in the array, and each element was not ... | This problem can be solved with mincost maxflow approach. Let's construct a following network: Construct a vertex for every number from $1$ to $n$. For each of these vertices add $n$ directed edges from the source to this vertex, the capacity of each edge will be $1$, and the costs will be $1, 3, 5, ..., 2n - 1$ (so pu... | [
"flows"
] | 2,200 | null |
863 | G | Graphic Settings | Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possibl... | If $m = 1$, then everything is simple. Cycle exists if $a[1] = 2$, and path exists if $b[1] = 1$ or $b[1] = a[1]$. Let's consider the case when $m = 2$. Let's call the combination odd if the sum of parameters is odd for this combination, and even otherwise. It's easy to see that if $a[1]$ and $a[2]$ are both odd, then ... | [] | 3,200 | null |
864 | A | Fair Game | Petya and Vasya decided to play a game. They have $n$ cards ($n$ is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (\textbf{different} from the number that Petya chose). During the game each player takes all the c... | This problem has many different solutions. Let's consider one of them. At first sort all numbers in non-descending order. Then the first $n / 2$ numbers must be equal to each other, the following $n / 2$ numbers must be equal to each other, and the number from the first half must be different from the number from the s... | [
"implementation",
"sortings"
] | 1,000 | null |
864 | B | Polycarp and Letters | Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string $s$ consisting only of lowercase and uppercase Latin letters.
Let $A$ be a set of positions in the string. Let's call it pretty if following conditions are met:
- letters on positions from $A$ in the string are all distinct and lowerca... | Let's solve the given problem in the following way. We will iterate through the letters in the string in order from left to right. If we are in position $pos$ and the next letter is uppercase we skip it. In the other case, we need to create $set$ and put letter $s_{pos}$ in it. After that we iterate through string to t... | [
"brute force",
"implementation",
"strings"
] | 1,000 | null |
864 | C | Bus | A bus moves along the coordinate line $Ox$ from the point $x = 0$ to the point $x = a$. After starting from the point $x = 0$, it reaches the point $x = a$, immediately turns back and then moves to the point $x = 0$. After returning to the point $x = 0$ it immediately goes back to the point $x = a$ and so on. Thus, the... | If the bus can not reach the first gas station (i.e. $b < f$) print -1. In the other case, the bus will reach the first gas station with $b - f$ liters in the gasoline tank. Then we need to iterate through journeys from $1$ to $k$ and calculate a value $need$ - how many liters of the gasoline needed to bus reach the ne... | [
"greedy",
"implementation",
"math"
] | 1,500 | null |
864 | D | Make a Permutation! | Ivan has an array consisting of $n$ elements. Each of the elements is an integer from $1$ to $n$.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integ... | We will use an array $cnt$ where we will store how many times the numbers from $1$ to $n$ met in the given array $a$. Put all numbers that never occur in the array $a$ in a vector $need$ - we must add this numbers in the array $a$ to make a permutation. We will add numbers from $need$ in ascending order because we want... | [
"greedy",
"implementation",
"math"
] | 1,500 | null |
864 | E | Fire | Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take $t_{i}$ seconds to save $i$-th item. In addition, for each item, he estimated the value of $d_{i}$ — the moment after which the item $i$ will be completely burned and will no lo... | If Polycarp will save two items, it is more profitable to first save the one whose $d$ parameter is less. So, you can sort items by the parameter $d$. Let $dp_{i, j}$ be the maximum total value of items Polycarp can save by checking first $i - 1$ items in $j$ seconds. Here are two types of transitions. Polycarp can eit... | [
"dp",
"sortings"
] | 2,000 | null |
864 | F | Cities Excursions | There are $n$ cities in Berland. Some pairs of them are connected with $m$ directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities $(x, y)$ there is at most one road from $x$ to $y$.
A path from city $s$ to city $t$ is a s... | There is a direct graph. For each query, you need to find the $k_{j}$-th vertex in the lexicographically minimal path from $s_{j}$ to $t_{j}$. First group the queries on the vertex $t_{j}$ and find all vertices from which the vertex $t_{j}$ is achievable. For this you can invert all the arcs and run dfs from the vertex... | [
"dfs and similar",
"graphs",
"trees"
] | 2,700 | null |
865 | A | Save the problem! | Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they... | The simplest solution is to make the denominations always ${1, 2}$, and set $N = 2 \cdot A - 1$. This provides exactly $A$ ways to make change, because you can choose any number of 2 cent pieces from $0$ to $A - 1$, then the rest must be 1 cent pieces. | [
"constructive algorithms"
] | 1,400 | null |
865 | B | Ordering Pizza | It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly $S$ slices.
It is known that the $i$-th contestant will eat $s_{i}$ slices of pizza, and... | To simplify things, let's first add a dummy contestant who will eat all the "leftover" pizza but gain no happiness. Then let's sort the contestants by $b_{i} - a_{i}$. Now we can describe the optimal way to feed the contestants once the pizzas are already bought: we should line up the contestants in order, and line up ... | [
"binary search",
"sortings",
"ternary search"
] | 1,900 | null |
865 | C | Gotta Go Fast | You're trying to set the record on your favorite video game. The game consists of $N$ levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the $i$-th level in either $F_{i}$ secon... | Let's change the game by adding a deterministic variant, which takes exactly $K$ seconds to complete. Initially, you play the original (random) game, but between levels (including before the first level), you're allowed to switch to the deterministic game (instead of restarting). You finish when you either complete the... | [
"binary search",
"dp"
] | 2,400 | null |
865 | D | Buy Low Sell High | You can perfectly predict the price of a certain stock for the next $N$ days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when y... | Let's introduce the idea of options to the problem. Instead of having to buy stock when it is at a given price, each day you gain the option to buy a share at that days price, which you can exercise at any time in the future. This way we only need to exercise an option in order to sell it, and we never need to "hold" a... | [
"constructive algorithms",
"data structures",
"greedy"
] | 2,400 | null |
865 | E | Hex Dyslexia | Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string... | First, observe that for a solution to exist, the sum of the digits in the input must be divisible by 15. This is because of the Casting out Nines rule, but applied in base 16. Furthermore, the sum of digits, when divided by 15, tells us how many carries must be performed when adding the answer to the input. We can try ... | [
"bitmasks",
"brute force",
"dp",
"graphs"
] | 3,300 | null |
865 | F | Egg Roulette | The game of Egg Roulette is played between two players. Initially $2R$ raw eggs and $2C$ cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg... | We can permute any prefix of an ordering containing at most $R - 1$ 'A's or $R - 1$ 'B's without changing the unfairness. This is because within that prefix one of the players cannot lose the game. This means that every ordering there is a unique ordering with the same unfairness that begins with exactly $R - 1$ 'A's f... | [
"bitmasks",
"brute force",
"divide and conquer",
"math",
"meet-in-the-middle"
] | 3,300 | null |
865 | G | Flowers and Chocolate | It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.
The flower shop has $F$ different types of flowers available. The $i$-th type of flower always has exactly $p_{i}$ petals. Pieguy has decided to buy a bouquet consisting of exactly $N$ flowers. He may buy t... | Let's first consider how to compute the number of ways to make a bouquet with exactly $K$ petals. Define a polynomial $P(x)=\sum_{i=1}^{F}x^{p}$. Then if we compute $P(x)^{N}$, the coefficient of $x^{K}$ gives the number of ways to make a bouquet with exactly $K$ petals. This is because each possible bouquet produces a... | [
"combinatorics",
"math",
"matrices"
] | 3,300 | null |
867 | A | Between the Offices | As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | The answer is "YES" if the first character of the given string is 'S' and the last character is 'F', otherwise it's "NO". | [
"implementation"
] | 800 | null |
868 | A | Bark to Unlock | As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p... | If the answer is 'yes', then the password is either one of the given strings, or can be formed by taking the last letter and the first letter of some of the given strings (these strings can be the same). This can be checked straightforwardly in $O(n^{2})$ time. | [
"brute force",
"implementation",
"strings"
] | 900 | null |
868 | B | Race Against Time | Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.
The entire universe turned into an enormous clock face with ... | There are $12 \times 60 \times 60$ positions on the clock face that can be occupied by hands and start/finish positions. After marking the positions occupied by hands, we can straightforwardly try both directions of moving and check if we arrive to the finish without encountering any of the hands. Of course, there ... | [
"implementation"
] | 1,400 | null |
868 | C | Qualification Rounds | Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of $n$ problems, and they want to select any non-empty subset of it as a problemset.
$k$ experienced teams are participating in the contest. Some of these teams already know some of the prob... | Let us show that if a solution exists, then there is always a solution that uses at most two problems. First, if there is a problem not known to any of the teams, that we can just take this only problem in the set. Next, suppose that there is a problem known only to one of the teams. If there is a problem this team doe... | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp"
] | 1,500 | null |
868 | D | Huge Strings | You are given $n$ strings $s_{1}, s_{2}, ..., s_{n}$ consisting of characters $0$ and $1$. $m$ operations are performed, on each of them you concatenate two existing strings into a new one. On the $i$-th operation the concatenation $s_{ai}s_{bi}$ is saved into a new string $s_{n + i}$ (the operations are numbered start... | The key insight is that despite the strings can get very long, the answer for each string at most 9. Indeed, let us keep track of the number of distinct substrings of length 10 across all strings. Obviously, this number is at most 100 for the initial strings. Once we obtain a new string as a concatenation of two old on... | [
"bitmasks",
"brute force",
"dp",
"implementation",
"strings"
] | 2,200 | null |
868 | E | Policeman and a Tree | You are given a tree (a connected non-oriented graph without cycles) with vertices numbered from $1$ to $n$, and the length of the $i$-th edge is $w_{i}$. In the vertex $s$ there is a policeman, in the vertices $x_{1}, x_{2}, ..., x_{m}$ ($x_{j} ≠ s$) $m$ criminals are located.
The policeman can walk along the edges w... | Suppose that the policeman is moving from $v$ to $u$ via the tree edge. The criminals can now assume any positions in two halves of the tree (but cannot travel from one half to another). Let $dp_{e, k, a}$ be the resulting time to catch the criminals if the policeman have just started to travel along a (directed) edge ... | [
"dp",
"graphs",
"trees"
] | 2,700 | null |
868 | F | Yet Another Minimization Problem | You are given an array of $n$ integers $a_{1}... a_{n}$. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into $k$ non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element... | First, let us solve the problem in $O(kn^{2})$ time with a simple DP. Let $dp_{i, j}$ be the smallest cost of a partition of first $j$ elements into $i$ parts. Clearly, $dp_{i, j} = min_{j' < j}dp_{i - 1, j'} + cost(j', j)$. We can optimize the cost computation by moving $j'$ from right to left and maintaining frequenc... | [
"divide and conquer",
"dp"
] | 2,500 | null |
868 | G | El Toll Caves | The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of $n$ possible spots in the caves. You assume that each of the spots has probability $1 / n$ to contain a treasure.
You cannot get into the caves yourself, so you have constructed a robot that can s... | Let $a_{i, j}$ be the number of times we have checked spot $j$ after $i$ days. Assuming that the spot $j$ contains the treasure, we can see that the expected number of days to find the treasure is $\textstyle\sum_{i=0}^{\infty}2^{-a_{i,j}}$. Hence the unconditional expectation of the answer is ${\frac{1}{n}}\sum_{i=0}^... | [
"math"
] | 3,300 | null |
869 | A | The Artful Expedient | Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer $n$ is decided first. Both Koyomi and Karen independently choose $n$ distinct positive integers, deno... | First approach: Optimize the straightforward solution. The $O(n^{3})$ solution is to iterate through $(i, j)$ pairs, then iterate over $k$ and check whether $x_{i}$ xor $y_{j}$ equals either $x_{k}$ or $y_{k}$. But it doesn't fit into the time limit. We try to get rid of the $k$ loop and make the check faster. Here's t... | [
"brute force",
"implementation"
] | 1,100 | #include <stdio.h>
int main()
{
puts("Karen");
return 0;
} |
869 | B | The Eternal Immortality | Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every $a!$ years. Here $a!$ deno... | Multiply instead of divide. What happens to the last digit when multiplying? $\frac{\partial!}{\alpha!}$ equals $(a + 1) \cdot (a + 2) \cdot ... \cdot (b - 1) \cdot b$. Consider the multiplicands one by one, and when the last digit of the product becomes $0$, it stays unchanged from then on. Hence we can multiply the i... | [
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
long long L,R;
int ans;
int main()
{
scanf("%lld%lld",&L,&R);
if (R-L>=10) printf("%d\n",0);
else
{
ans=1;
for (long long i=L+1;i<=R;i++)
ans=(1LL*ans*(i%10))%10;
printf("%d\n",ans);
}
return 0;
} |
869 | C | The Intriguing Obsession | — This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three... | First step: Consider what does at least 3 mean? 'The shortest distance between them is at least 3' means it can't be 1 or 2. The distance can't be 1 means that no two islands with the same colour can be straightly connected. The distance can't be 2 means that for each island, no two islands with the same colour can bot... | [
"combinatorics",
"dp",
"math"
] | 1,800 | #include <bits/stdc++.h>
#define Maxn 5007
#define modp 998244353
int p[Maxn][Maxn];
int pre[Maxn];
int a,b,c;
int solve(int x,int y)
{
int res=0;
for (int k=0;k<=x&&k<=y;k++)
{
int del=pre[k];
del=(1LL*del*p[x][k])%modp;
del=(1LL*del*p[y][k])%modp;
res=(res+del)%modp;
}
return res;
}
int main()
{
scanf("... |
869 | D | The Overdosing Ubiquity | The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.
The Cinderswarm Bee. Koyomi knows it.
The bees, according to their nature, live in a tree. To be more specific, a \underline{complete binary tree} with $n$ nodes numbered from $1$ to $n$. The node... | Iterate over all possible combination, order and direction of extra edges. There are no more than $O(m!2^{m})$ ways to go through these extra edges, each of which will bring us at most $O(n^{2})$ more simple paths. If we count all these simple paths using simple depth-first search, the time complexity will be $O(n^{2}m... | [
"brute force",
"dfs and similar",
"graphs"
] | 2,800 | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
const int MAXN=255;
const int Mod=1000000007;
inline void add_mod(int &x,int y)
{
x=(x+y<Mod ? x+y : x+y-Mod);
}
int u[MAXN],v[MAXN];
map<int,int> mp;
inline int get_id... |
869 | E | The Untended Antiquity | Adieu l'ami.
Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.
The space is represented by a rectangular grid of $n × m$ cells, arranged into $n$ rows and $m$ columns. The $c$-th cell in the $r$-th row is deno... | The barriers share no common points. Therefore two cells are connected iff the set of barriers containing each of them are the same. The reason is that no barrier can divide a barrier of larger area into two separate regions that are not reachable from each other. The inner barrier can't be any larger in either side (o... | [
"data structures",
"hashing"
] | 2,400 | #include <bits/stdc++.h>
#define Maxn 2507
using namespace std;
int n,m,q;
map<pair<pair<int,int>,pair<int,int> >,pair<unsigned long long,unsigned long long> > mp;
pair<unsigned long long,unsigned long long> s[Maxn][Maxn];
void add(int x,int y,pair<unsigned long long,unsigned long long> del)
{
for (int kx=x;kx<=2503;k... |
870 | A | Search for Pretty Integers | You are given two lists of non-zero digits.
Let's call an integer pretty if its (base $10$) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? | Note that the length of the answer does not exceed two because we can take one number from the first list and one number from the second lists and make up of them a pretty number. So we need to check two cases: 1) Iterate through the digits from the first list and check if digit belongs to the second list too. Make up ... | [
"brute force",
"implementation"
] | 900 | n, m = [int(i) for i in input().split()]
a = set(int(i) for i in input().split())
b = set(int(i) for i in input().split())
if a & b:
print(min(a & b))
else:
x = min(a)
y = min(b)
print(min(x, y), max(x, y), sep='') |
870 | B | Maximum of Maximums of Minimums | You are given an array $a_{1}, a_{2}, ..., a_{n}$ consisting of $n$ integers, and an integer $k$. You have to split the array into exactly $k$ non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the $k$ obtained minimums. What is the maximum possible inte... | To solve the problem, we need to consider three cases: $k \ge 3:$ then let $pos_max$ be the position of the element with the maximum value, then it is always possible to divide the array into subsegments so that one subsegment contains only this number, so the answer to the problem is $a_{pos_max}$. $k = 2:$ then all... | [
"greedy"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5;
int a[MAXN];
int n, k;
int suf_min[MAXN];
int main()
{
cin >> n >> k;
for (int i = 0; i < n; ++i)
cin >> a[i];
if (k == 1)
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans = min(ans, a[i]);
cout << ans << endl;
}
else
if... |
870 | C | Maximum splitting | You are given several queries. In the $i$-th query you are given a single positive integer $n_{i}$. You are to represent $n_{i}$ as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than $1$ is composite, if it is not ... | Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in splitting of big numbers. Let's write for small numbers ($1 \le M \le n$) $dp_{n}$ - number of composite summands in splitting of $n$. If our query $n$ is small number let's print $dp_{n}$. Else let's find mini... | [
"dp",
"greedy",
"math",
"number theory"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 16;
signed main() {
ios_base::sync_with_stdio(false); cin.tie(0);
vector<int> ans(maxn, -1);
ans[0] = 0;
for (int i = 1; i < maxn; ++i) {
for (auto j: vector<int>{4, 6, 9}) {
if (i >= j && ans[i - j] != -1) {
... |
870 | D | Something with XOR Queries | This is an interactive problem.
Jury has hidden a permutation $p$ of integers from $0$ to $n - 1$. You know only the length $n$. Remind that in permutation all integers are distinct.
Let $b$ be the inverse permutation for $p$, i.e. $p_{bi} = i$ for all $i$. The only thing you can do is to ask xor of elements $p_{i}$ ... | The statement: those and only those permutations whose answers to the queries $(0, i)$ and $(i, 0)$ for all $i$ coincide with the answers given to the program, are suitable for all possible queries. The proof: $p_{i}\oplus b_{j}=(p_{i}\oplus b_{0})\oplus(p_{0}\oplus b_{j})\oplus(p_{0}\oplus b_{0})$, which means that wi... | [
"brute force",
"interactive",
"probabilities"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)5e3;
const int MAX_QUESTIONS_CNT = 2 * MAXN;
const int E_QUESTIONS_LIMIT_EXCEEDED = 1;
const int E_SMART_TEST_NOT_EQUAL_STUPID_TEST = 2;
const int E_WA = 3;
int n;
int P[MAXN], B[MAXN], ANSWERS_CNT;
int questions[MAXN][MAXN];
int... |
870 | E | Points, Lines and Ready-made Titles | You are given $n$ distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.
You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo $10^{9... | Let's build graph on points. Add edge from point to left, right, top and bottom neighbours (if such neigbour exist). Note that we can solve problem independently for each connected component and then print product of answer for components. So we can consider only connected graphs without loss of generality. Let's defin... | [
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
struct point {
int x, y;
};
int binpow(int x, int p) {
if (p == 0) return 1;
if (p & 1) return binpow(x, p - 1) * x % mod;
return binpow(x * x % mod, p >> 1);
}
int n;
vector<point> pt;... |
870 | F | Paths | You are given a positive integer $n$. Let's build a graph on vertices $1, 2, ..., n$ in such a way that there is an edge between vertices $u$ and $v$ if and only if $\operatorname*{gcd}(u,v)\neq1$. Let $d(u, v)$ be the shortest distance between $u$ and $v$, or $0$ if there is no path between them. Compute the sum of va... | Integer $1 \le x \le n$ is bad is $x = 1$ or $x$ is prime and $x > n / 2$. Otherwise integer is good. $prime_{x}$ for $1 < x \le n$ is minimal prime divisor of $x$. Path between two vertices doesn't exist if at least one of them is bad. Distance equals to zero if this two vertices are the same. Distance equals to... | [
"data structures",
"number theory"
] | 2,700 | #include <iostream>
using namespace std;
using ll = long long;
const int maxn = 1e7 + 5;
int n;
int prime[maxn];
char bad[maxn];
int phi[maxn];
int number_of_prime_divisors[maxn];
int pref_smallest_prime[maxn];
int number_of_bad = 0;
void calc_arrays() {
for (int i = 1; i <= n; ++i) {
phi[i] = i;
... |
871 | E | Restore the Tree | Petya had a tree consisting of $n$ vertices numbered with integers from $1$ to $n$. Accidentally he lost his tree.
Petya remembers information about $k$ vertices: distances from each of them to each of the $n$ tree vertices.
Your task is to restore any tree that satisfies the information that Petya remembers or repor... | In the beginning, it should be noted that it is possible to find out numbers of vertices from which distances are given, the number of the $i$th specified vertex is $id_{i}$, such that $d_{i, idi} = 0$. If there is no such a vertex, or more than one, then there is no answer. Fix the $root$ equal to some vertex from whi... | [
"graphs",
"greedy",
"trees"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
void impossible() {
puts("-1");
exit(0);
}
int main() {
int n, k;
assert(scanf("%d %d", &n, &k) == 2);
assert(k > 0);
vector <int> dist[k];
vector <int> idx(n, 0);
for (int i = 0; i < k; ++i) {
dist[i] = vector <int> (n, 0);
for (int j = 0; j < n; ++j)
... |
873 | A | Chores | Luba has to do $n$ chores today. $i$-th chore takes $a_{i}$ units of time to complete. It is guaranteed that for every $i\in[2...n]$ the condition $a_{i} ≥ a_{i - 1}$ is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than $k$ any chores and do each of them in $x$... | Since $x<\operatorname*{min}_{i=1}a_{i}$, it is better to do exactly $k$ chores in time $x$. And since we need to minimize total time we need to spend, it's better to speed up the "longest" chores. So the answer is $k\cdot x+\sum_{i=1}^{n-k}a_{i}$. | [
"implementation"
] | 800 | null |
873 | B | Balanced Substring | You are given a string $s$ consisting only of characters 0 and 1. A substring $[l, r]$ of $s$ is a string $s_{l}s_{l + 1}s_{l + 2}... s_{r}$, and its length equals to $r - l + 1$. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length... | Let $cnt_{0}(i)$ be the number of zeroes and $cnt_{1}(i)$ - the number of ones on prefix of length $i$; also let $balance(i) = cnt_{0}(i) - cnt_{1}(i)$ ($i \ge 0$). The interesting property of $balance$ is that the substring $[x, y]$ is balanced iff $balance(y) = balance(x - 1)$. That leads to a solution: for each va... | [
"dp",
"implementation"
] | 1,500 | null |
873 | C | Strange Game On Matrix | Ivan is playing a strange game.
He has a matrix $a$ with $n$ rows and $m$ columns. Each element of the matrix is equal to either $0$ or $1$. Rows and columns are $1$-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
- Initially Iv... | Let's notice that this task can be solved independently for each column, total result will be the sum of results for columns. The ones you should remove will always be the top ones in column. It makes no profit to erase some one while there are still ones on top of it, score won't become higher. Go from the top of the ... | [
"greedy",
"two pointers"
] | 1,600 | null |
873 | D | Merge Sort | Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array $a$ with indices from $[l, r)$ can be implemented as follows:
- If the segment $[l, r)$ is already sorted in non-descending order (that is, for any $i$ such that $l ≤ i < r - 1$ $a[i] ≤ a[i + 1]$), then end the function ca... | First of all, if $k$ is even, then there is no solution, since the number of calls is always odd (one call in the beginning, and each call makes either $0$ or $2$ recursive calls). Then, if $k$ is odd, let's try to start with a sorted permutation and try to "unsort" it. Let's make a function $unsort(l, r)$ that will do... | [
"constructive algorithms",
"divide and conquer"
] | 1,800 | null |
873 | E | Awards For Contestants | Alexey recently held a programming contest for students from Berland. $n$ students participated in a contest, $i$-th of them solved $a_{i}$ problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degre... | Let's consider naive solution: make three loops to fix amounts of people to get dimplomas of each degree, take the best. Obviously, sorting the scores will regroup optimal blocks for each degree in such a way that they come in segments of initial array. We tried to make these solutions fail but underestimated the abili... | [
"brute force",
"data structures",
"dp"
] | 2,300 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.