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 ⌀ |
|---|---|---|---|---|---|---|---|
1238 | E | Keyboard Purchase | You have a password which you often type — a string $s$ of length $n$. Every character of this string is one of the first $m$ lowercase Latin letters.
Since you spend a lot of time typing it, you want to buy a new keyboard.
A keyboard is a permutation of the first $m$ Latin letters. For example, if $m = 3$, then ther... | Let's solve this problem by subset dynamic programming. Let's denote $cnt_{x, y}$ as the number of adjacent characters ($s_i$ and $s_{i+1}$) in $s$ such that $s_i = x, s_{i+1} = y$ or $s_i = y, s_{i+1} = x$. Let's $dp_{msk}$ be some intermediate result (further it will be explained what kind of intermediate result) if ... | [
"bitmasks",
"dp"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
void upd(int &a, int b){
a = min(a, b);
}
const int N = 20;
const int M = (1 << N) + 55;
const int INF = int(1e9) + 100;
int a, n;
string s;
int cnt[N][N];
int d[M][N];
int dp[M];
int cntBit[M];
int minBit[M];
int main() {
cin >> n >> a >> s;
int B = (1 << a) - 1... |
1238 | F | The Maximum Subtree | Assume that you have $k$ one-dimensional segments $s_1, s_2, \dots s_k$ (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of $k$ vertexes, and there is an edge between the $i$-th and the $j$-th vertexes ($i \neq j$) if and only if the... | At first let's understand which trees are good. For this, let's consider some vertex $v$ (we denote its segment as $[l_v, r_v]$) which is not a leaf. Also let's consider some adjacent vertex $u$ (we denote its segment as $[l_u, r_u]$) which also is not leaf. It is claimed that segment $[l_v, r_v]$ can't be inside segme... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int n;
vector <int> g[N];
int d[N];
int dp[N][2];
void dfs(int v, int p){
vector <int> d1;
dp[v][1] = d[v] - 1;
for(auto to : g[v]){
if(to == p) continue;
dfs(to, v);
dp[v][0] = max(dp[v][0], dp[to][0]);
if(g[to].size() > 1){
d... |
1238 | G | Adilbek and the Watering System | Adilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job.
The watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than $c$ lite... | Despite the fact that statement sounds like some dp or flow, the actual solution is pretty greedy. Let's iterate over all minutes Adilbek has to water at and maintain the cheapest $C$ liters he can obtain to this minute. Let this be some structure which stores data in form (price for 1 liter, total volume Adilbek can b... | [
"data structures",
"greedy",
"sortings"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef long long li;
typedef pair<int, int> pt;
const int N = 500 * 1000 + 13;
int n, m, c, c0;
pair<int, pt> a[N];
li solve() {
scanf("%d%d%d%d", &n, &m, &c, &... |
1239 | A | Ivan the Fool and the Probability Theory | Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$... | If there is no adjecent cells with same color coloring is chess coloring. Otherwise there is exist two adjecent cells with same color. Let's decide for which cells we already know their color. It turns out that color rows or columns alternates. It means that this problem equal to the same problem about strip. Answer fo... | [
"combinatorics",
"dp",
"math"
] | 1,700 | null |
1239 | B | The World Is Just a Programming Task (Hard Version) | This is a harder version of the problem. In this version, $n \le 300\,000$.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya... | Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. The answer for a bracket sequence is the same as the answer for any of its cyclic shifts. Then find $i$- index of the minimum balance and perform a cyclic shift of the string by i to the l... | [
"implementation"
] | 2,500 | null |
1239 | C | Queue in the Train | There are $n$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \le... | The problem can be solved easily with an abstraction of "events". Let's define an "event" as a tuple of variables $(time, type, index)$, where $index$ is the index of the passenger $(1 \leq index \leq n)$, $time$ is the time when the event will happen, $type$ is either $0$ (the passenger exits the queue) or $1$ (the pa... | [
"data structures",
"greedy",
"implementation"
] | 2,300 | null |
1239 | D | Catowice City | In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $n$ residents and $n$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $1$ to $n$, whe... | You are given bipartite graph and a perfect matching in it. You have to find independent set of size $n$ which doesn't coincide with either of two parts. Suppose such independent set exists, let's call it $S$. Also, let's call left part of graph as $L$ and right part of graph as $R$. Then define $A = S \cap L$, $B = L ... | [
"2-sat",
"dfs and similar",
"graph matchings",
"graphs"
] | 2,400 | null |
1239 | E | Turtle | Kolya has a turtle and a field of size $2 \times n$. The field rows are numbered from $1$ to $2$ from top to bottom, while the columns are numbered from $1$ to $n$ from left to right.
Suppose in each cell of the field there is a lettuce leaf. The energy value of lettuce leaf in row $i$ and column $j$ is equal to $a_{i... | Consider that we already fixed the set in the top line and fixed. If we perform a swap in this situation, the answer will clearly won't become worse (some paths are not changing, and some are decreasing). So we can assume that the first line is sorted, and similarly the second line is sorted too (but descending). Now l... | [
"dp",
"implementation"
] | 3,100 | null |
1239 | F | Swiper, no swiping! | \begin{quote}
I'm the Map, I'm the Map! I'm the MAP!!!
\hfill Map
\end{quote}
In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose $t$ graph's variants, which Dora might like. However ... | We will look only on set of vertex, that will stay after deleting. Let node-$x$ - node with degree $mod\ 3$ equal $x$. Let's consider some cases: Node-$0$ exists. It is the answer, except the case, when our graph consists of one node. Cycle on nodes-$2$ exists. So exists irreducible cycle on nodes-$2$. It is the answer... | [
"graphs",
"implementation"
] | 3,400 | null |
1240 | F | Football | There are $n$ football teams in the world.
The Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums.
Let $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a t... | Let's assume that $m \leq n \cdot k$. We can randomly assign colors to edges. If there is a vertex that does not satisfy the condition, then we can choose color $a$ which appears the smallest number of times and color $b$ which appears the biggest number of times. We will "recolor" edges that have one of these two colo... | [
"graphs"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 101;
const int MAX_M = 1001;
int n, m, k;
vector<pair<int, int> > v[MAX_N];
int w[MAX_N];
int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M];
set<pair<int, int> > s[MAX_N], s2;
int deg[MAX_N][MAX_M];
inline pair<int, int> get_s2(int i)... |
1242 | A | Tile Painting | Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of $n$ consecutive tiles, numbered from $1$ to $n$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two \textbf{diffe... | If $n = p^k$ for some prime $p$, then the answer is $p$ colors. Simply color all tiles with indices $i \pmod p$ in color $i$. Since any divisor $d$ of $n$ greater than $1$ is divisible by $p$, then any two tiles $i$ and $i+d$ will have the same color. Also, if the first $p$ tiles are colored in $c$ different colors, th... | [
"constructive algorithms",
"math",
"number theory"
] | 1,500 | null |
1242 | B | 0-1 MST | Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on $n$ vertices. It is a complete graph: each pair of vertices is con... | First examine the given graph where there are only edges of weight $0$: suppose that the number of connected components in this subgraph is $k$. Then the minimum spanning tree of the given graph is equal to $k-1$. Therefore, we need to find the number of such (zero weight) components in the given graph. The following i... | [
"dfs and similar",
"dsu",
"graphs",
"sortings"
] | 1,900 | null |
1242 | C | Sum Balance | Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. \textbf{All of the integers are distinct.}
Ujan is lazy, so he will do the following reor... | First, calculate the total average sum $s := (\sum_{i=1}^n a_i)/k$. If the answer is positive, the sum of integers in each box must be equal to $s$ after reordering. If $s$ is not integer, then the answer is immediately negative. Now, suppose that an integer $x := a_{i,p}$ is taken out of some box $i$. Then we know tha... | [
"bitmasks",
"dfs and similar",
"dp",
"graphs"
] | 2,400 | null |
1242 | D | Number Discovery | Ujan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers $n$ and $k$. He creates an infinite sequence $s$ by repeating the following steps.
- Find $k$ smallest distinct positive integers that are not in $s$. Let's call them $u_{1}, u_{2}, \ldots, u_{k}$ from the smallest t... | Let's make some definitions: $x$ is non-self number if $x$ is appended into $s$ by summation form. For example, if $k = 2$, then $3, 9, 13, 18, \ldots$ are non-self numbers. $x$ is self number if $x$ is not non-self number. Let $I_{i} = [(k^2+1) \cdot i + 1, (k^2+1) \cdot i + 2, \ldots, (k^2+1) \cdot (i+1)]$. In other ... | [
"math"
] | 3,400 | null |
1242 | E | Planar Perimeter | Ujan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together.
He is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an ex... | If there is just a single face, just output it. Suppose there are at least $2$ faces. Let's say that we "glue" a cycle to a planar graph along $k$ edges if we place this cycle so that the graph and the cycle share $k$ edges on their perimeters. First, sort the numbers in decreasing order (then we have $a_1 \geq a_2 \ge... | [
"constructive algorithms",
"graphs"
] | 3,200 | null |
1243 | A | Maximum Square | Ujan decided to make a new wooden roof for the house. He has $n$ rectangular planks numbered from $1$ to $n$. The $i$-th plank has size $a_i \times 1$ (that is, the width is $1$ and the height is $a_i$).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some ... | There are different solutions: Solution 1: Bruteforce the length of the square $l$ from $1$ to $n$. If you can make a square of side length $l$, then there should be at least $l$ planks of length at least $l$. The complexity of such solution: $O(n^2)$. The parameter $l$ can be also checked using binary search: then the... | [
"implementation"
] | 800 | null |
1243 | B1 | Character Swap (Easy Version) | {This problem is different from the hard version. In this version Ujan makes \textbf{exactly} one exchange. You can hack this problem only if you solve both problems.}
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two \... | First, suppose that we make the strings equal by picking some $i$, $j$. Then for all $p \neq i, j$, we must have $s_p = t_p$, since these letters don't change. Suppose that $i = j$. Since the strings are distinct, we then must have $s_i \neq t_i$. But then the strings are not equal also after the swap; hence, we always... | [
"strings"
] | 1,000 | null |
1243 | B2 | Character Swap (Hard Version) | This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \le 1000, n \le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and faili... | We claim that you can make the strings equal if and only if the total number of each character in both of the strings $s$ and $t$ is even. Proof that this is a necessary condition. If we can make the strings equal, then for each position, the characters of $s$ and $t$ will be the same. Therefore, each character must ap... | [
"strings"
] | 1,600 | null |
1244 | A | Pens and Pencils | Tomorrow is a difficult day for Polycarp: he has to attend $a$ lectures and $b$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures a... | There is a solution with brute force in $O(n^2)$ and a solution with formulas in $O(1)$. I'll describe the latter one. We should determine the minimum number of pens that we should take to be able to write all of the lectures. It is $\lceil \frac{a}{c} \rceil$, but how to compute it easily? We can use some internal cei... | [
"math"
] | 800 | null |
1244 | B | Rooms and Staircases | Nikolay lives in a two-storied house. There are $n$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $1$ and $n$).
If Nikolay is currently in some room,... | If there are no stairs, the best we can do is to visit all the rooms on the same floor, so the answer is $n$. Otherwise, the best course of action is to choose exactly one stair (let's denote its number by $s$) and do one of the following: either start from the leftmost room on the first floor, then use the stair and m... | [
"brute force",
"implementation"
] | 1,000 | null |
1244 | C | The Football Season | The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets $w$ points, and the opposing team gets $0$ points. If the game results... | The crucial observation is that $d$ wins give us the same amount of points as $w$ draws. Let's use them to solve a problem where we want to minimize the total amount of wins and draws giving $p$ points (if it is not greater than $n$, we can just lose all other matches). If $y \ge w$, then we can subtract $w$ from $y$ a... | [
"brute force",
"math",
"number theory"
] | 2,000 | null |
1244 | D | Paint the Tree | You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph.
\begin{center}
{\small Example of a tree.}
\end{center}
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that an... | The key observation is that if we fix the colors of two adjacent vertices $x$ and $y$, then the color of any vertex adjacent to $x$ or to $y$ can be only $6 - c_x - c_y$. So we can fix the colors of the endpoints of any edge (there are $6$ possibilities to do that), then do a traversal to color all other vertices, then... | [
"brute force",
"constructive algorithms",
"dp",
"graphs",
"implementation",
"trees"
] | 1,800 | null |
1244 | E | Minimizing Difference | You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers.
You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.
Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can ... | Suppose that the maximum value in the resulting array should be $R$, and the minimum value should be $L$. Let's estimate the required number of operations to make an array with such properties. All elements that are less than $L$ should be increased to $L$, and all elements that are greater than $R$ should be decreased... | [
"binary search",
"constructive algorithms",
"greedy",
"sortings",
"ternary search",
"two pointers"
] | 2,000 | null |
1244 | F | Chips | There are $n$ chips arranged in a circle, numbered from $1$ to $n$.
Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If th... | The main observation for this problem is the following: a chip changes its color if and only if both of its neighbours have the opposite colors (so, a W chip changes its color only if both of its neighbours are B, and vice versa). Let's denote such chips as unstable, and also let's denote an unstable segment as a maxim... | [
"constructive algorithms",
"implementation"
] | 2,300 | null |
1244 | G | Running in Pairs | Demonstrative competitions will be held in the run-up to the $20NN$ Berlatov Olympic Games. Today is the day for the running competition!
Berlatov team consists of $2n$ runners which are placed on two running tracks; $n$ runners are placed on each track. The runners are numbered from $1$ to $n$ on each track. The runn... | First of all, let's understand which values of $sum$ we can obtain at all. Obviously, the minimum possible value of $sum$ is $mn = \frac{n(n+1)}{2}$. The maximum possible value of $sum$ is $mx = (\lceil\frac{n}{2}\rceil + 1 + n) \cdot \lfloor\frac{n}{2}\rfloor + n \% 2 \cdot \lceil\frac{n}{2}\rceil$. We can obtain ever... | [
"constructive algorithms",
"greedy",
"math"
] | 2,400 | null |
1245 | A | Good ol' Numbers Coloring | Consider the set of all nonnegative integers: ${0, 1, 2, \dots}$. Given two integers $a$ and $b$ ($1 \le a, b \le 10^4$). We paint all the numbers in increasing number first we paint $0$, then we paint $1$, then $2$ and so on.
Each number is painted white or black. We paint a number $i$ according to the following rule... | If $\gcd(a, b) \neq 1$, print "Infinite". This is correct because any integer that isn't divisible by $\gcd(a, b)$ will not be expressible in the form $ax + by$ since $ax + by$ is always divisible by $\gcd(a, b)$. Otherwise, print "Finite". To show that this is correct, we will prove that any integer greater than $ab$ ... | [
"math",
"number theory"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
while (b)
{
a %= b;
swap(a, b);
}
return a;
}
int main()
{
int t;
for (cin >> t; t--;)
{
int a, b;
cin >> a >> b;
if (gcd(a, b) == 1)
cout << "Finite... |
1245 | B | Restricted RPS | Let $n$ be a positive integer. Let $a, b, c$ be nonnegative integers such that $a + b + c = n$.
Alice and Bob are gonna play rock-paper-scissors $n$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $a$ times, paper $b$ times, and scissors $c$ times.
Alice wins if she beats... | Let $A$, $B$, $C$ be the number of rocks, papers, and scissors in Bob's sequence, respectively. It is easy to see that Alice can win at most $w := \min(A, b) + \min(B, c) + \min(C, a)$ hands. So if $2w < n$, Alice can't win. Otherwise, Alice can always win. One way to construct a winning sequence of hands for Alice is ... | [
"constructive algorithms",
"dp",
"greedy"
] | 1,200 | #include <vector>
#include <string>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int q;
for (cin >> q; q--;)
{
int ... |
1245 | C | Constanze's Machine | Constanze is the smartest girl in her village but she has bad eyesight.
One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto... | If $s$ has any 'm' or 'w', the answer is 0. Otherwise, we can do dp. Define $dp_i$ to be the number of strings that Constanze's machine would've turned into the first $i$ characters of $s$. Then, $dp_0 = dp_1 = 1$. For $i > 1$, transition is $dp_i = dp_{i - 1} + dp_{i - 2}$ if both $s_i = s_{i - 1}$ and $s_i$ is either... | [
"dp"
] | 1,400 | // In the name of Allah.
// We're nothing and you're everything.
// Ya Ali!
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 14, mod = 1e9 + 7;
int n, fib[maxn];
int main(){
ios::sync_with_stdio(0), cin.tie(0);
fib[0] = fib[1] = 1;
for(int i = 2; i < maxn; i++... |
1245 | D | Shichikuji and Power Grid | Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:
There are $n$ new cities located in Prefecture X. Cities are numbered from $1$ to $n$. City $i$ is located $x_i$ km North of the shrine and $y_i$ km East of the shrine. It is possible that $(x_i, y_i) = (x_j, y_j)$ even ... | Claim. Let $i$ be such that $c_i$ is minimum, then there is an optimal configuration with a power station in City $i$. Proof. Consider an optimal configuration. Let's say that City $u$ and City $v$ are in the same component if they are connected or City $v$ is connected to a City $w$ such that City $w$ is in the same c... | [
"dsu",
"graphs",
"greedy",
"shortest paths",
"trees"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
int main(){
int n;
scanf("%d", &n);
vector<int> x(n), y(n);
forn(i, n)
scanf("%d%d", &x[i], &y[i]);
vector<int> c(n), k(n);
forn(i, n)
scanf("%d", &c[i]);
forn(i, n)
s... |
1245 | E | Hyakugoku and Ladders | Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snake... | To make implementation easier, flatten the board into an array $a$ such that the $i$-th tile on the path is $a_i$. Define a function $f$ as follows: $f(i) = i$ if $a_i$ has no ladder, otherwise $f(i) = j$ where $j$ is such that the ladder from $a_i$ leads to $a_j$. Then, do dp. Define $dp_i$ to be the minimum expected ... | [
"dp",
"probabilities",
"shortest paths"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int grid[10][10];
for (int i = 0; i != 10; ++i)
for (int j = 0; j != 10; ++j)
cin >> grid[i][j];
int flat[10][10];
for (int i = 0; i != 10; ++i)
for (int j ... |
1245 | F | Daniel and Spring Cleaning | While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his ... | Claim. Let $x$, $y$ be nonnegative integers. If $x + y = x \oplus y$, then $x * y = 0$, where $x * y$ is the bitwise AND of $x$ and $y$. Proof. Recall that bitwise XOR is just addition in base two without carry. So if addition is to be equal to addition in base two without carry, then there must be no carry when added ... | [
"bitmasks",
"brute force",
"combinatorics",
"dp"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
int f(int a, int b)
{
int ret = 0;
int zeroes = 0;
for (int i = 1; i <= b; i <<= 1)
{
if (b & i)
{
b ^= i;
if (!(a & b))
ret += 1 << zeroes;
}
if (!(a & i))
... |
1246 | F | Cursor Distance | There is a string $s$ of lowercase English letters. A cursor is positioned on one of the characters. The cursor can be moved with the following operation: choose a letter $c$ and a direction (left or right). The cursor is then moved to the closest occurence of $c$ in the chosen direction. If there is no letter $c$ in t... | Again, it's easier to solve the problem backwards. For a character $s_i$, from which characters $s_j$ can we reach $s_i$ in one step? Clearly, $s_j$ should lie in a subsegment of $s$ bounded by adjacent occurences of $s_i$ (inclusive), or by the borders of $s$. Let's denote this subsegment for $s_i$ by $[L_i, R_i)$ (we... | [] | 3,500 | null |
1248 | A | Integer Points | DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $n$ distinct lines, given by equations $y = x + p_i$ for some distinct $p_1, p_2, \ldots, p_n$.
Then JLS drew on the same paper sheet $m$ distinct lines given by equations $y = -x + q_i$ for some distinct $q_... | Consider two lines $y = x + p$ and $y = -x + q$: $\begin{cases} y = x + p \\ y = -x + q \end{cases} \Rightarrow \begin{cases} 2y = p + q \\ y = -x + q \end{cases} \Rightarrow \begin{cases} y = \frac{p + q}{2} \\ y = -x + q \end{cases} \Rightarrow \begin{cases} y = \frac{p + q}{2} \\ x = \frac{q - p}{2} \end{cases}$ It'... | [
"geometry",
"math"
] | 1,000 | null |
1248 | B | Grow The Tree | Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting o... | At first, let's do some maths. Consider having an expression $a^2 + b^2$ which we have to maximize, while $a + b = C$, where $C$ is some constant. Let's proof that the maximum is achieved when $a$ or $b$ is maximum possible. At first let $a$ or $b$ be about the same, while $a \geq b$. Let's see what happens when we add... | [
"greedy",
"math",
"sortings"
] | 900 | null |
1248 | D1 | The World Is Just a Programming Task (Easy Version) | This is an easier version of the problem. In this version, $n \le 500$.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya bel... | Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. Note that the answer to the question about the number of cyclic shifts, which are correct bracket sequences, equals the number of minimal prefix balances. For example, for string )(()))()(... | [
"brute force",
"dp",
"greedy",
"implementation"
] | 2,000 | null |
1249 | A | Yet Another Dividing into Teams | You are a coach of a group consisting of $n$ students. The $i$-th student has programming skill $a_i$. \textbf{All students have distinct programming skills}. You want to divide them into teams in such a way that:
- No two students $i$ and $j$ such that $|a_i - a_j| = 1$ belong to the same team (i.e. skills of each pa... | The answer is always $1$ or $2$. Why it is so? Because if there is no such pair $i, j$ among all students that $|a_i - a_j| = 1$ then we can take all students into one team. Otherwise, we can divide them into two teams by their programming skill parity. | [
"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 q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
vector<int> a(n);
for (int j = 0; j < n; ++j) {
cin >> a[j];
}
bool ok = true;
... |
1249 | B1 | Books Exchange (easy version) | \textbf{The only difference between easy and hard versions is constraints}.
There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are... | In this problem you just need to implement what is written in the problem statement. For the kid $i$ the following pseudocode will calculate the answer (indices of the array $p$ and its values are $0$-indexed): | [
"dsu",
"math"
] | 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 q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
vector<int> p(n);
for (int j = 0; j < n; ++j) {
cin >> p[j];
--p[j];
}
for (i... |
1249 | B2 | Books Exchange (hard version) | \textbf{The only difference between easy and hard versions is constraints}.
There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are... | In this problem, we can notice that when we calculate the answer for the kid $i$, we also calculate the answer for kids $p_i$, $p_{p_i}$ and so on. So we can a little bit modify the pseudocode from the easy version to calculate answers faster: And of course, we don't need to run this while for all elements for which we... | [
"dfs and similar",
"dsu",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
vector<int> p(n);
for (int j = 0; j < n; ++j) {
cin >> p[j];
--p[j];
}
vector... |
1249 | C1 | Good Numbers (easy version) | \textbf{The only difference between easy and hard versions is the maximum value of $n$}.
You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.
The positive integer is called good if it can be represented as a sum of \textbf... | As you can see from the example, the maximum answer doesn't exceed $2 \cdot 10^4$. So we can run some precalculation before all queries, which will find all good numbers less than $2 \cdot 10^4$. The number is good if it has no $2$ in the ternary numeral system. When you read the next query, you can increase $n$ until ... | [
"brute force",
"greedy",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
while (true) {
bool ok = true;
int cur = n;
while (cur > 0) {
if (ok && cur ... |
1249 | C2 | Good Numbers (hard version) | \textbf{The only difference between easy and hard versions is the maximum value of $n$}.
You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.
The positive integer is called good if it can be represented as a sum of \textbf... | Let's see the representation of $n$ in the ternary numeral system. If it has no twos, then the answer is $n$. Otherwise, let $pos_2$ be the maximum position of $2$ in the ternary representation. Then we obviously need to replace it with $0$ and add some power of three to the right from it. Let $pos_0$ be the leftmost p... | [
"binary search",
"greedy",
"math",
"meet-in-the-middle"
] | 1,500 | #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 q;
cin >> q;
for (int i = 0; i < q; ++i) {
long long n;
cin >> n;
vector<int> vals;
int pos2 = -1;
while (n > 0) {... |
1249 | D1 | Too Many Segments (easy version) | \textbf{The only difference between easy and hard versions is constraints}.
You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$.
Th... | In this problem, the following greedy solution works: let's find the leftmost point covered by more than $k$ segments. We should fix it somehow. How to do it? Let's find some segment that was not removed already, it covers this point and its rightmost end is maximum possible, and remove this segment. You can implement ... | [
"greedy"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 250;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<pair<int, int>> segs(n);
vector<int> cnt(N);
for (int i = 0; i < n; ++i) {
cin >> segs[i].first >> segs... |
1249 | D2 | Too Many Segments (hard version) | \textbf{The only difference between easy and hard versions is constraints}.
You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$.
Th... | In this problem, we need to implement the same greedy solution as in the easy version, but faster. Firstly, let's calculate for each point the number of segments covering it. We can do it using standard trick with prefix sums: increase $cnt_{l_i}$, decrease $cnt_{r_i + 1}$ and build prefix sums on the array $cnt$. Let'... | [
"data structures",
"greedy",
"sortings"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 200200;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<pair<int, int>> segs(n);
vector<int> cnt(N);
vector<vector<int>> ev(N);
for (int i = 0; i < n; ++i) {... |
1249 | E | By Elevator or Stairs? | You are planning to buy an apartment in a $n$-floor building. The floors are numbered from $1$ to $n$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.
Let:
- $a_i$ for all $i$ from $1$ to $n-1$ be the time required to go from th... | This is easy dynamic programming problem. It is easy to understand that we don't need to go down at all (otherwise your solution will be Dijkstra's algorithm, not dynamic programming). Let $dp_{i, 0}$ be the minimum required time to reach the floor $i$ if we not in the elevator right now and $dp_{i, 1}$ be the minimum ... | [
"dp",
"shortest paths"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, c;
cin >> n >> c;
vector<int> a(n - 1), b(n - 1);
for (int i = 0; i < n - 1; ++i) {
cin >> a[i];
}
for (int i = 0; i < n - 1;... |
1249 | F | Maximum Weight Subset | You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles.
\begin{center}
{\small Example of a tree.}
\end{center}
Vertices are numbered from $1$ to $n$. All vertices have weights, the weight of the vertex $v$ is $a_v$.
Recall that the distance between tw... | Let's solve this problem using dynamic programming on a tree. Suppose the tree is rooted and the root of the tree is $1$. Also, let's increase $k$ to find the subset in which any pair of vertices had distance $k$ or greater instead of $k+1$ or greater. Let $dp_{v, dep}$ be the maximum total weight of the subset in the ... | [
"dp",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 200 + 13;
const int INF = 1e9;
int n, k;
int a[N];
vector<int> g[N];
int dp[N][N];
int d[N];
int tmp[N];
void dfs(int v, int p = -1){
d[v] = 1;
dp[v][0] = a[v];
for (auto u : g[v]) if (u != p){
dfs(... |
1251 | A | Broken Keyboard | Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $26$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.
To check which buttons need replacement, Polycarp pressed so... | If a key malfunctions, each sequence of presses of this key gives a string with even number of characters. So, if there is a substring consisting of odd number of equal characters $c$, such that it cannot be extended to the left or to the right without adding other characters, then it could not be produced by presses o... | [
"brute force",
"strings",
"two pointers"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
bool ans[26];
void solve() {
string s;
cin >> s;
memset(ans, 0, sizeof(ans));
for (int i = 0; i < s.size(); i++) {
int j = i;
while (j + 1 < s.size() && s[j + 1] == s[i])
j++;
if ((j - i) % 2 == 0)
ans[s[i] - 'a'] = true;
i = j;
}
for (int i = 0... |
1251 | B | Binary Palindromes | A palindrome is a string $t$ which reads the same backward as forward (formally, $t[i] = t[|t| + 1 - i]$ for all $i \in [1, |t|]$). Here $|t|$ denotes the length of a string $t$. For example, the strings 010, 1001 and 0 are palindromes.
You have $n$ binary strings $s_1, s_2, \dots, s_n$ (each $s_i$ consists of zeroes ... | Let's make several observations. At first, note that the lengths of the strings doesn't change. At second, note that if the string has even length then being palindromic is the same as having even number of zeroes and even number of ones. But if the string has odd length, then it always is palindromic. So the question ... | [
"greedy",
"strings"
] | 1,400 | fun main() {
val q = readLine()!!.toInt()
for (ct in 1..q) {
val n = readLine()!!.toInt()
var (odd, evenGood, evenBad) = listOf(0, 0, 0)
for (i in 1..n) {
val s = readLine()!!
when {
s.length % 2 == 1 -> odd++
s.count { it == '0' } ... |
1251 | C | Minimize The Integer | You are given a huge integer $a$ consisting of $n$ digits ($n$ is between $1$ and $3 \cdot 10^5$, inclusive). It may contain leading zeros.
You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $2$).
For exam... | Let's consider two sequences of digits: $e_1, e_2, \dots , e_k$ and $o_1, o_2, \dots , o_m$, there $e_1$ is the first even digit in $a$, $e_2$ is the second even digit and so on and $o_1$ is the first odd digit in $a$, $o_2$ is the second odd digit and so on. Since you can't swap digits of same parity, the sequence $e$... | [
"greedy",
"two pointers"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int t;
string a;
int main() {
cin >> t;
for(int tc = 0; tc < t; ++tc){
cin >> a;
string s[2];
for(auto x : a)
s[int(x - '0') & 1] += x;
reverse(s[0].begin(), s[0].end());
reverse(s[1].begin(), s[1].end());
string res = "";
while(!(s[0].empty() && ... |
1251 | D | Salary Changing | You are the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$).
You have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such... | Let $f(mid)$ be equal minimum amount of money to obtain the median salary at least $mid$. We'll solve this problem by binary search by $mid$. Suppose the have to calculate the minimum amount of money for obtaining median salary at least $mid$. Let's divide all salaries into three groups: $r_i < mid$; $mid \le l_i$; $l_... | [
"binary search",
"greedy",
"sortings"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 99;
const int INF = int(1e9) + 100;
int t;
int n;
long long s;
pair<int, int> p[N];
bool ok(int mid){
long long sum = 0;
int cnt = 0;
vector <int> v;
for(int i = 0; i < n; ++i){
if(p[i].second < mid)
sum += p[i].first;
else if(p[i].fi... |
1251 | E2 | Voting (Hard Version) | \textbf{The only difference between easy and hard versions is constraints.}
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay h... | Denote the number of voters with $m_i = x$ as $c_x$. Also denote $pref_x = \sum\limits_{i=0}^{x-1} c_x$, i.e. $pref_x$ is equal to number of voters with $m_i < x$. Let's group all voters by value $m_i$. We'll consider all these group in decreasing value of $m_i$. Assume that now we consider group with $m_i = x$. Then t... | [
"binary search",
"data structures",
"greedy"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int t, n;
vector <int> v[N];
int main() {
int t;
scanf("%d", &t);
for(int tc = 0; tc < t; ++tc){
scanf("%d", &n);
for(int i = 0; i < n; ++i)
v[i].clear();
for(int i = 0; i < n; ++i){
int x, s;
scanf("%d %d", &x, &s);
v[... |
1251 | F | Red-White Fence | Polycarp wants to build a fence near his house. He has $n$ white boards and $k$ red boards he can use to build it. Each board is characterised by its length, which is an integer.
A good fence should consist of \textbf{exactly one} red board and several (possibly zero) white boards. The red board should be the longest ... | Let's analyze how the perimeter of the fence can be calculated, if we know its array of lengths. Suppose there are $m$ boards in the fence. The perimeter of the fence can be composed of the three following values: the lower border of the fence (with length $m$); $m$ horizontal segments in the upper border of the fence ... | [
"combinatorics",
"fft"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
const int LOGN = 20;
const int N = (1 << LOGN);
const int MOD = 998244353;
const int g = 3;
#define forn(i, n) for(int i = 0; i < int(n); i++)
inline int mul(int a, int b)
{
return (a * 1ll * b) % MOD;
}
inline int norm(int a)
{
while(a >= MOD)
a -= MOD;
while(a <... |
1253 | A | Single Push | You're given two arrays $a[1 \dots n]$ and $b[1 \dots n]$, both of the same length $n$.
In order to perform a push operation, you have to choose three integers $l, r, k$ satisfying $1 \le l \le r \le n$ and $k > 0$. Then, you will add $k$ to elements $a_l, a_{l+1}, \ldots, a_r$.
For example, if $a = [3, 7, 1, 4, 1, 2... | If we set $d_i = b_i - a_i$, we have to check that $d$ has the following form: $[0, 0, \ldots, 0, k, k, \ldots, k, 0, 0, \ldots, 0]$. Firstly check that there is no negative element in $d$. Solution 1 : add $0$ to the beginning and the end of the array $d$, then check that there is at most two indices $i$ such that $d_... | [
"implementation"
] | 1,000 | "#include <iostream>\n#include <vector>\nusing namespace std;\n\nbool solve()\n{\n\tint nbElem;\n\tcin >> nbElem;\n\n\tint extSize = nbElem+2;\n\tvector<int> orig(extSize), target(extSize);\n\tvector<int> diff(extSize, 0);\n\n\tfor (int iElem = 1; iElem <= nbElem; ++iElem) {\n\t\tcin >> orig[iElem];\n\t}\n\n\tfor (int ... |
1253 | B | Silly Mistake | The Central Company has an office with a sophisticated security system. There are $10^6$ employees, numbered from $1$ to $10^6$.
The security system logs entrances and departures. The entrance of the $i$-th employee is denoted by the integer $i$, while the departure of the $i$-th employee is denoted by the integer $-i... | We can solve this problem with a straightforward greedy solution: simulate the events in the order in which they occured, and as soon as the office is empty, end the current day and begin a new one. We can prove that if there exists a valid solution, this greedy algorithm will find one (and furthermore, it will use max... | [
"greedy",
"implementation"
] | 1,400 | "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int borne = (int)(1e6) + 5;\nconst int WAIT=0, ENTERED=1, LEFT=2;\nint state[borne];\n\nbool solve()\n{\n\tios::sync_with_stdio(false);\n\tint nbEvents;\n\tcin >> nbEvents;\n\tvector<int> res, cur;\n\tint ofs = 0;\n\n\tfor (int ind = 0; ind < nbEvents; ++ind) {\n... |
1253 | C | Sweets Eating | Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$.
Yui loves sweets, but she can eat at most $m$ sweets each day for health reasons.
Days are $1$-indexed (numbered $1, 2, 3, \ldots$). Eating t... | Let's sort array $a$. Now we can easily that if Yui wants to eat $k$ sweets, she has to eat sweets $k, k-1, \ldots, 1$ in this order, because of rearrangement inequality (put lower coefficients (day) on higher values (sugar concentration)). A naive simulation of this strategy would have complexity $O(n^2)$, which is to... | [
"dp",
"greedy",
"math",
"sortings"
] | 1,500 | "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbSweets, maxPerDay;\n\tcin >> nbSweets >> maxPerDay;\n\n\tvector<int> val(nbSweets);\n\n\tfor (int iSweet = 0; iSweet < nbSweets; ++iSweet) {\n\t\tcin >> val[iSwe... |
1253 | D | Harmonious Graph | You're given an undirected graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$.
The graph is considered harmonious if and only if the following property holds:
- For every triple of integers $(l, m, r)$ such that $1 \le l < m < r \le n$, if there exists a \textbf{path} going from node $l$ to node $... | For each connected component, let's find the weakest node $l$ and the biggest node $r$ in it (with one DFS per connected component). If we look for all components at their intervals $[l\ ;\ r]$, we can see that two components should be connected in the resulting graph if and only if their intervals intersect. This lead... | [
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"sortings"
] | 1,700 | "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nconst int borne = 201*1000;\nint nbNodes, nbEdges;\n\nvector<int> adj[borne];\nbool vu[borne];\nvector<pair<int, int>> ivComp;\n\nvoid dfs(int nod, int& weaker, int& bigger)\n{\n\tvu[nod] = true;\n\tweaker = min(weaker, nod);\n\tbigg... |
1253 | E | Antenna Coverage | The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $(Ox)$ axis.
On this street, there are $n$ antennas, numbered from $1$ to $n$. The $i$-th antenna lies on the position $x_i$ and has an initial scope of $s_i$: it covers all integer positions inside the interval $[x_i -... | We can add an antenna $(x=0, s=0)$. It will not modifiy the answer, because it would be non-optimal to increase the scope of this antenna. Let $dp_x$ be the minimum cost to cover all positions from $x$ to $m$ inclusive, knowing that position $x$ is covered. We compute $dp$ in decreasing order of $x$. Base case is $dp_m... | [
"data structures",
"dp",
"greedy",
"sortings"
] | 2,200 | "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Antenna\n{\n\tint iniLeft, iniRight;\n};\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbAntennas, totLen;\n\tcin >> nbAntennas >> totLen;\n\tvector<Antenna> ants(nbAntennas);\n\n\tfor (int iAnt = 0;... |
1253 | F | Cheap Robot | You're given a simple, undirected, connected, weighted graph with $n$ nodes and $m$ edges.
Nodes are numbered from $1$ to $n$. There are exactly $k$ centrals (recharge points), which are nodes $1, 2, \ldots, k$.
We consider a robot moving into this graph, with a battery of capacity $c$, not fixed by the constructor y... | Key insight 1: Since we always end on a central, at any time our robot have to be able to reach the nearest central. Key insight 2: Since we always start from a central, from any node $u$, going to the nearest central, then going back to $u$ can't decrease the number of energy points in the battery. - Firstly, let's do... | [
"binary search",
"dsu",
"graphs",
"shortest paths",
"trees"
] | 2,500 | "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nusing llg = long long;\n\nconst int maxNod = (int)(1e5) + 5;\nconst int maxEdges = 3*(int)(1e5) + 5;\nconst int maxQueries = 3*(int)(1e5) + 5;\n\nconst int maxTokens = 2*maxQueries;\n\nconst llg BIG = (llg)(1e9) * (... |
1254 | A | Feeding Chicken | Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.
His farm is presented by a rectangle grid with $r$ rows and $c$ columns. Some of these cells contain rice, others are empty. $k$ chickens are living on his farm. \textbf{The num... | First, we will try to solve the problem when our rectangle is an array (or an $1 \cdot n$ rectangle). Let $r$ be the number of rice cells. It's not hard to see that the difference between the maximum and the minimum number of cells with rice assigned to a chicken is either $0$, when $r$ $mod$ $k = 0$, or $1$ otherwise.... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,700 | #include<bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a), _b = (b); i <= _b; i++)
#define FORD(i, b, a) for (int i = (b), _a = (a); i >= _a; i--)
#define REP(i, n) for (int i = 0, _n = (n); i < _n; i++)
#define FORE(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); i++)
#define ALL(v) (v).begin(), ... |
1254 | B1 | Send Boxes to Alice (Easy Version) | This is the easier version of the problem. In this version, $1 \le n \le 10^5$ and $0 \le a_i \le 1$. You can hack this problem only if you solve and lock both problems.
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepa... | Author: MofK. Prepared by UncleGrandpa The problem asked you to move chocolate pieces between adjacent boxes so that the number of chocolate pieces in all boxes is divisible by $k$ ($k>1$). Now, it's clear that we will divide the array into segments, such that the sum of each segment is divisible by $k$, and move all c... | [
"constructive algorithms",
"greedy",
"math",
"number theory",
"ternary search",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000006;
int n;
int a[maxn];
vector <int> v;
long long cost(int p) {
long long ret = 0;
for (int i = 0; i < v.size(); i += p) {
int median = v[(i + i + p - 1) / 2];
for (int j = i; j < i + p; ++j)
ret += abs(v[j] - med... |
1254 | B2 | Send Boxes to Alice (Hard Version) | This is the harder version of the problem. In this version, $1 \le n \le 10^6$ and $0 \leq a_i \leq 10^6$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-ti... | Author: MofK. Prepared by MofK and UncleGrandpa The problem E2 is different from the problem E1 in some ways. Now all $A_i$ is at most $10^6$, and so is the number $n$. That makes our solution on E1 simply not usable in this problem. Let $S_i$ be the sum of $a_1 + a_2 + ... + a_i$. Now we see that: if we move a chocola... | [
"constructive algorithms",
"greedy",
"math",
"number theory",
"ternary search",
"two pointers"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000006;
int n;
long long a[maxn];
long long s[maxn];
long long cost(long long mod) {
long long ret = 0;
for (int i = 1; i <= n; ++i)
ret += min(s[i] % mod, mod - s[i] % mod);
return ret;
}
int main(void) {
ios_base::sync_with_st... |
1254 | C | Point Ordering | \textbf{This is an interactive problem.}
Khanh has $n$ points on the Cartesian plane, denoted by $a_1, a_2, \ldots, a_n$. All points' coordinates are integers between $-10^9$ and $10^9$, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a... | Let's start by choosing vertices $1$ and $2$ as pivots. Recall that if the cross product of two vectors $\vec{A}$ and $\vec{B}$ is positive, point $B$ lies to the left of $\vec{A}$; if the product is negative, point $B$ lies to the right of $\vec{A}$; and if the product is zero, the 3 points $(0,0)$, $A$, $B$ are colli... | [
"constructive algorithms",
"geometry",
"interactive",
"math"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int n;
void check_if_zero(long long x){
if (x == 0) exit(0);
}
long long get_area(int a,int b,int c){
long long result;
cout << 1 << ' ' << a << ' ' << b << ' ' << c << endl;
cin >> result;
check_if_zero(result);
assert(result > 0);
return res... |
1254 | D | Tree Queries | Hanh is a famous biologist. He loves growing trees and doing experiments on his own garden.
One day, he got a tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. A tree with $n$ vertices is an undirected connected graph with $n-1$ edges. Initially, Hanh sets the value of every vertex to $0$.
Now, ... | Disclaimer: Our other authors and testers have found better solutions; our best complexity is $O(n \times log^{2}(n))$. However, since this solution is the theoretically worst complexity that we intended to accept, I decided to write about it. Feel free to share your better solution in the comment section :) Consider t... | [
"data structures",
"probabilities",
"trees"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 150005;
const int mod = 998244353;
const int heavy = 300;
int n, m, q;
vector <int> adj[maxn];
int dad[maxn];
int sz[maxn];
vector <int> pos[maxn];
int tour[2*maxn];
vector <int> heavy_vector;
int weight[2*maxn];
int pw(int x, int y) {
int r = 1;
... |
1254 | E | Send Tree to Charlie | Christmas was knocking on the door, and our protagonist, Bob, was preparing a spectacular present for his long-time second best friend Charlie. As chocolate boxes are lame, he decided to decorate a tree instead. Bob's tree can be represented as an undirected connected graph with $n$ nodes (numbered $1$ to $n$) and $n-1... | Let's solve an easier version of this problem first: when all $a_i$ is equal to $0$. Let $P[1..n-1]$ be some order of edges. If $n=2$ then the answer is clearly $1$. Otherwise, consider any leaf $u$ and its neighbor $v$. The label of $u$ in the end will depend solely on the relative position of the edge $(u, v)$ compar... | [
"combinatorics",
"dfs and similar",
"dsu",
"trees"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 500005;
int n;
vector <int> adj[maxn];
int a[maxn];
int dad[maxn];
int h[maxn];
vector <pair <int, int> > conditions[maxn];
int nxt[maxn], prv[maxn], seen[maxn];
void no(int ncase) {
cerr << ncase << endl;
cout << 0 << e... |
1255 | A | Changing Volume | Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume.
There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or ... | Notice that if at some moment we increase the volume and at some moment we decrease the volume, we can remove those two actions and replace them with at most two new actions that are both increasing or decreasing (for instance, $+5$ $-1$ can be replaced with $+2$ $+2$; $+2$ and $-2$ can be replaced with nothing and $+2... | [
"math"
] | 800 | null |
1255 | B | Fridge Lockers | Hanh lives in a shared apartment. There are $n$ people (including Hanh) living there, each has a private fridge.
$n$ fridges are secured by several steel chains. Each steel chain connects two \textbf{different} fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to... | Author: I_love_tigersugar ft. MikeMirzayanov. Prepared by UncleGrandpa We modelize the problem as graph, where each fridge is a vertex and each chain is an edge between two vertexes. The problem is now equivalent to: Given a graph with $n$ vertexes, each vertex has a value $a_i \ge 0$. We have to add $m$ edges to the g... | [
"graphs",
"implementation"
] | 1,100 | null |
1255 | C | League of Leesins | Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end!
The tournament consisted of $n$ ($n \ge 5$) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from $1$-st to $n$-th.... | There will be exactly $2$ numbers that appear only once in the input and they are the first and the last element of the permutation. Let $p_1$ be any of them and start with the only triple that contains $p_1$. If $x, y$ are the other members of the mentioned triple, there exists a unique triple that contains $x, y$ but... | [
"constructive algorithms",
"implementation"
] | 1,600 | null |
1256 | A | Payment Without Change | You have $a$ coins of value $n$ and $b$ coins of value $1$. You always pay in exact change, so you want to know if there exist such $x$ and $y$ that if you take $x$ ($0 \le x \le a$) coins of value $n$ and $y$ ($0 \le y \le b$) coins of value $1$, then the total value of taken coins will be $S$.
You have to answer $q$... | Firstly, we obviously need to take at least $S \% n$ coins of value $1$. If we cannot do it, the answer it NO. Otherwise we always can obtain the required sum $S$ if $a \cdot n + b \ge S$. | [
"math"
] | 1,000 | #include <iostream>
using namespace std;
int main() {
int q;
cin >> q;
for (int qr = 0; qr < q; ++qr) {
int a, b, n, s;
cin >> a >> b >> n >> s;
if (s % n <= b && 1ll * a * n + b >= s) {
cout << "YES\n";
}
else {
cout << "NO\n";
}
}
} |
1256 | B | Minimize the Permutation | You are given a permutation of length $n$. Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n=... | The following greedy solution works: let's take the minimum element and move it to the leftmost position we can. With this algorithm, all forbidden operations are form the prefix of operations: ($1, 2$), $(2, 3)$, ..., and so on. So we can carry the position of the leftmost operation we can perform $pos$. Initially, it... | [
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
vector<int> a(n);
for (int j = 0; j < n; ++j) {
cin >> a[j];
--a[j];
}
int po... |
1256 | C | Platforms Jumping | There is a river of width $n$. The left bank of the river is cell $0$ and the right bank is cell $n + 1$ (more formally, the river can be represented as a sequence of $n + 2$ cells numbered from $0$ to $n + 1$). There are also $m$ wooden platforms on a river, the $i$-th platform has length $c_i$ (so the $i$-th platform... | This problem has a very easy idea but requires terrible implementation. Firstly, let's place all platforms as rightmost as we can. Thus, we will have the array, in which the first $n - \sum\limits_{i=1}^{m} c_i$ elements are zeros and other elements are $1$, $2$, ..., $m$. Now, let's start the algorithm. Firstly, we ne... | [
"greedy"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m, d;
cin >> n >> m >> d;
vector<int> c(m);
for (int i = 0; i < m; ++i) {
cin >> c[i];
}
vector<int> ans(n + 2);
for (int i = m - 1, pos = n; i ... |
1256 | D | Binary String Minimizing | You are given a binary string of length $n$ (i. e. a string consisting of $n$ characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform \textbf{no more} than $k$ moves? It is possib... | This problem has a very standard solution: let's take the leftmost zero, place it as left as possible, and solve the problem without this zero and all operations we spent. But we should do it fast. Let's go from left to right and carry the number of ones on the prefix $cnt$. If we meet $1$, let's just increase $cnt$ an... | [
"greedy"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
while (q--) {
int n;
long long k;
string s;
cin >> n >> k >> s;
string res;
int cnt = 0;
bool printed = false;
for (int i = 0;... |
1256 | E | Yet Another Division Into Teams | There are $n$ students at your university. The programming skill of the $i$-th student is $a_i$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $2 \cdot 10^5$ students ready for the finals!
Each team should consist of \tex... | Let's sort all students by their programming skills but save the initial indices to restore the answer. Now we can understand that we don't need to compose the team of size greater than $5$ because in this case we can split it into more teams with fewer participants and obtain the same or even less answer. Now we can d... | [
"dp",
"greedy",
"sortings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pt;
#define x first
#define y second
#define mp make_pair
const int N = 200043;
const int INF = int(1e9) + 43;
int n;
int dp[N];
int p[N];
pt a[N];
int t[N];
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
a[i].y = i;... |
1256 | F | Equalizing Two Strings | You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters.
In one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation:
- Choose any contiguous substring of the string $s$ of length $len$ and reverse it;
- \textbf{at the same time} cho... | The necessary condition to make strings equal is that the number of occurrences of each character should be the same in both strings. Let's show that if some character appears more than once, we always can make strings equal. How? Let's sort the first string by swapping adjacent characters (and it does not matter what ... | [
"constructive algorithms",
"sortings",
"strings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
string s, t;
cin >> n >> s >> t;
vector<int> cnts(26), cntt(26);
for (int j = 0; j < n; ++j) {
... |
1257 | A | Two Rival Students | You are the gym teacher in the school.
There are $n$ students in the row. And there are two rivalling students among them. The first one is in position $a$, the second in position $b$. Positions are numbered from $1$ to $n$ from left to right.
Since they are rivals, you want to maximize the distance between them. If ... | To solve the problem you need to understand two facts: The answer can't be greater than $n - 1$; If current distance between rivaling student if less then $n-1$ we always can increment this distance by one swap; In means that answer is equal to $\min (n - 1, |a - b| + x)$. | [
"greedy",
"math"
] | 800 | import kotlin.math.abs
fun main() {
val q = readLine()!!.toInt()
for (ct in 1..q) {
val (n, x, a, b) = readLine()!!.split(' ').map { it.toInt() }
println(minOf(n - 1, abs(a - b) + x))
}
} |
1257 | B | Magic Stick | Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a \textbf{positive} integer:
- If the chosen number $a$ is even, then the spell will turn it into $\frac{3a... | $1$ cannot be transformed into any other number. $2$ can be transformed into $3$ or $1$, and $3$ can be transformed only into $2$. It means that if $x = 1$, then only $y = 1$ is reachable; and if $x = 2$ or $x = 3$, then $y$ should be less than $4$. Otherwise, we can make $x$ as large as we want, so if $x > 3$, any $y$... | [
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int x, y;
cin >> x >> y;
if (x > 3) puts("YES");
else if (x == 1) puts(y == 1 ? "YES" : "NO");
else puts(y <= 3 ? "YES" : "NO");
}
int main() {
int tc;
cin >> tc;
while (tc--) solve();
} |
1257 | C | Dominated Subarray | Let's call an array $t$ dominated by value $v$ in the next situation.
At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. ... | At first, let's prove that the shortest dominated subarray has pattern like $v, c_1, c_2, \dots, c_k, v$ with $k \ge 0$ and dominated by value $v$. Otherwise, we can decrease its length by erasing an element from one of its ends which isn't equal to $v$ and it'd still be dominated. Now we should go over all pairs of th... | [
"greedy",
"implementation",
"sortings",
"strings",
"two pointers"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
int n;
vector<int> a;
inline bool read() {
if(!(cin >> n))
return false;
a.resize(n);
for(int i = 0; i < n; i++)
cin >> a[i];
return true;
}
inline void solve() {
int ans = n + 5;
vector<int> lst(n + 1, -1);
for(int i = 0; i < n; ... |
1257 | D | Yet Another Monster Killing Problem | You play a computer game. In this game, you lead a party of $m$ heroes, and you have to clear a dungeon with $n$ monsters. Each monster is characterized by its power $a_i$. Each hero is characterized by his power $p_i$ and endurance $s_i$.
The heroes clear the dungeon day by day. In the beginning of each day, you choo... | At first, lets precalc array $bst$; $bst_i$ is equal to maximum hero power whose endurance is greater than or equal to $i$. Now let's notice that every day it's profitable for as to kill as many monster as possible. Remains to understand how to calculate it. Suppose that we already killed $cnt$ monsters. If $a_{cnt+1} ... | [
"binary search",
"data structures",
"dp",
"greedy",
"sortings",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 99;
int t;
int n;
int a[N];
int m;
int p[N], s[N];
int bst[N];
int main() {
scanf("%d", &t);
for(int tc = 0; tc < t; ++tc){
scanf("%d", &n);
for(int i = 0; i <= n; ++i) bst[i] = 0;
for(int i = 0; i < n; ++i)
scanf("%d", a + i);
sca... |
1257 | E | The Contest | A team of three programmers is going to play a contest. The contest consists of $n$ problems, numbered from $1$ to $n$. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some num... | Suppose we want to divide $r$ first problems of the contest between the first contestant and the second contestant (the first contestant will get $l$ first problems, and the second contestant will get $r - l$ problems in the middle), and then give all the remaining problems to the third contestant. We are going to iter... | [
"data structures",
"dp",
"greedy"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int k1, k2, k3;
scanf("%d %d %d", &k1, &k2, &k3);
int n = k1 + k2 + k3;
vector<int> a(n);
for(int i = 0; i < k1; i++)
{
int x;
scanf("%d", &x);
a[x - 1] = 0;
}
for(int i = 0; i < k2; i++)
{
int x;
scanf("%d", &x);
a[x - 1] = 1;
}
for(i... |
1257 | F | Make Them Similar | Let's call two numbers similar if their binary representations contain the same number of digits equal to $1$. For example:
- $2$ and $4$ are similar (binary representations are $10$ and $100$);
- $1337$ and $4213$ are similar (binary representations are $10100111001$ and $1000001110101$);
- $3$ and $2$ are not simila... | Iterating over all possible values of $x$ and checking them may be too slow (though heavily optimized brute force is difficult to eliminate in this problem), so we need to speed this approach up. The resulting number consists of $30$ bits. Let's use the classical meet-in-the-middle trick: try all $2^{15}$ combinations ... | [
"bitmasks",
"brute force",
"hashing",
"meet-in-the-middle"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
const int N = 143;
const int K = 15;
const int V = 5000000;
int n;
li a[N];
int lst[V];
map<int, int> nxt[V];
int t = 1;
li a1[N];
li a2[N];
int get_nxt(int v, int x)
{
if(!nxt[v].count(x))
nxt[v][x] = t++;
return nxt[v][x];
}
void add(vector<i... |
1257 | G | Divisor Set | You are given an integer $x$ represented as a product of $n$ its prime divisors $p_1 \cdot p_2, \cdot \ldots \cdot p_n$. Let $S$ be the set of all positive integer divisors of $x$ (including $1$ and $x$ itself).
We call a set of integers $D$ good if (and only if) there is no pair $a \in D$, $b \in D$ such that $a \ne ... | The problem consists of two parts: what do we want to calculate and how to calculate it? What do we want to calculate? There are several ways to figure it out. At first, you could have met this problem before and all you need is to remember a solution. At second, you can come up with the solution in a purely theoretica... | [
"divide and conquer",
"fft",
"greedy",
"math",
"number theory"
] | 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())
const int LOGN = 18;
const int MOD = 998244353;
int g = 3;
int mul(int a, int b) {
return int(a * 1ll * b % MOD);
}
int norm(int a) {
while(a >= MOD) a -= MOD;
while(a < 0) a += M... |
1260 | A | Heating | Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.
Your house has $n$ rooms. In the $i$-th room you can install at most $c_i$ heating radiators. Each radiator can have several sections... | Let's denote the number of sections in the $i$-th radiator as $x_i$. Let's prove that in the optimal answer $\max(x_i) - \min(x_i) < 2$. Proof by contradiction: suppose we have $x$ and $y \ge x + 2$ in the answer, let's move $1$ from $y$ to $x$ and check: $(x + 1)^2 + (y - 1)^2 = x^2 + 2x + 1 + y^2 - 2y + 1 = (x^2 + y^... | [
"math"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
int c, sum;
inline bool read() {
if(!(cin >> c >> sum))
return false;
return true;
}
inline void solve() {
int d = sum / c;
int rem = sum % c;
cout << rem * (d + 1) * (d + 1) + (c - rem) * d * d << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdi... |
1260 | B | Obtain Two Zeroes | You are given two integers $a$ and $b$. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer $x$ and set $a := a - x$, $b := b - 2x$ or $a := a - 2x$, $b := b - x$. Note that you may choose different values of $x$ in different operations.
Is it... | Let's assume $a \le b$. Then the answer is YES if two following conditions holds: $(a+b) \equiv 0 \mod 3$, because after each operation the value $(a+b) \mod 3$ does not change; $a \cdot 2 \ge b$. | [
"binary search",
"math"
] | 1,300 | for t in range(int(input())):
a, b = map(int, input().split())
if a > b:
a, b = b, a
print ('YES' if ( ((a + b) % 3) == 0 and a * 2 >= b) else 'NO') |
1260 | C | Infinite Fence | You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of $10^{100}$ planks in two colors in the following way (suppose planks are numbered fro... | At first, suppose that $r \le b$ (if not - swap them). Let's look at the case, where $gcd(r, b) = 1$. We can be sure that there will be a situation where the $pos$-th plank is painted in blue and $pos + 1$ plank is painted in red. It's true because it's equivalent to the solution of equation $r \cdot x - b \cdot y = 1$... | [
"greedy",
"math",
"number theory"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
li a, b, k;
inline bool read() {
if(!(cin >> a >> b >> k))
return false;
return true;
}
inline void solve() {
li g = __gcd(a, b);
a /= g;
b /= g;
if(a > b)
swap(a, b);
if((k - 1) * a + 1 < b)
cout << "REBEL";
else
cout << "OBEY";
cou... |
1260 | D | A Game with Traps | You are playing a computer game, where you lead a party of $m$ soldiers. Each soldier is characterised by his agility $a_i$.
The level you are trying to get through can be represented as a straight line segment from point $0$ (where you and your squad is initially located) to point $n + 1$ (where the boss is located).... | When we fix a set of soldiers, we can determine a set of traps that may affect our squad: these are the traps with danger level greater than the lowest agility value. So we can use binary search on minimum possible agility of a soldier that we can choose. How should we actually bring our soldiers to the boss? Each trap... | [
"binary search",
"dp",
"greedy",
"sortings"
] | 1,900 | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
typedef pair<int, int> pt;
#define x first
#define y second
int m, n, k, t;
vector<int> l, r, d, a;
bool can(int x)
{
int mn = int(1e9);
for (int i = 0; i < x; i++)
mn =... |
1260 | E | Tournament | You are organizing a boxing tournament, where $n$ boxers will participate ($n$ is a power of $2$), and your friend is one of them. All boxers have different strength from $1$ to $n$, and boxer $i$ wins in the match against boxer $j$ if and only if $i$ is stronger than $j$.
The tournament will be organized as follows: ... | If our friend is the strongest boxer, he wins without any bribing. Otherwise, we have to bribe the strongest boxer - and he can defeat some $\frac{n}{2} - 1$ other boxers (directly or indirectly). Suppose we chose the boxers he will defeat, then there is another strongest boxer. If our friend is the strongest now, we d... | [
"brute force",
"dp",
"greedy"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int LOGN = 20;
const int N = (1 << LOGN) + 99;
const long long INF = 1e18;
int n;
int a[N];
long long dp[LOGN+2][N];
int sum[100];
long long calc(int cnt, int pos){
long long &res = dp[cnt][pos];
if(res != -1) return res;
if(a[pos] == -1) return res = 0;
int ... |
1260 | F | Colored Tree | You're given a tree with $n$ vertices. The color of the $i$-th vertex is $h_{i}$.
The value of the tree is defined as $\sum\limits_{h_{i} = h_{j}, 1 \le i < j \le n}{dis(i,j)}$, where $dis(i,j)$ is the number of edges on the shortest path between $i$ and $j$.
The color of each vertex is lost, you only remember that $... | Let's set the root as $1$. Define $lca(u,v)$ as the lowest common ancestor of vertices $u$ and $v$, $dep(u)$ as the depth of vertex $u$ $(dep(u) = dis(1,u))$. Obviously $dis(u,v) = dep(u) + dep(v) - 2 \times dep(lca(u,v))$. The answer we want to calculate is $\sum_{G}{\sum_{h_{i} = h_{j},i < j}{dis(i,j)}}$ where $G$ re... | [
"data structures",
"trees"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
int n ;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7 ;
vector<int> E[maxn];
vector<int> in[maxn] , out[maxn];
int cm = 0;
int l[maxn] , dfn = 0 , dep[maxn];
int g[maxn];
int siz[maxn] , top[maxn] , h[maxn] , f[maxn];
///-----segment tree
struct seg
{
int l , r;
... |
1261 | F | Xor-Set | You are given two sets of integers: $A$ and $B$. You need to output the sum of elements in the set $C = \{x | x = a \oplus b, a \in A, b \in B\}$ modulo $998244353$, where $\oplus$ denotes the bitwise XOR operation. Each number should be counted only once.
For example, if $A = \{2, 3\}$ and $B = \{2, 3\}$ you should c... | Consider a segment tree over the interval $[0,2^{60}-1]$, a node representing a segment of length $2^n$ would represent all numbers with the first $60-n$ bits same, with all possible last n bits. In other words, the binary representation of any number in the segment would be $a_1a_2a_3\ldots a_{59-n}a_{60-n}x_1x_2x_3\l... | [
"bitmasks",
"divide and conquer",
"math"
] | 3,100 | null |
1263 | A | Sweet Problem | You have three piles of candies: red, green and blue candies:
- the first pile contains only red candies and there are $r$ candies in it,
- the second pile contains only green candies and there are $g$ candies in it,
- the third pile contains only blue candies and there are $b$ candies in it.
Each day Tanya eats exac... | Sort the values of $r$, $g$, $b$ such that $r \geq g \geq b$. Now consider two cases. If $r \geq g + b$, then Tanya can take $g$ candies from piles $r$ and $g$, and then - $b$ candies from piles $r$ and $b$. After that there may be a bunch of candies left in the pile $r$ that Tanya won't be able to eat, so the answer i... | [
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int a[3];
cin >> a[0] >> a[1] >> a[2];
sort(a, a + 3);
if (a[2] <= a[0] + a[1])
cout << (a[0] + a[1] + a[2]) / 2 << ... |
1263 | B | PIN Codes | A PIN code is a string that consists of exactly $4$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.
Polycarp has $n$ ($2 \le n \le 10$) bank cards, the PIN code of the $i$-th card is $p_i$.
Polycarp has recently read a recommendation th... | Group all the numbers into groups of equals PIN-Codes. Note that the size of each such group does not exceed $10$. Therefore, in each PIN-Code we need to change no more than $1$ digits. If the group consists of $1$ element, then we do nothing, otherwise, we take all the PIN-codes except one from this group and change e... | [
"greedy",
"implementation"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<char> calced(n);
vector<string> a(n);
set<string> have;
int res = 0;
for (string &pin : a) {
cin >> pin;
have.insert(pin);
}
for (int i = 0; i < n; i++) {
if (calced[i]) {
continue;
}
vector<int> sameIds;
... |
1263 | C | Everyone is a Winner! | On the well-known testing system MathForces, a draw of $n$ rating units is arranged. The rating will be distributed according to the following algorithm: if $k$ participants take part in this event, then the $n$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawin... | There are two approaches to solving this problem. Mathematical Solution Note that the answer will always contain the numbers $0 \le x < \lfloor \sqrt{n} \rfloor$. You can verify this by solving the equation $\lfloor \frac{n}{k} \rfloor = x$, equivalent to the inequality $x \le \frac{n}{k} < x + 1$, for integer values o... | [
"binary search",
"math",
"meet-in-the-middle",
"number theory"
] | 1,400 | // #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#define ALL(s) (s).begin(), (s).end()
#define rALL(s) (s).rbegin(), (s).rend()
#define sz(s) (int)(s).size()
#define mkp make_pair
#define pb push_back
#define sqr(s) ((s) * (s))
... |
1263 | D | Secret Passwords | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters.
Hacker went home and started preparing ... | This problem can be solved in many ways (DSU, bipartite graph, std::set and so on). A solution using a bipartite graph will be described here. Consider a bipartite graph with $26$ vertices corresponding to each letter of the Latin alphabet in the first set and $n$ vertices corresponding to each password in the second s... | [
"dfs and similar",
"dsu",
"graphs"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
const int N = (int)2e5 + 100;
vector<int> g[N];
char used[N];
void addEdge(int v, int u) {
g[v].push_back(u);
g[u].push_back(v);
}
void dfs(int v) {
used[v] = 1;
for (int to : g[v]) {
if (!used[to]) {
dfs(to);
}
}
}
int main() {
int n;
cin >> n;
for (i... |
1263 | E | Editor | The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.
Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters)... | To respond to requests, you need two stacks. The first stack will contain all the brackets at the positions left than the cursor position, and the second one all the remaining ones. Also, for each closing bracket in the first stack, we will maintain the maximum depth of the correct bracket sequence (CBS) ending with th... | [
"data structures",
"implementation"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
struct MyStack {
int cnt = 0;
int allOpens = 0;
stack<int> s;
stack<int> minValue;
stack<int> maxValue;
void push(int x) {
s.push(x);
cnt += x;
if (x == 1) {
allOpe... |
1263 | F | Economic Difficulties | An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is $1$). Every other node gets electricity from the head node. Each node can be reached fr... | We assume that the leaves of the trees are numbered in the same way as the devices to which these leaves are connected. Let's calculate $cost_{l, r}$ ($l \le r$) for each tree (let's call them $upperCost_{l, r}$ and $lowerCost_{l, r}$) - the maximum number of edges that can be removed so that on the segment $[l, r]$ ex... | [
"data structures",
"dfs and similar",
"dp",
"flows",
"graphs",
"trees"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define sz(x) int((x).size())
#define all(x) begin(x), end(x)
#ifdef LOCAL
#define eprint(x) cerr << #x << " = " << (x) << endl
#define eprintf(args...) fprintf(stderr, args), fflush(stderr)
#else
#define eprint(... |
1264 | A | Beautiful Regional Contest | So the Beautiful Regional Contest (BeRC) has come to an end! $n$ students took part in the contest. The final standings are already known: the participant in the $i$-th place solved $p_i$ problems. Since the participants are primarily sorted by the number of solved problems, then $p_1 \ge p_2 \ge \dots \ge p_n$.
Help ... | To solve this problem, we have to make the following observations: All participants who solved the same number of problems must be either not awarded at all or all are awarded a same type of medal. All $g+s+b$ awarded participants are the first $g+s+b$ participants. Suppose we have an optimal solution with $g$ gold med... | [
"greedy",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n;
cin >> n;
map<int,int> c;
forn(i, n) {
int pi;
cin >> pi;
c[-pi]++;
}
ve... |
1264 | B | Beautiful Sequence | An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $1$. More formally, a sequence $s_1, s_2, \ldots, s_{n}$ is beautiful if $|s_i - s_{i+1}| = 1$ for all $1 \leq i \leq n - 1$.
Trans has $a$ numbers $0$, $b$ numbers $1$, $c$ numbers $2$ and $d$ numbers $3$. He wan... | Firstly, let's arrange even numbers. It is optimal to arrange those numbers as $0, 0, 0,\ldots,0,2, 2, \ldots 2$. Because we can place number $1$ anywhere while number $3$ only between two numbers $2$ or at the end beside a number $2$. So we need to maximize the number of positions where we can place number $3$. The ab... | [
"brute force",
"constructive algorithms",
"greedy"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> hs;
cin >> hs[0] >> hs[1] >> hs[2] >> hs[3];
int total = hs[0] + hs[1] + hs[2] + hs[3];
for (int st = 0; st < 4; st++) if (hs[st]) {
vector<int> res;
auto ths = hs;
ths[st]--;
res.push_back(st);
... |
1264 | C | Beautiful Mirrors with queries | Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$.
\textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a check... | Assuming that currently there are $k$ checkpoints $1 = x_1 < x_2 < \ldots < x_k \leq n$, the journey becoming happy of Creatnx can be divided to $k$ stages where in $i$-th stage Creatnx "moving" from mirror $x_i$ to mirror at position $x_{i+1} - 1$. Denote the $i$-th stage as $(x_i, x_{i+1}-1)$. These $k$ stages are in... | [
"data structures",
"probabilities"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 119 << 23 | 1;
struct node_t {
int prd;
int val;
node_t() {
prd = val = 0;
}
};
node_t operator + (node_t a, node_t b) {
if (!a.prd) return b;
if (!b.prd) return a;
node_t c;
c.prd = (long long) a.prd * b.prd % MOD;... |
1264 | C | Beautiful Mirrors with queries | Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$.
\textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a check... | We calculate the depth of a sequence as follow: Let two pointers at each end of the sequence. If character at the left pointer is ')', we move the left pointer one position to the right. If character at the right pointer is '(', we move the right pointer one position to the left. If the character at the left pointer is... | [
"data structures",
"probabilities"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 119 << 23 | 1;
int fpow(int a, int k) {
int r = 1, t = a;
while (k) {
if (k & 1) r = (long long) r * t % MOD;
t = (long long) t * t % MOD;
k >>= 1;
}
return r;
}
int main() {
string s; cin >> s;
int n = s.si... |
1264 | D2 | Beautiful Bracket Sequence (hard version) | This is the hard version of this problem. The only difference is the limit of $n$ - the length of the input string. In this version, $1 \leq n \leq 10^6$.
Let's define a correct bracket sequence and its depth as follow:
- An empty string is a correct bracket sequence with depth $0$.
- If "s" is a correct bracket sequ... | By the way calculate the depth in easy version we can construct a maximal depth correct bracket $S$. At $i$-th position containing '(' or '?' we will count how many times it appears in $S$. Let $x$ be the number of '(' before the $i$-th position, $y$ be the number of ')' after the $i$-th position, $c$ be the number of ... | [
"combinatorics",
"probabilities"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 119 << 23 | 1;
int inv(int a) {
int r = 1, t = a, k = MOD - 2;
while (k) {
if (k & 1) r = (long long) r * t % MOD;
t = (long long) t * t % MOD;
k >>= 1;
}
return r;
}
int main() {
string s; cin >> s;
int k =... |
1264 | E | Beautiful League | A football league has recently begun in Beautiful land. There are $n$ teams participating in the league. Let's enumerate them with integers from $1$ to $n$.
There will be played exactly $\frac{n(n-1)}{2}$ matches: each team will play against all other teams exactly once. In each match, there is always a winner and los... | Firstly, Let's calculate the number of non-beautiful triples given all result of matches. It is obvious that for each non-beautiful triple $(A, B, C)$ there exactly is one team that wins over the others. So if a team $A$ wins $k$ other teams $B_1, B_2,\ldots, B_k$ then team A corresponds to $\frac{k\cdot (k - 1)}{2}$ n... | [
"constructive algorithms",
"flows",
"graph matchings"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m; cin >> n >> m;
vector<int> d(n);
vector<vector<int>> g(n, vector<int>(n));
vector<vector<int>> f(n, vector<int>(n, 1));
for (int i = 0; i < m; i++) {
int u, v; cin >> u >> v; u--, v--;
d[u]++;
g[u][v] = 1, ... |
1264 | F | Beautiful Fibonacci Problem | The well-known Fibonacci sequence $F_0, F_1, F_2,\ldots $ is defined as follows:
- $F_0 = 0, F_1 = 1$.
- For each $i \geq 2$: $F_i = F_{i - 1} + F_{i - 2}$.
Given an increasing arithmetic sequence of positive integers with $n$ elements: $(a, a + d, a + 2\cdot d,\ldots, a + (n - 1)\cdot d)$.
You need to find another ... | Intuitively, we want to a formula for $F_{m + n}$. This is one we need: $F_{m + n} = F_m\cdot F_{n + 1} + F_{m - 1}\cdot F_n$. Denote $n = 12\cdot 10^k$, one can verify that $F_{i\cdot n} \equiv 0$ modulo $10^k$ (directly calculate or use 'Pisano Period'). So we have following properties: $F_{2\cdot n + 1} = F_{n + 1}^... | [
"constructive algorithms",
"number theory"
] | 3,500 | n,a,d=map(int,input().split())
print(368131125*a%10**9*12*10**9+1,368131125*d%10**9*12*10**9)
|
1265 | A | Beautiful String | A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each... | If string $s$ initially contains 2 equal consecutive letters ("aa", "bb" or "cc") then the answer is obviously -1. Otherwise, it is always possible to replacing all characters '?' to make $s$ beautiful. We will replacing one '?' at a time and in any order (from left to right for example). For each '?', since it is adja... | [
"constructive algorithms",
"greedy"
] | 1,000 | T = int(input())
for tc in range(T):
s = [c for c in input()]
n = len(s)
i = 0
while (i < n):
if (s[i] == '?'):
prv = 'd' if i == 0 else s[i - 1]
nxt = 'e' if i + 1 >= n else s[i + 1]
for x in ['a', 'b', 'c']:
if (x != prv) and (x != nxt):
... |
1265 | B | Beautiful Numbers | You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$.
For example, let $p ... | A number $m$ is beautiful if and only if all numbers in range $[1, m]$ occupies $m$ consecutive positions in the given sequence $p$. This is equivalent to $pos_{max} - pos_{min} + 1 = m$ where $pos_{max}, pos_{min}$ are the largest, smallest position of $1, 2, \dots, m$ in sequence $p$ respectively. We will consider $m... | [
"data structures",
"implementation",
"math",
"two pointers"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 239;
int n, p[M], x;
void solve()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> x;
p[x - 1] = i;
}
int l = n;
int r = 0;
string ans = "";
for (int i = 0; i < n; i++)
{
l = min(l, p[i]);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.