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 ⌀ |
|---|---|---|---|---|---|---|---|
1213 | F | Unstable String Sort | Authors have come up with the string $s$ consisting of $n$ lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) $p$ and $q$ (both of length $n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once.
For all $i$ from $1... | Because if we write down all characters of $s$ in order of both permutations and this string will be sorted, it is obvious that these two strings are equal. Let's try the maximum possible number of distinct characters and then replace extra characters with 'z'. How to find the maximum number of distinct characters? Let... | [
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"implementation",
"strings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<int> p1(n), p2(n);
for (int i = 0; i < n; ++i) {
cin >> p1[i];
--p1[i];
}
for (int i = 0; i < n; ++i) {
cin >> p2[i];
... |
1213 | G | Path Queries | You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$.
You are given $m$ queries. The $i$-th query is given as an integer $q_i$. In this query you need to calculate the number of pairs of ver... | Let's carry the value $res$ that means the answer for the current set of edges. Initially it is $0$. Let's sort all edges by their weight and all queries by their weight also (both in non-decreasing order). Let's merge components of the tree using DSU (disjoint set union). We need to carry sizes of components also (it ... | [
"divide and conquer",
"dsu",
"graphs",
"sortings",
"trees"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
vector<int> p, rk;
int getp(int v) {
if (v == p[v]) return v;
return p[v] = getp(p[v]);
}
long long res;
long long get(int cnt) {
return cnt * 1ll * (cnt - 1) / 2;
}
void merge(int u, int v) {
u = getp(u);
v = getp(v);
if (rk[u] < rk[v]) swap(u, v);
res -= ... |
1214 | A | Optimal Currency Exchange | Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $n$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar... | If we have bought dollar bills with value of two or more dollar bill, we can change it one-dollar bills. Same goes for euro, we can replace all euro bills with several $5$-euro bills. Now we can simply try buying some number of five-euro bills and buying all the rest with one-dollar bills. Complexity is $\mathcal{O}(n)... | [
"brute force",
"math"
] | 1,400 | null |
1214 | B | Badges | There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them.
Organizers are preparing red badges for girls and blue ones for boys.
... | Vasya must take one deck for each possible combination $(participants_{girls}, participants_{boys})$ (where $0 \le participants_{girls} \le g$, $0 \le participants_{boys} \le b$ and $participants_{girls} + participants_{boys} = n$). Let's determine how many girls can come for the game: at least $n - min(b, n)$, at most... | [
"brute force",
"math"
] | 1,100 | null |
1214 | C | Bad Sequence | Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.
To make everything right, Petya is going to move at most one bracket from it... | Let's call a balance of bracket sequence a number of opening brackets minus the number of closing brackets. Correct bracket sequence is such a sequence that balance of any of its prefixes is at least $0$ and the balance of the entire sequence is equal to $0$. To solve the problem let's consider the shortest prefix with... | [
"data structures",
"greedy"
] | 1,200 | null |
1214 | D | Treasure Island | All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.
Treasure Island may be represented as a rectangular table $n \times m$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $1$ to $n$ from top to bottom and columns with consecutive in... | The answer is no more than two as we can block $(2, 1)$ and $(1, 2)$. If there is no way from $(1, 1)$ to $(n, m)$, the answer is zero. The only thing to do is to distinguish $k = 1$ and $k = 2$. If answer is one, there must exist such cell $(x, y)$ that each path from $(1, 1)$ to $(n, m)$ goes through that cell. Also ... | [
"dfs and similar",
"dp",
"flows",
"hashing"
] | 1,900 | null |
1214 | E | Petya and Construction Set | It's Petya's birthday party and his friends have presented him a brand new "Electrician-$n$" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.
Construction set "Electrician-$n$" consists of $2n - 1$ wires and $2n$ light bulbs. Each bulb has its own unique index tha... | Assume without loss of generality that the array $d$ sorted in non-increasing order. Let's make a linear ("bamboo") graph from the vertices $1, 3, 5, \ldots, 2n - 1$ in this order. We will add nodes $2i$ one by one, we will also maintain the longest route during that. On the $i$-th step we are looking for the vertex at... | [
"constructive algorithms",
"graphs",
"math",
"sortings",
"trees"
] | 2,000 | null |
1214 | F | Employment | Two large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total $n$ vacancies in all of their offices. After many tests and interviews $n$ candidates were selected and the only thing le... | First, let's notice that the optimal answer can be achieved without changing the relative order of candidates. That means that if we order candidates by circle clockwise, the second candidate will work at the next clockwise workplace from the first candidate's workplace, the third candidate will work at the next clockw... | [
"greedy",
"sortings"
] | 2,700 | null |
1214 | G | Feeling Good | Recently biologists came to a fascinating conclusion about how to find a chameleon mood. Consider chameleon body to be a rectangular table $n \times m$, each cell of which may be green or blue and may change between these two colors. We will denote as $(x, y)$ ($1 \leq x \leq n$, $1 \leq y \leq m$) the cell in row $x$ ... | Let's define the set $A_i$ for each $1 \leq i \leq n$ as a set of columns $j$, such that the color of the cell $(i, j)$ is blue. If there exists two rows $1 \leq x_1 < x_2 \leq n$, such that $A_{x_1} \not\subset A_{x_2}$ and $A_{x_2} \not\subset A_{x_1}$ the good mood certificate exists. It's easy to see, because if $A... | [
"bitmasks",
"data structures"
] | 3,200 | null |
1214 | H | Tiles Placement | The new pedestrian zone in Moscow city center consists of $n$ squares connected with each other by $n - 1$ footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a si... | Suppose there exists a vertex with tree with a tree paths going from it, with longest paths of lengths $a$, $b$ and $c$ (in edges). Then if $a + b \ge k - 1$, $b + c \ge k - 1$, $a + c \ge k - 1$, then clearly the answer is Impossible. We can check whether such vertex exists in $\mathcal{O}(n)$ using subtree dp and "up... | [
"constructive algorithms",
"dfs and similar",
"trees"
] | 2,800 | null |
1215 | A | Yellow Cards | The final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team.
The rules of sending players off the game are a bit different in Berland footba... | At first, if $k_1 > k_2$, then we swap $k_1$ with $k_2$ and $a_1$ with $a_2$, so the number of yellow cards required to send a player of the first team off is not greater than the same value for the second team. If all players from the first team receive $k_1 - 1$ cards each and all players from the second team receive... | [
"greedy",
"implementation",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int a1, a2, k1, k2, n;
inline void read() {
cin >> a1 >> a2 >> k1 >> k2 >> n;
}
inline void solve() {
if (k1 > k2) {
swap(k1, k2);
swap(a1, a2);
}
int minCnt = max(0, n — a1 * (k1 — 1) — a2 * (k2 — 1));
int maxCnt = 0;
if (n <= a1 * k1... |
1215 | B | The Number of Products | You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ non-zero integers (i.e. $a_i \ne 0$).
You have to calculate two following values:
- the number of pairs of indices $(l, r)$ $(l \le r)$ such that $a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$ is negative;
- the number of pairs of indices $(l, r)$ $(l... | At first, let's calculate the value of $ans_p$ - the number of subsegments with positive product. We should iterate through the array and store $bal$ - the number of negative elements. Also we should store $cnt_1$ and $cnt_2$ - the number of elements such that there is an even number of negative elements before them ($... | [
"combinatorics",
"dp",
"implementation"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
const int N = 200 * 1000 + 13;
int n;
int a[N];
inline void read() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
inline void solve() {
int pos = -1;
li ans0 = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
pos = i;
}
if (pos != -1) {
... |
1215 | C | Swap Letters | Monocarp has got two strings $s$ and $t$ having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings $s$ and $t$ equal to each other. He can do the following operation any number of times: choose an index $pos_1$ in the string $s$, choose an index $pos_2$ ... | Let's calculate two vectors $pos_{01}$ and $pos_{10}$. $pos_{01}$ will contain all positions $x$ such that $s[x] = 0$ and $t[x] = 1$. Analogically, $pos_{10}$ will contain all positions $x$ such that $s[x] = 1$ and $t[x] = 0$. If the sizes of these vectors are not equal modulo $2$, the answer does not exist, because th... | [
"constructive algorithms",
"greedy"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
int n;
string s, t;
inline void read() {
cin >> n >> s >> t;
}
inline void solve() {
vector<int> pos01, pos10;
for (int i = 0; i < n; i++) {
if (s[i] != t[i]) {
if (s[i] == 'a') {
pos01.pb(i);
} else {
pos10.pb(i);
}
}
}
if (sz(pos01) % 2 != sz... |
1215 | D | Ticket Game | Monocarp and Bicarp live in Berland, where every bus ticket consists of $n$ digits ($n$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. \textbf{The number of digits that have been erased is even}.
Monocarp and Bicarp have decided to play a game ... | Let's denote the balance as the difference between the sum of digits in the left half and the sum of digits in the right half. Also let $L$ be the minimum possible balance (it can be calculated if we replace all question marks in the left half with $0$'s and all the question marks in the right half with $9$'s), and let... | [
"games",
"greedy",
"math"
] | 1,700 | #include <iostream>
#include <set>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int main() {
cin >> n;
long double sum1 = 0, sum2 = 0;
string s;
cin >> s;
for (int i = 0; i < n; i++) {
if (s[i] != '?') {
if (i < n / 2) {... |
1215 | E | Marbles | Monocarp has arranged $n$ colored marbles in a row. The color of the $i$-th marble is $a_i$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to r... | The main fact is that the number of colors is less than $20$, which allows us to use exponential solutions. For each pair of colors $(i, j)$, we can calculate $cnt[i][j]$ - the number of swaps required to place all marbles of color $i$ before all marbles of color $j$ (if we consider only marbles of these two colors). W... | [
"bitmasks",
"dp"
] | 2,200 | #include <iostream>
#include <set>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1000 * 1000 + 13;
const int M = 20 + 1;
const long long INF = 1000 * 1000 * 1000 * 1ll * 1000 * 1000 * 1000;
int n;
long long d[(1 << M)];
long long cnt[M][M];
vector<int> col[M];
int main(... |
1215 | F | Radio Stations | In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. $n$ complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the $i$-th complaint, one of the radio fans has mentioned that the signals... | Let's try to solve the problem without any constraints on $f$ (we just need to choose a set of stations that satisfies all the complaints and contains no forbidden pair). We can see that this is an instance of 2-SAT: we can convert it into a logical expression that is a conjunction of some clauses, and each clause cont... | [
"2-sat"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 1600043;
vector<int> g[N];
vector<int> gt[N];
int used[N];
vector<int> order;
int comp[N];
vector<int> result;
int v;
void add_edge(int v1, int v2)
{
g[v1].push_back(v2);
gt[v2].push_back(v1);
}
void add_disjunction(int v1, int v2)
{
add_edge(v1 ^ 1, v2... |
1216 | A | Prefixes | Nikolay got a string $s$ of \textbf{even} length $n$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $1$ to $n$.
He wants to modify his string so that every its prefix of \textbf{even} length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform t... | The problem can be solved like this: firstly let's iterate over all $i$ from $1$ to $\frac{n}{2}$. If characters $s_{2i-1}$ and $s_{2i}$ are the same then we obviously need to replace one of them with the other character. We can see that such replacements are enough to make the string suitable. | [
"strings"
] | 800 | n, s = int(input()), list(input())
ans = 0
for i in range(0, n, 2):
if (s[i] == s[i + 1]):
s[i] = chr(1 - ord(s[i]) + 2 * ord('a'))
ans += 1
print(ans)
print(''.join(s)) |
1216 | B | Shooting | Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $n$ cans in a row on a table. Cans are numbered from left to right from $1$ to $n$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose \textbf{the order}... | We can see that because the multiplier $x$ in the formula $(a_i \cdot x + 1)$ is the position of the number and we want to minimize the sum of such formulas, the following greedy solution comes up to mind: because we want to count greater values as earlier as possible, let's sort the array $a$ in non-increasing order (... | [
"greedy",
"implementation",
"sortings"
] | 900 | n, a = int(input()), list(map(int, input().split()))
res = []
ans = 0
for i in range(n):
pos = -1
for j in range(n):
if (pos == -1 or a[j] > a[pos]): pos = j
res.append(pos + 1)
ans += i * a[pos] + 1
a[pos] = 0
print(ans)
print(' '.join([str(x) for x in res])) |
1216 | C | White Sheet | There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates $(0, 0)$, and coordinate axes are left and bottom sides of the table, then the bo... | There are at least two solution to the problem. I'll describe both of them. The first solution: firstly let's notice that the point we search can have non-integer coordinates, but if the answer exists then there will be the answer such that its point has at most half-integer coordinates. So let's multiply all coordinat... | [
"geometry",
"math"
] | 1,700 | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <random>
#include <ctime>
#include <string>
#include <iomanip>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
typedef long long li;
typedef unsigned long long ul... |
1216 | D | Swords | There were $n$ types of swords in the theater basement which had been used during the plays. Moreover there were \textbf{exactly} $x$ swords of each type. $y$ people have broken into the theater basement and each of them has taken exactly $z$ swords of some \textbf{single type}. Note that different people might have ta... | Firstly, let's notice that for the fixed value of $z$ our problem is reduced to the following: we are given $n$ numbers $a_1, a_2, \dots, a_n$. We need to choose such values $k_1, k_2, \dots, k_n$ that $a_1 + k_1 \cdot z = a_2 + k_2 \cdot z = \dots = a_n + k_n \cdot z$. And among all such values $k_1, k_2, \dots, k_n$ ... | [
"math"
] | 1,300 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
1216 | E1 | Numerical Sequence (easy version) | \textbf{The only difference between the easy and the hard versions is the maximum value of $k$}.
You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the secon... | Let's take a look on the upper bound of the number $n$, where $n$ is the maximum possible number of block which can be asked. If we assume that each number has length $1$ then the sum of lengths will be equal to $1 + 2 + \dots + n$. And as we know this value equals $\frac{n(n+1)}{2}$. So the maximum value of $n$ is not... | [
"binary search",
"brute force",
"math"
] | 1,900 | #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--) {
long long k;
cin >> k;
--k;
long long lst = 0;
long long nxtpw = 1;
int numlen = 0;
for (long long i = 1; ; ++i)... |
1216 | E2 | Numerical Sequence (hard version) | \textbf{The only difference between the easy and the hard versions is the maximum value of $k$}.
You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the secon... | This problem idea is not very hard. Now $n$ can be up to $10^9$ so we need to find the number of block $i$ faster. Let's do binary search on it! Now using some shitty pretty formulas we can determine if the total sum of lengths of blocks from $1$ to $i$ is greater than or equal to $k$ or not. And more about these formu... | [
"binary search",
"math"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
long long get(long long r) {
return (r + 1) * r / 2;
}
long long sumto(long long r, int need) {
long long pw = 1;
long long sum = 0;
long long add = 0;
for (int len = 1; ; ++len) {
if (pw * 10 - 1 < r) {
long long cnt = pw * 10 - pw;
if (need) {
sum += a... |
1216 | F | Wi-Fi | You work as a system administrator in a dormitory, which has $n$ rooms one after another along a straight hallway. Rooms are numbered from $1$ to $n$.
You have to connect all $n$ rooms to the Internet.
You can connect each room to the Internet directly, the cost of such connection for the $i$-th room is $i$ coins.
S... | Firstly, I know that this problem has very pretty linear solution and its author can describe it if he wants. I'll describe my own solution without any data structures but std::set. Let $dp_i$ be the total cost to connect all rooms from $i$ to $n-1$ to the Internet ($0$-indexed). Initially $dp_{n} = 0$, all other value... | [
"data structures",
"dp",
"greedy"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<long long> dp(n + 1);
multiset<long long> mins, vals;
mins.insert(0);
vector<vector<long long>> del(n... |
1217 | A | Creating a Character | You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point you can either rais... | Let $addS$ and $addI$ be number of free points that we invest in the strength and intelligence respectively. It's obvious that $addS + addI = exp$ since we must spend all free points. From the other side we must make $str + addS > int + addI$. Now we can expess $addI = exp - addS$ and put it in the inequality: $str + a... | [
"binary search",
"math"
] | 1,300 | fun main() {
val t = readLine()!!.toInt()
for (ct in 1..t) {
val (str, int, exp) = readLine()!!.split(' ').map { it.toInt() }
val minAddStr = maxOf(0, (exp + int - str + 2) / 2)
println(maxOf(exp - minAddStr + 1, 0))
}
} |
1217 | B | Zmei Gorynich | You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!
Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is th... | Lets divide all dealing blows into two parts: the last blow and others blows. The last hit should be with maximum value of $d$. The others blows should be with the maximum value of $d - h$. So, lets denote $\max\limits_{1 \le i \le n} d_i$ as $maxD$ and $\max\limits_{1 \le i \le n} (d_i - h_i)$ as $maxDH$. Then if $x \... | [
"greedy",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 105;
int t;
int n, m;
int d[N], h[N];
int main() {
cin >> t;
for(int tc = 0; tc < t; ++tc){
cin >> n >> m;
int maxDH = -2e9;
for(int i = 0; i < n; ++i){
cin >> d[i] >> h[i];
maxDH = max(maxDH, d[i] - h[i]);
}
int res = 1;
int maxD = *... |
1217 | C | The Number Of Good Substrings | You are given a binary string $s$ (recall that a string is binary if each character is either $0$ or $1$).
Let $f(t)$ be the decimal representation of integer $t$ written in binary form (possibly with leading zeroes). For example $f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$ and $f(000100) = 4$.
The... | At first, lets precalc the array $nxt_1, nxt_2, \dots , nxt_n$. The value of $nxt_i$ if equal the maximum position $j$ in range $1 \dots i$ such that $s_j = 1$. After that lets iterate over the right boundary of substring and high $1$-bit position (denote it as $r$ and $l$ respectively). Note that if $r - l > 18$ then ... | [
"binary search",
"bitmasks",
"brute force"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int t;
string s;
int nxt[N];
int main() {
cin >> t;
for(int tc = 0; tc < t; ++tc){
cin >> s;
for(int i = 0; i < s.size(); ++i)
if(s[i] == '1') nxt[i] = i;
else nxt[i] = (i == 0? -1 : nxt[i - 1]);
int res = 0;
for(int r = 0;... |
1217 | D | Coloring Edges | You are given a directed graph with $n$ vertices and $m$ directed edges without self-loops or multiple edges.
Let's denote the $k$-coloring of a digraph as following: you color each edge in one of $k$ colors. The $k$-coloring is \textbf{good} if and only if there no cycle formed by edges of same color.
Find a good $k... | Let's run dfs on the graph and color all "back edges" ($(u, v)$ is back edge if there is a path from $v$ to $u$ by edges from dfs tree) in black and all other edges in white. It can be proven that any cycle will have at least one white edge and at least black edge. Moreover each back edge connected with at least one cy... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,100 | #include<bits/stdc++.h>
using namespace std;
const int N = int(1e6) + 55;
int n, m;
vector <pair<int, int> > g[N];
int col[N];
bool cyc;
int res[N];
void dfs(int v){
col[v] = 1;
for(auto p : g[v]){
int to = p.first, id = p.second;
if(col[to] == 0){
dfs(to);
res[id] = 1;
}
else if(col[to] == 2)
re... |
1217 | E | Sum Queries? | Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that ho... | We are given the definition of the balanced multiset but let's instead fix the criteria to determine if the multiset is unbalanced. Take an empty multiset and start adding numbers to it until it becomes unbalanced. Empty set to the set of one number is trivial. Now for the second number. If there is some position such ... | [
"data structures",
"greedy",
"implementation",
"math"
] | 2,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 200 * 1000 + 13;
const int INF = 2e9;
const int LOGN = 9;
struct node{
int best;
int mn[LOGN];
node(){
best = INF;
forn(i, LOGN)
mn[i] = INF;
}
int& operator [](int x){
return mn[x];
}
};
... |
1217 | F | Forced Online Queries Problem | You are given an undirected graph with $n$ vertices numbered from $1$ to $n$. Initially there are no edges.
You are asked to perform some queries on the graph. Let $last$ be the answer to the latest query of the second type, it is set to $0$ before the first such query. Then the queries are the following:
- $1~x~y$ (... | The problem directly tells you do solve some kind of Dynamic Connectivity Problem. You could use the online approach with Link-Cut Tree if you'd had its implementation beforehand. There is also a nice modification to the $log^2$ solution of the offline version of DCP (check out the comment). I'd tell the solution which... | [
"data structures",
"divide and conquer",
"dsu",
"graphs",
"trees"
] | 2,600 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int BUF = 10 * 1000 * 1000 + 13;
const int N = 300 * 1000 + 13;
const int M = 300 * 1000 + 13;
const int P = 400;
struct query{
int t, x, y;
int e0, e1;
};
int n, m;
query q[M];
int p[N], rk[N];
int cnt;
int... |
1220 | A | Cards | When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | It's easy to see that letter $\text{z}$ contains only in $\text{zero}$ and $\text{n}$ contains only in $\text{one}$, so we should print $1$ $count(\text{n})$ times and then $0$ $count(\text{z})$ times. | [
"implementation",
"sortings",
"strings"
] | 800 | null |
1220 | B | Multiplication Table | Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \cdot a_j$ where $a_1, \dots, a_n$ is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was havi... | Let's note that $\frac{(xy) \cdot (xz)}{(yz)} = x^2$ if $x, y, z > 0$. In this problem $n \ge 3$, so we can get each value this way. | [
"math",
"number theory"
] | 1,300 | null |
1220 | C | Substring Game in the Lesson | Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $s$ and a number $k$ ($0 \le k < |s|$).
At the beginning of the game, players are given a substring of $s$ with left border $l$ and right border $r$, bo... | The main idea of this task is that Mike never moves. Lets fix $k$, there two cases: 1) $s[k] \ge s[i]$ for all $i < k$, in this case $s[k, k] \le s[l, r]$ for all $l \le k$ and $r \ge k$, so Ann can't make her first move (Mike wins). 2) There is $i < k$ such that $s[i] < s[k]$. In this case Ann can move with substring ... | [
"games",
"greedy",
"strings"
] | 1,300 | null |
1220 | D | Alex and Julian | Boy Dima gave Julian a birthday present — set $B$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer... | Let all numbers in $B$ be odd. If two vertices $i$ and $j$ are connected, then they have different parity, hence our graph is already bipartite (first part is even vertices, second - odd vertices). Now let's see that if we choose an integer $k > 0$, multiply all elements of the set by $2^k$ and build a new graph on thi... | [
"bitmasks",
"math",
"number theory"
] | 1,900 | null |
1220 | E | Tourism | Alex decided to go on a touristic trip over the country.
For simplicity let's assume that the country has $n$ cities and $m$ bidirectional roads connecting them. Alex lives in city $s$ and initially located in it. To compare different cities Alex assigned each city a score $w_i$ which is as high as interesting city se... | Let's note that if you visit a vertex $u$ located on a loop, you can always add the numbers on vertices in this loop to answer and you can also add the numbers on vertices between $u$ and $s$. It is true because you can just visit $u$, go through the vertices of the cycle, return to $u$ and then go back to $s$. But if ... | [
"dfs and similar",
"dp",
"dsu",
"graphs",
"greedy",
"trees"
] | 2,200 | null |
1220 | F | Gardener Alex | Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $n$ vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $1$ to $n$ which he was presented at his last birthday,... | Notice that element $a$ is an ancestor of an element $b$ when it's minimum on a subsegment from $a$ to $b$. Count amount of ancestors for every element in initial permutation. Now, when you remove element $l$ from the left, all elements between it and the leftmost element smaller than $l$ now have one ancestor less. Wh... | [
"binary search",
"data structures"
] | 2,700 | null |
1220 | G | Geolocation | You are working for the Gryzzl company, headquartered in Pawnee, Indiana.
The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be $n$ antennas located somewhere in the par... | Let's look on the sum of squared distances from unknown point $(x;y)$ to all known points $(x_i;y_i)$: $\sum\limits_{i=1}^n d_i^2 = \sum\limits_{i=1}^n\left((x-x_i)^2+(y-y_i)^2\right)= n(x^2+y^2)-2x\sum\limits_{i=1}^n x_i - 2y\sum\limits_{i=1}^n y_i + \sum\limits_{i=1}^n (x_i^2+y_i^2)$ If we switch to new coordinates w... | [
"geometry"
] | 3,400 | null |
1221 | A | 2048 Game | You are playing a variation of game 2048. Initially you have a multiset $s$ of $n$ integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two \textbf{equal} integers from $s$, remove them from $s$ and inse... | It's obvious that we don't need elements that are larger than $2048$. If the sum of the remaining elements is greater than or equal to 2048, then the answer is YES, and NO otherwise. It's true because for getting a integer $x$ that wasn't in the multiset initially, we first need to get integer $\frac{x}{2}$. | [
"brute force",
"greedy",
"math"
] | 1,000 | for t in range(int(input())):
n = input()
l = filter(lambda x : x <= 2048, map(int, input().split()) )
print('YES' if sum(l) >= 2048 else 'NO') |
1221 | B | Knights | You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.
A knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the following conditions is m... | Let's denote a cell ($i$, $j$) as black if $i + j$ is even, otherwise the cell is white. It's easy to see that if a knight is occupying a black cell, then all cells attacked by it are white, and vice versa. Using this fact, we can construct a solution where every pair of knights that attack each other have different co... | [
"constructive algorithms",
"greedy"
] | 1,100 | n = int(input())
for i in range(n):
print(''.join(['W' if (i + j) % 2 == 0 else 'B' for j in range(n)])) |
1221 | C | Perfect Team | You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. \textbf{She/he can have no specialization, but can't have both at the same time.}
So the team is considered perfect if ... | Notice that if $c \ne m$, then you can equalize them to the min and re-qualify the rest into students without specialization. That won't change the answer. Now analyze the possible team formations: 1 of each kind, 2 coders and 1 mathematician or 1 coder and 2 mathematicians. Each of these squads have 1 coder and 1 math... | [
"binary search",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main(){
int q;
cin >> q;
for (int i = 0; i < q; ++i){
int c, m, x;
cin >> c >> m >> x;
int l = 0, r = min(c, m);
int ans = 0;
while (l <= r){
int mid = (l + r) / 2;
if (c + m + x - 2 * mid >= mid){
l = mid + 1;
ans = mid;
}
else{
r... |
1221 | D | Make The Fence Great Again | You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $2$ to $n$, the condition $a... | Let's notice that in optimal answer all boards will be increased by no more than two. It is true because if it is beneficial to increase the length of some board by three or more (denote its length as $len$) then increasing to the length $len - 1$, $len - 2$ or $len - 3$ is cheaper and one of these boards is not equal ... | [
"dp"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
const long long INF64 = (long long)(1e18) + 100;
int t;
int n;
int a[N];
int b[N];
long long dp[3][N];
long long calc(int add, int pos){
long long &res = dp[add][pos];
if(res != -1) return res;
res = INF64;
if(pos == n) return res = 0;
... |
1221 | E | Game With String | Alice and Bob play a game. Initially they have a string $s_1, s_2, \dots, s_n$, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must se... | At first, let's transform input to a more convenient form. We consider only such subsegments that consist of the symbols . and which cannot be expanded to the right or left. For example, for $s = XX...X.X...X..$ we consider segments of length $3$, $1$, $3$, and $2$. Let's divide all such segments into four groups by th... | [
"games"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 99;
int t;
int a, b;
string s;
int main() {
cin >> t;
for(int tc = 0; tc < t; ++tc){
cin >> a >> b >> s;
vector <int> v;
int l = 0;
while(l < s.size()){
if(s[l] == 'X'){
++l;
continue;
}
int r = l + 1;
while(r < s.... |
1221 | F | Choose a Square | Petya recently found a game "Choose a Square". In this game, there are $n$ points numbered from $1$ to $n$ on an infinite field. The $i$-th point has coordinates $(x_i, y_i)$ and cost $c_i$.
You have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong t... | Notice that the square ($l, l$) ($r, r$) covers the point ($x, y$) if and only if $l \le min(x, y) \le max(x, y) \le r$. Using this fact, let's reformulate the problem the following way: we have to find the segment $(l, r)$, such that the sum of the segments fully covered by it is maximal. Let's build a segment tree, t... | [
"binary search",
"data structures",
"sortings"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef long long li;
typedef pair<int, int> pt;
const int N = 1000 * 1000 ... |
1221 | G | Graph And Numbers | You are given an undirected graph with $n$ vertices and $m$ edges. You have to write a number on each vertex of this graph, each number should be either $0$ or $1$. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge.
You have to choose the numbers you will write o... | Let $F(S)$ be the number of ways to paint the graph so that all numbers on edges belong to the set $S$. Using inclusion-exclusion we may get that the answer is $F(\{0, 1, 2\}) - F(\{1, 2\}) - F(\{0, 2\}) + F(\{2\}) - F(\{0, 1\}) + F(\{1\}) + F(\{0\}) - F(\{\})$. Okay, let's analyze everything separatedly. $F(\{0, 1, 2\... | [
"bitmasks",
"brute force",
"combinatorics",
"dp",
"meet-in-the-middle"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int N = 40;
const int M = 20;
long long incident_mask[N];
vector<int> g[N];
int n, m;
long long ans = 0;
long long cntmask[1 << M];
long long binpow(long long x, long long y)
{
long long z = 1;
while(y > 0)
{
if(y % 2 == 1) z *= x;
x *= x;
y /= 2;
}
ret... |
1223 | A | CME | Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero.
For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are... | If $n$ is odd then we have to buy at least one match because integers $a+b$ and $c$ ($a$, $b$ and $c$ is elements of equation $a+b=c$) must be of the same parity, so integer $a+b+c$ is always even. If $n$ is even then we can assemble an equation $1 + \frac{n-2}{2} = \frac{n}{2}$. But there is one corner case. If $n = 2... | [
"math"
] | 800 | for t in range(int(input())):
n = int(input())
print(2 if n == 2 else (n & 1)) |
1223 | B | Strings Equalization | You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two \textbf{adjacent} characters in \textbf{any} string and assign the value of the first character to the value of the ... | If there is a character which is contained in string $s$ and $t$ (let's denote it as $c$), then we answer is "YES" because we can turn these string into string consisting only of this character $c$. Otherwise the answer is "NO", because if initially strings have not a common character, then after performing operation t... | [
"strings"
] | 1,000 | for t in range(int(input())):
print('NO' if len(set(input()) & set(input())) == 0 else 'YES') |
1223 | C | Save the Nature | You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have $n$ tickets to sell. The price of the $i$-th ticket is $p_i$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutatio... | At first, let's assume that $x \ge y$ (otherwise, we can swap parameters of programs). Let's define $cont(len)$ as the maximum contribution we can get selling exactly $len$ tickets. Note, in general case sold ticket can be one of $4$ types: tickets with $(x + y)\%$ of the price are contributed; the number of such ticke... | [
"binary search",
"greedy"
] | 1,600 | fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long {
var ans = 0L
var (cX, cY, cXY) = listOf(0, 0, 0)
for (i in 1..len) {
if (i % a == 0 && i % b == 0) cXY++
else if (i % a == 0) cX++
else if (i % b == 0) cY++
}
for (i in 0 until cXY)
ans += p[i] * ... |
1223 | D | Sequence Sorting | You are given a sequence $a_1, a_2, \dots, a_n$, consisting of integers.
You can apply the following operation to this sequence: choose some integer $x$ and move \textbf{all} elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in \textbf{one} direction in ... | Let's consider two sequences of integers $m_1 < m_2 < \dots < m_k$ and $d_1 < d_2 < \dots < d_l$. Sequence $m$ contains integers which were used in some operation in the optimal answer. Sequence $d$ contains integers which were not used. For example, if $a = [2, 1, 3, 5, 4]$, then optimal answer is move all $1$-element... | [
"dp",
"greedy",
"two pointers"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
const int INF = int(1e9) + 99;
int t, n;
int a[N];
int l[N], r[N];
int dp[N];
int main() {
scanf("%d", &t);
for(int tc = 0; tc < t; ++tc){
scanf("%d", &n);
for(int i = 0; i < n; ++i){
l[i] = INF;
r[i] = -INF;
dp[i] = 0;
}
... |
1223 | E | Paint the Tree | You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$.
Let's define the $k$-coloring of the tree as an assignment of exactly $k$ colors to \textbf{each} vertex, so that each color is used no ... | It is obvious that if we paint two vertices in the same color, they should be adjacent to each other - otherwise we could paint them in different colors, and the answer would not be worse. So we can reduce the problem to the following: choose a set of edges with maximum cost such that no vertex is adjacent to more than... | [
"dp",
"sortings",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 500 * 1000 + 13;
int n, k;
vector<pair<int, int>> g[N];
long ... |
1223 | F | Stack Exterminable Arrays | Let's look at the following process: initially you have an empty stack and an array $s$ of the length $l$. You are trying to push array elements to the stack in the order $s_1, s_2, s_3, \dots s_{l}$. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you j... | Let's understand how calculate the array $nxt$, such that $nxt_l$ is equal to the minimum index $r > l$ such that subarray $a_{l \dots r}$ is stack exterminable. If there is no such index, then $nxt_l = -1$. If we calculate this array then we solve this task by simple dynamic programming. Let's calculate it in order $n... | [
"data structures",
"divide and conquer",
"dp",
"hashing"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int t, n;
int a[N];
int nxt[N];
int dp[N];
map<int, int> nxtX[N];
int main() {
scanf("%d", &t);
for(int tc = 0; tc < t; ++tc){
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%d", a + i);
for(int i = 0; i < n + 2; ++i){
nx... |
1223 | G | Wooden Raft | Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have $n$ logs and the $i$-th log has length $a_i$.
The woo... | Let's iterate $y$ from $2$ to $A$, where $A = \max(a_i)$. And let's try to find the best answer for a fixed $y$ in $O(\frac{A}{y})$ time. How to do so? At first, we can quite easily calculate the total number of logs of length $y$ we can acquire (denote it as $cntY$): since all $a_i \in [ky, ky + y)$ give the same numb... | [
"binary search",
"math",
"number theory"
] | 3,200 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) (int)(a).size()
#define all(a) (a).begin(), (a).end()
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
int n;
v... |
1225 | A | Forgetting Things | Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation $a + 1 = b$ with positive integers $a$ and $b$, but Kolya forgot the numbers $a$ and $b$. He does, however, remember that the first (leftmost) digit of $a$ was $d_a$, and the first (leftmost) digit of $b$ was $d_b$... | The answer exists only if $d_a = d_b$, $d_b = d_a + 1$, or $d_a = 9$ and $d_b = 1$. Alternatively, one could simply check all $a$ up to 100 (or another reasoable bound). | [
"math"
] | 900 | null |
1225 | B1 | TV Subscriptions (Easy Version) | \textbf{The only difference between easy and hard versions is constraints.}
The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will b... | We are looking for a segment of length $d$ with the smallest number of distinct values. In small limitations one could just try all segments and count the number of distinct elements naively (for example, by sorting or with an std::set). | [
"implementation"
] | 1,000 | null |
1225 | B2 | TV Subscriptions (Hard Version) | \textbf{The only difference between easy and hard versions is constraints.}
The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will b... | In larger limitations we have to use two pointers to maintain the number of distinct elements between segments. We can store a map or an array that counts the number of occurences of each element, as well as the number of distinct elements (i.e. the number of non-zero entries in the map). Moving the segment to the righ... | [
"implementation",
"two pointers"
] | 1,300 | null |
1225 | C | p-binary | Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer $p$ (which may be positive, negative, or zero). To combine their tastes, they invented $p$-binary numbers of the form $2^x + p$, where $x$ is a \textbf{non-negative} integ... | Suppose we want to represent $n$ as the sum of $k$ $p$-binary numbers. We must have $n = \sum_{i = 1}^k (2^{x_i} + p)$ for a suitable choice of $x_1, \ldots, x_k$. Moving all $p$'s to the left-hand side, we must have $n - kp = \sum_{i=1}^k 2^{x_i}$. In particular, $n - kp$ has to be at least $k$. Consider the binary re... | [
"bitmasks",
"brute force",
"math"
] | 1,600 | null |
1225 | D | Power Products | You are given $n$ positive integers $a_1, \ldots, a_n$, and an integer $k \geq 2$. Count the number of pairs $i, j$ such that $1 \leq i < j \leq n$, and there exists an integer $x$ such that $a_i \cdot a_j = x^k$. | Suppose that $x \cdot y$ is a $k$-th power. The sufficient and necessary condition for that is: for any prime $p$, the total number of times it divides $x$ and $y$ must be divisible by $k$. Let us factorize each number $a_i = p_1^{b_1} \ldots p_m^{b_m}$, and associate the list of pairs $L_i ((p_1, b_1 \bmod k), \ldots,... | [
"hashing",
"math",
"number theory"
] | 1,800 | null |
1225 | E | Rock Is Push | You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$.
Some cells of the la... | Let us compute $R_{i, j}$ and $D_{i, j}$ - the number of legal ways to reach the goal assuming: we've arrived at the cell $(i, j)$; our next move is right/down respectively; our previous move (if there was a previous move) was not in the same direction. By definition, let us put $D_{n, m} = R_{n, m} = 1$. We can see th... | [
"binary search",
"dp"
] | 2,200 | null |
1225 | F | Tree Factory | Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.
The tree in question is a rooted tree with $n$ vertices labelled with distinct integers from $0$ to $n - 1$. The v... | Let's solve the problem backwards: given a tree, transform it into a bamboo with reverse operations. A reverse operation in this context looks like this: given a vertex $v$ and its two distinct children $u$ and $w$, make $w$ the parent of $u$. What's the lower bound on the number of operations we need to make? We can s... | [
"constructive algorithms",
"greedy",
"trees"
] | 2,500 | null |
1225 | G | To Make 1 | There are $n$ positive integers written on the blackboard. Also, a positive number $k \geq 2$ is chosen, and none of the numbers on the blackboard are divisible by $k$. In one operation, you can choose any two integers $x$ and $y$, erase them and write one extra number $f(x + y)$, where $f(x)$ is equal to $x$ if $x$ is... | An experienced eye will immediately spot a subset dynamic programming solution in roughly $O(3^n \sum a_i)$ time, but the time constraints will not allow this. What to do? Suppose there is a way to obtain 1 in the end. Looking at how many times each initial number $a_i$ gets divided by $k$ (including the divisions of t... | [
"bitmasks",
"constructive algorithms",
"dp",
"greedy",
"number theory"
] | 3,100 | null |
1227 | A | Math Problem | Your math teacher gave you the following problem:
There are $n$ segments on the $x$-axis, $[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$. The segment $[l; r]$ includes the bounds, i.e. it is a set of such $x$ that $l \le x \le r$. The length of the segment $[l; r]$ is equal to $r - l$.
Two segments $[a; b]$ and $[c; d]... | Find the left most right point for all segments, call it $r_{min}$. The right most left point for all segments, call it $l_{max}$. It's easy to see that the answer is $\max(0,l_{max} - r_{min})$. | [
"math"
] | 1,100 | null |
1227 | B | Box | Permutation $p$ is a sequence of integers $p=[p_1, p_2, \dots, p_n]$, consisting of $n$ distinct (unique) positive integers between $1$ and $n$, inclusive. For example, the following sequences are permutations: $[3, 4, 1, 2]$, $[1]$, $[1, 2]$. The following sequences are not permutations: $[0]$, $[1, 2, 1]$, $[2, 3]$, ... | Obviously, if $q_{i} \neq q_{i-1}$ then $p_{i} = q_{i}$. We assume $q_{0} = 0$. Other positions can be filled with the left numbers in increasing order. Then check whether the permutation is correct or not. | [
"constructive algorithms"
] | 1,200 | null |
1227 | C | Messy | You are fed up with your messy room, so you decided to clean it up.
Your room is a bracket sequence $s=s_{1}s_{2}\dots s_{n}$ of length $n$. Each character of this string is either an opening bracket '(' or a closing bracket ')'.
In one operation you can choose any consecutive substring of $s$ and reverse it. In othe... | It's easy to construct a valid bracket sequence, for example "()()()() ... (((...(())...))))". Now let the initial bracket sequence be $s$, the target one be $t$. For each position, if $s_{i} = t_{i}$ then we needn't do anything, otherwise find a position $j$ which $j > i$ and $s_{j} = t_{i}$ (it exists), and reverse t... | [
"constructive algorithms"
] | 1,700 | null |
1227 | D2 | Optimal Subsequences (Hard Version) | This is the harder version of the problem. In this version, $1 \le n, m \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removin... | Let's first solve the simplified version (Easy Version) without paying attention to the efficiency of the algorithm. It is clear that the sum of the elements of the optimal subsequence is equal to the sum of $k$ maximal elements of the sequence $a$. Let the smallest (the $k$-th) of $k$ maximal elements be $x$. Obviousl... | [
"data structures",
"greedy"
] | 1,800 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
int main()... |
1227 | E | Arson In Berland Forest | The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $n \times m$ rectangle map which represents the damaged part of the... | Let's note that if there is a possible configuration in which the forest burnt $T$ minutes then there is a configuration when the forest burnt $T - 1$ minutes. So we can binary search the answer. Now we need to check the existence of the configuration for a fixed time $T$. Let's find all trees that can be set on fire. ... | [
"binary search",
"graphs",
"shortest paths"
] | 2,200 | null |
1227 | F1 | Wrong Answer on test 233 (Easy Version) | \begin{quote}
Your program fails again. This time it gets "Wrong answer on test 233"
\end{quote}
.This is the easier version of the problem. In this version $1 \le n \le 2000$. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing $n$ one-choice-questions. Each of ... | First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \space \mod \space n + 1}$, the answer for this position will not affect $d$. Assume the... | [
"dp"
] | 2,200 | null |
1227 | F2 | Wrong Answer on test 233 (Hard Version) | \begin{quote}
Your program fails again. This time it gets "Wrong answer on test 233"
\end{quote}
.This is the harder version of the problem. In this version, $1 \le n \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
The problem is to ... | First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \space \mod \space n + 1}$, the answer for this position will not affect $d$. Assume the... | [
"combinatorics",
"math"
] | 2,400 | null |
1227 | G | Not Same | You are given an integer array $a_1, a_2, \dots, a_n$, where $a_i$ represents the number of blocks at the $i$-th position. It is guaranteed that $1 \le a_i \le n$.
In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a posit... | The solution can be inspired by the output format :) First of all, sort all numbers in decreasing order. Let them be $A_{1}, A_{2} \dots , A_{n}$. We will construct the answer column by column. Let us use a set of binary string to represent a series of operations. For example $\lbrace 10,10,10,11 \rbrace$ represent ope... | [
"constructive algorithms"
] | 2,600 | null |
1228 | A | Distinct Digits | You have two integers $l$ and $r$. Find an integer $x$ which satisfies the conditions below:
- $l \le x \le r$.
- All digits of $x$ are different.
If there are multiple answers, print any of them. | Let's see how to check if all digits of $x$ are different. Since there can be only $10$ different numbers($0$ to $9$) in single digit, you can count the occurrences of $10$ numbers by looking all digits of $x$. You can count all digits by using modulo $10$ or changing whole number to string. For example, if $x = 1217$,... | [
"brute force",
"implementation"
] | 800 | # Return if given number's digits are distinct.
def is_distinct(x):
return len(set(str(x))) == len(str(x))
L, R = [int(c) for c in input().split()]
found = False
for i in range(L, R+1):
if is_distinct(i):
found = True
print(i)
break
if not found: print(-1) |
1228 | B | Filling the Grid | Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions:
- $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty.
- $c_{j}$ is the number of conse... | You can see some observations below; $r$ and $c$ values reserves some cells to be full, and some cells to be empty. Because they have to satisfy number of consecutive full cells in their row/column. If some cell is reserved to be full by some values and reserved to be empty by some other values, then it is impossible t... | [
"implementation",
"math"
] | 1,400 | # Get input
h, w = [int(z) for z in input().split()]
r = [int(z) for z in input().split()]
c = [int(z) for z in input().split()]
mod = 10**9 + 7
# Make grid
grid = [['?' for col in range(w+1)] for row in range(h+1)]
def try_set(row, col, target):
if grid[row][col] == '?':
grid[row][col] = target
elif ... |
1228 | C | Primes and Multiplication | Let's introduce some definitions that will be needed later.
Let $prime(x)$ be the set of prime divisors of $x$. For example, $prime(140) = \{ 2, 5, 7 \}$, $prime(169) = \{ 13 \}$.
Let $g(x, p)$ be the maximum possible integer $p^k$ where $k$ is an integer such that $x$ is divisible by $p^k$. For example:
- $g(45, 3)... | Let's say $h(x, p) = \log_{p} g(x, p)$, then $h(x, p) + h(y, p) = h(x y, p)$. Because if we describe $x = p^{h(x, p)} q_{x}$ and $y = p^{h(y, p)} q_{y}$, then $x y = p^{h(x, p) + h(y, p)} q_{x} q_{y}$. Now let's go to the main step; $\begin{aligned} \prod_{i=1}^{n} f(x, i) &= \prod_{i=1}^{n} \prod_{p \in prime(x)} g(i,... | [
"math",
"number theory"
] | 1,700 | # Prime factorization
def prime_factorization(x):
answer = []
i = 2
while i*i <= x:
if x%i == 0:
answer.append(i)
while x%i == 0: x //= i
i += 1
if x > 1: answer.append(x)
return answer
# Main
def main(X: int, N: int):
answer = 1
mod = 10**9 + 7
... |
1228 | D | Complete Tripartite | You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let... | You can make answer by following these steps; If two vertices $u_{1}$ and $u_{2}$ are in same vertex set, there should be no edge between them. Otherwise, there should be edge between them. If you choose any $u$ as first vertex of specific vertex set, then you can simply add all vertices which are not directly connecte... | [
"brute force",
"constructive algorithms",
"graphs",
"hashing",
"implementation"
] | 1,900 | // Standard libraries
#include <stdio.h>
#include <vector>
#include <set>
// Main
int main(int argc, char **argv){
#ifdef __McDic__ // Local testing I/O
freopen("VScode/IO/input.txt", "r", stdin);
freopen("VScode/IO/output.txt", "w", stdout);
#endif
// Get input
int v, e; scanf("%d %d", &v, &e);
... |
1228 | E | Another Filling the Grid | You have $n \times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below.
- All numbers in the grid should be between $1$ and $k$ inclusive.
- Minimum number of the $i$-th row is $1$ ($1 \le i \le n$).
- Minimum number of the $j$-th column is $1$ ($1 \le j \le n$).
Find ... | $O(n^{3})$ solution:Let $f(r, c)$ to be the number of filling grids of $r$ rows, $c$ incomplete columns, and $n-c$ complete columns. Incomplete columns means which doesn't contain $1$ in already filled part, and complete columns means opposite. Now you can see that the formula can be described as below; $f(r, 0) = (k^{... | [
"combinatorics",
"dp",
"math"
] | 2,300 | // Standard libraries
#include <stdio.h>
#include <vector>
// Typedef
typedef long long int lld;
const lld mod = 1000 * 1000 * 1000 + 7;
// Clean
lld clean(lld x){
x %= mod;
if(x<0) x += mod;
return x;
}
// x^n
lld power(lld x, lld n){
if(n==0) return 1;
x = clean(x);
lld half = power(x, n... |
1228 | F | One Node is Gone | You have an integer $n$. Let's define following tree generation as McDic's generation:
- Make a complete and full binary tree of $2^{n} - 1$ vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exact... | Let me suggest this observation; Root of generated tree should be one of middle of diameter. Because only $1$ node is deleted from complete full binary tree. So there are $3$ valid cases; The removed node is child of root. In this case, there are $2$ answers($2$ center nodes), diameter is decreased by $1$ (odd), and tr... | [
"constructive algorithms",
"implementation",
"trees"
] | 2,500 | // Standard libraries
#include <stdio.h>
#include <vector>
#include <utility>
// Max2
int max2(int a, int b){return a>b ? a:b;}
// Graph attributes
int v;
std::vector<std::vector<int>> edges;
// DFS from given vertex with avoidance. Return [(previous, distance), ...]
std::vector<std::pair<int, int>> DFS(int star... |
1230 | A | Dawid and Bags of Candies | Dawid has four bags of candies. The $i$-th of them contains $a_i$ candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?
Note, that you can't keep bags for yourself or ... | Let's firstly sort all the bags in non-decreasing order of capacities. As the order of friends doesn't matter, it turns out that one of them should take only the biggest bag or the biggest and the smallest bag. It's easy to check if any of these possibilities works. | [
"brute force",
"implementation"
] | 800 | null |
1230 | B | Ania and Minimizing | Ania has a large integer $S$. Its decimal representation has length $n$ and doesn't contain any leading zeroes. Ania is allowed to change at most $k$ digits of $S$. She wants to do it in such a way that $S$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? | There are a couple of corner cases: if $k=0$, we cannot change $S$. Otherwise, if $n=1$, we can change $S$ into $0$. Now assume that $n \geq 2$ and $k \geq 1$. A simple greedy approach works here: we can iterate over the digits from left to right and change them to the lowest possible digits as long as we still can cha... | [
"greedy",
"implementation"
] | 1,000 | null |
1234 | A | Equalize Prices Again | You are both a shop keeper and a shop assistant at a small nearby shop. You have $n$ goods, the $i$-th good costs $a_i$ coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $n$ goods you... | In this problem, we need to find the minimum possible $price$ such that $price \cdot n \ge sum$, where $sum$ is the sum of all $a_i$. $price$ equals to $\lceil \frac{sum}{n} \rceil$, where $\lceil \frac{x}{y} \rceil$ is $x$ divided by $y$ rounded up. | [
"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;
int sum = 0;
for (int j = 0; j < n; ++j) {
int x;
cin >> x;
sum += x;
}
co... |
1234 | B1 | Social Network (easy version) | \textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed convers... | The solution to this problem is just the implementation of what is written in the problem statement. Let's carry the array $q$ which shows the current smartphone screen. When we receive the new message from the friend with ID $id_i$, let's do the following sequence of moves: Firstly, let's try to find him on the screen... | [
"implementation"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<int> ids;
for (int i = 0; i < n; ++i) {
int id;
cin >> id;
if (find(ids.begin(), ids.end(), id) == ids.end()) {
if (i... |
1234 | B2 | Social Network (hard version) | \textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed convers... | The idea of this solution is the same as in the easy version, but now we need to do the same sequence of moves faster. We can notice that the smartphone screen works as a queue, so let store it as a queue! When the new message appears, we have to check if the friend with this ID is in the queue already, but we need to ... | [
"data structures",
"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 n, k;
cin >> n >> k;
queue<int> q;
set<int> vals;
for (int i = 0; i < n; ++i) {
int id;
cin >> id;
if (!vals.count(id)) {
if (int(q.size()) >=... |
1234 | C | Pipes | You are given a system of pipes. It consists of two rows, each row consists of $n$ pipes. The top left pipe has the coordinates $(1, 1)$ and the bottom right — $(2, n)$.
There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:
\begin{center}
Typ... | Let's see how the water can flow when it meets the pipe of type $1$ or $2$ and in the other case. When the water meets the pipe of type $1$ or $2$ we cannot do anything but let it flow to the right of the current cell. Otherwise (if the current pipe is curved) then there are two cases: if the pipe on the same position ... | [
"dp",
"implementation"
] | 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;
for (int i = 0; i < q; ++i) {
int n;
string s[2];
cin >> n >> s[0] >> s[1];
int row = 0;
int pos = 0;
for (pos = 0; pos < n; ++pos... |
1234 | D | Distinct Characters Queries | You are given a string $s$ consisting of lowercase Latin letters and $q$ queries for this string.
Recall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \dots s_r$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types o... | Let's store for each letter all positions in which it appears in some data structure. We need such a data structure that can add, remove and find the next element greater than or equal to our element, fast enough. Suddenly, this data structure is std::set again (in C++). When we meet the first type query, let's just mo... | [
"data structures"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
string s;
cin >> s;
vector<set<int>> poss(26);
for (int i = 0; i < int(s.size()); ++i) {
poss[s[i] - 'a'].insert(i);
}
int q;
cin >> q;
for (int i = 0... |
1234 | E | Special Permutations | Let's define $p_i(n)$ as the following permutation: $[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$. This means that the $i$-th permutation is \textbf{almost identity} (i.e. which maps every element to itself) permutation but the element $i$ is on the first position. Examples:
- $p_1(4) = [1, 2, 3, 4]$;
- $p_2(4) = [2, 1, ... | Let's calculate the answer for the first permutation $p_1(n)$ naively in $O(m)$. Then let's recalculate the answer somehow and then maybe prove that it works in linear time. Which summands will change when we try to recalculate the function $f(p_i(n))$ using $f(p_1(n))$? First of all, let's notice that each pair of adj... | [
"math"
] | 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 n, m;
cin >> n >> m;
vector<int> a(m);
for (int i = 0; i < m; ++i) {
cin >> a[i];
--a[i];
}
vector<long long> res(n);
for (int j = 0; j < m - 1; ... |
1234 | F | Yet Another Substring Reverse | You are given a string $s$ consisting only of first $20$ lowercase Latin letters ('a', 'b', ..., 't').
Recall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \dots s_r$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
You can perform ... | First of all, I wanted to offer you one little challenge: I found a solution that I can't break (and I don't sure if it can be broken) and I will be so happy if anyone will give me countertest which will break it. You can see its code below. Let's notice that we can reduce our problem to the following: find two substri... | [
"bitmasks",
"dp"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int tt = clock();
string s;
cin >> s;
vector<int> dp(1 << 20);
vector<int> masks;
for (int i = 0; i < int(s.size()); ++i) {
vector<bool> used(20);
in... |
1236 | A | Stones | Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones.
Each time she can do one of two operations:
- take one stone from the first heap and two stones from the second hea... | We can use many ways to solve the problem. If you just enumerate how many operations of the first and the second type, it will also pass. Of course there is a greedy solution. We make the second operation as much as possible, and then use the first operation. It takes $O(1)$ time. | [
"brute force",
"greedy",
"math"
] | 800 | null |
1236 | B | Alice and the List of Presents | Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different ... | The answer is $(2^m-1)^n$. If we consider each present, it may contain only in the first box, in the second ... both in the first and second box, in the first and the third one ... in the first,the second and the third one ... There are $2^m-1$ ways. There are $n$ presents, so there are $(2^m-1)^n$ ways in total accord... | [
"combinatorics",
"math"
] | 1,500 | null |
1236 | C | Labs | In order to do some research, $n^2$ labs are built on different heights of a mountain. Let's enumerate them with integers from $1$ to $n^2$, such that the lab with the number $1$ is at the lowest place, the lab with the number $2$ is at the second-lowest place, $\ldots$, the lab with the number $n^2$ is at the highest ... | The maximum number is $\lfloor\frac{n^2}{2}\rfloor$. It can be proved we cannot find a larger answer. There is $n^2$ pipes between any two groups. So the valid pairs of the minimum of them does not exceed $\lfloor\frac{n^2}{2}\rfloor$. Then we try to find a way to achieve the maximum. We find if we put the first lab in... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,300 | null |
1236 | D | Alice and the Doll | Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with $n$ rows and $m$ columns. There are $k$ obstacles, the $i$-th of them is on the cell $(x_i, y_i)$, which means the cell in the intersection of the $x_i$-th row and the $y_i$-th column.
... | Consider just simulate the whole process. We walk straight, and then turn right when meet the obstacle or the border of the grid. Then we can use set to make it faster. We can check along the direction, which is the first obstacle. To check whether any cell is covered, we can calculate the number of cells we walk acros... | [
"brute force",
"data structures",
"greedy",
"implementation"
] | 2,300 | null |
1236 | E | Alice and the Unfair Game | Alice is playing a game with her good friend, Marisa.
There are $n$ boxes arranged in a line, numbered with integers from $1$ to $n$ from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have $m$ chances to guess where the doll is. If Alice will correctly guess the number of box, where doll ... | First there is a conclusion: each start point will be able to reach a consecutive segment of end points except for n=1. It's easy to prove, when a place is banned, we can make a move to make it reachable again. So with the conclusion then we can solve the problem. First we will come up with a greedy algorithm. We can m... | [
"binary search",
"data structures",
"dp",
"dsu"
] | 2,500 | null |
1236 | F | Alice and the Cactus | Alice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them.
A cactus is a connected undirected graph. No edge of this graph lies on more than one simple cycle. Let's call a sequence of different nodes of ... | First we consider how to calculate $E(X)$. The number of connected components equals to the number of nodes minus the number of edges and then add the number of rings in it. So we can calculate the possibility of removing one node, one edge or one single ring. Then we can split the variance, it is equals to $E(X^2)-2*E... | [
"dfs and similar",
"graphs",
"math",
"probabilities"
] | 3,000 | null |
1237 | A | Balanced Rating Changes | Another Codeforces Round has just finished! It has gathered $n$ participants, and according to the results, the expected rating change of participant $i$ is $a_i$. These rating changes are perfectly balanced — their sum is equal to $0$.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. ... | Let $b_i = \frac{a_i}{2} + \delta_i$. It follows that if $a_i$ is even, then $\delta_i = 0$, and if $a_i$ is odd, then either $\delta_i = \frac{1}{2}$ or $\delta_i = -\frac{1}{2}$. At the same time, the sum of $b_i$ is equal to the sum of $\delta_i$, as the sum of $a_i$ is $0$. Thus, as the sum of $b_i$ must be equal t... | [
"implementation",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int flag = 1;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
if (x % 2 == 0) {
cout << x / 2 << '\n';
} else {
cout << (x + flag) / 2 << '\n';
flag *= -1;
... |
1237 | B | Balanced Tunnel | Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.
A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tun... | This problem can be approached in several ways, here is one of them. Let's say that cars exit the tunnel at time moments $1, 2, \ldots, n$, and let $c_i$ be time when car $a_i$ exited the tunnel. For instance, in the first example we had $a = \langle 3, 5, 2, 1, 4 \rangle$ and $b = \langle 4, 3, 2, 5, 1 \rangle$. Then,... | [
"data structures",
"sortings",
"two pointers"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n), b(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
--a[i];
}
for (int i = 0; i < n; i++) {
cin >> b[i];
--b[i];
}
vector<int> pos(n);
for (int i = ... |
1237 | C1 | Balanced Removals (Easier) | This is an easier version of the problem. In this version, $n \le 2000$.
There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.
You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps.... | Pick any two points $i$ and $j$, let's say that this is our candidate pair $(i, j)$ for removal. Loop over all other points. If some point $k$ lies inside the bounding box of $i$ and $j$, change our candidate pair to $(i, k)$. Note that the bounding box of $i$ and $k$ lies inside the bounding box of $i$ and $j$, so we ... | [
"constructive algorithms",
"geometry",
"greedy"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<pair<int, int>, pair<int, int> > ii;
int main(){
int n;
cin >> n;
vector<ii> v(n);
for (int i = 0; i < n; i++){
cin >> v[i].first.first >> v[i].first.second >> v[i].second.first;
v[i].second.second = i... |
1237 | C2 | Balanced Removals (Harder) | This is a harder version of the problem. In this version, $n \le 50\,000$.
There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.
You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snap... | Consider a one-dimensional version of the problem where $n$ is not necessarily even. We can sort all points by their $x$-coordinate and remove them in pairs. This way, we'll leave at most one point unremoved. Now, consider a two-dimensional version of the problem where $n$ is not necessarily even. For each $y$, conside... | [
"binary search",
"constructive algorithms",
"divide and conquer",
"greedy",
"implementation",
"sortings"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int D = 3;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<vector<int>> p(n, vector<int>(D));
for (int i = 0; i < n; i++) {
for (int j = 0; j < D; j++) {
cin >> p[i][j];
}
}
auto Solve = [&](auto& Self, ve... |
1237 | D | Balanced Playlist | Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $n$ tracks numbered from $1$ to $n$. The playlist is automatic and cyclic: whenever track $i$ finishes playing, track $i+1$ starts playing automatically; after track $n$ goes track $1$.
For eac... | This problem allowed a lot of approaches. First, to determine if the answer is all $-1$, compare half of maximum $x_i$ and minimum $x_i$. Second, note that during the first $n$ tracks, we'll listen to the track with maximum $x_i$, and during the next $n$ tracks, we'll stop at the track with minimum $x_i$. Thus, to pret... | [
"binary search",
"data structures",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(3 * n);
for (int i = 0; i < n; i++) {
cin >> a[i];
a[i + n] = a[i + 2 * n] = a[i];
}
vector<int> ans(3 * n);
vector<int> st_max;
vector<int> st_min;
for (int... |
1237 | E | Balanced Binary Search Trees | Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree.
The depth of a vertex is the number o... | Consider perfectly balanced striped BSTs of some maximum depth $d$. Note that both the left and the right subtree of the root must be perfectly balanced striped BSTs of maximum depth $d-1$. Also note that the parity of the root must be equal to the parity of $n$, as $n$ lies on the rightmost branch of the tree; thus, t... | [
"dp",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int x = 1;
while (x <= n) {
if (n == x || n == x + 1) {
cout << 1 << '\n';
return 0;
}
if (x % 2 == 0) {
x = x + 1 + x;
} else {
x = (x + 1) + 1 + x;... |
1237 | F | Balanced Domino Placements | Consider a square grid with $h$ rows and $w$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.
Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells cover... | Suppose we're going to place $d_h$ extra horizontal dominoes and $d_v$ extra vertical ones. Consider all rows of the grid, and mark them with $0$ if it's empty and with $1$ if it already has a covered cell. Do the same for columns. Now, let's find the number of ways $R$ to pick $d_h$ rows marked with $0$, and also $d_v... | [
"combinatorics",
"dp"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 998244353;
const int MAX = 3610;
ll dp1[MAX][MAX], dp2[MAX][MAX];
int has1[MAX], has2[MAX];
ll fac[MAX], c[MAX][MAX];
int n, m, k;
void make(int n){
dp1[0][0] = 1;
for (int i = 1; i <= n; i++){
for (int j = 0; j <= m; ... |
1237 | G | Balanced Distribution | There are $n$ friends living on a circular street. The friends and their houses are numbered clockwise from $0$ to $n-1$.
Initially person $i$ has $a_i$ stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones.
The only way to change ... | Let $A$ be the average of $a_i$, and let $p_i$ be the sum of $a_0, a_1, \ldots, a_i$ minus $A$ times $i+1$. Consider a pair of friends $i$ and $(i+1) \bmod n$ that never attend the same meeting. Then we can make a "cut" between them to transform the circle into a line. Consider some other pair of friends $j$ and $(j+1)... | [
"data structures",
"dp",
"greedy"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int... |
1237 | H | Balanced Reversals | You have two strings $a$ and $b$ of equal even length $n$ consisting of characters 0 and 1.
We're in the endgame now. To finally make the universe perfectly balanced, you need to make strings $a$ and $b$ equal.
In one step, you can choose any prefix of $a$ of even length and reverse it. Formally, if $a = a_1 a_2 \ldo... | Unfortunately, solutions used by most participant are different from what I expected. Here is the intended solution that works in exactly $n+1$ reversals. Let's form string $b$ from right to left at the front of string $a$. For each $i = 2, 4, 6, \ldots, n$, we'll make some reversals so that $a[1..i] = b[n-i+1..n]$. Fo... | [
"constructive algorithms"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int... |
1238 | A | Prime Subtraction | You are given two integers $x$ and $y$ (it is guaranteed that $x > y$). You may choose any prime integer $p$ and subtract it any number of times from $x$. Is it possible to make $x$ equal to $y$?
Recall that a prime number is a positive integer that has exactly two positive divisors: $1$ and this integer itself. The s... | Let's denote the difference between $x$ and $y$ as $z$ ($z = x - y$). Then, if $z$ has a prime divisor $p$, we can subtract $p$ from $x$ $\frac{z}{p}$ times. The only positive integer that doesn't have any prime divisors is $1$. So, the answer is NO if and only if $x - y = 1$. | [
"math",
"number theory"
] | 900 | t = int(input())
for i in range(t):
x, y = map(int, input().split())
if(x - y > 1):
print('YES')
else:
print('NO') |
1238 | B | Kill `Em All | Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.
The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'... | Notice the following fact: it's never optimal to fire a missile at such a position that there are monsters to the right of it. That suggests the next solution: sort the positions, leave only the unique ones and process to shoot at the rightmost alive monster until every monster is dead. Position of some monster after $... | [
"greedy",
"sortings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int N = 100 * 1000 + 13;
int n, r;
int a[N];
void solve() {
scanf("%d%d", &n, &r);
forn(i, n) scanf("%d", &a[i]);
sort(a, a + n);
n = unique(a, a + n) - a;
int ans = 0;
for (int i = n - 1; i >= 0; i--)... |
1238 | C | Standard Free2play | You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $h$, and there is a moving platform on each height $x$ from $1$ to $h$.
Each platform is either hidden inside the cliff or moved out. At first, there are $n$ moved out... | You are given the input data in compressed format, let's decompress it in binary string, where the $i$-th character is 0 if the $i$-th platform is hidden and 1 otherwise. For, example, the third query is 101110011. Let's look how our string changes: if we had ...01... then after pulling the lever it becomes ...10... an... | [
"dp",
"greedy",
"math"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
const int INF = int(1e9);
int h, n;
vector<int> p;
inline bool read() {
if(!(cin >> h >> n))
return false;
p.resize(n);
fore(i, 0, n)
cin >>... |
1238 | D | AB-string | The string $t_1t_2 \dots t_k$ is good if each letter of this string belongs to at least one palindrome of length \textbf{greater} than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here a... | Instead of counting the number of good substrings, let's count the number of bad substrings $cntBad$, then number of good substrings is equal to $\frac{n(n+1)}{2} - cntBad$. Let's call a character $t_i$ in string $t_1t_2 \dots t_k$ is bad if there is no such palindrome $t_lt_{l+1} \dots t_r$ that $l \le i \le r$. Any c... | [
"binary search",
"combinatorics",
"dp",
"strings"
] | 1,900 | n = int(input())
s = input()
res = n * (n - 1) // 2
for x in range(2):
cur = 1
for i in range(1, n):
if s[i] == s[i - 1]:
cur += 1
else:
res -= cur - x
cur = 1
s = s[::-1]
print(res) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.