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 ⌀ |
|---|---|---|---|---|---|---|---|
1469 | D | Ceil Divisions | You have an array $a_1, a_2, \dots, a_n$ where $a_i = i$.
In one step, you can choose two indices $x$ and $y$ ($x \neq y$) and set $a_x = \left\lceil \frac{a_x}{a_y} \right\rceil$ (ceiling function).
Your goal is to make array $a$ consist of $n - 1$ ones and $1$ two in no more than $n + 5$ steps. Note that you don't ... | There are many different approaches. We will describe a pretty optimal one. Let's solve the problem recursively. Let's say we need to process segment $[1, x]$. If $x = 2$, we don't need to do anything. Otherwise, $x > 2$. Let's find the minimum $y$ such that $y \ge \left\lceil \frac{x}{y} \right\rceil$. The chosen $y$ ... | [
"brute force",
"constructive algorithms",
"math",
"number theory"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
const ld EPS = 1e-9;
... |
1469 | E | A Bit Similar | Let's call two strings $a$ and $b$ (both of length $k$) a bit similar if they have the same character in some position, i. e. there exists at least one $i \in [1, k]$ such that $a_i = b_i$.
You are given a binary string $s$ of length $n$ (a string of $n$ characters 0 and/or 1) and an integer $k$. Let's denote the stri... | Let's denote $z$ as the number of substrings of $s$ having length exactly $k$ (so, $z = n - k + 1$). The first and crucial observation is that if $2^k > z$, then the answer always exists. Each of $z$ substrings forbids one of the strings from being the answer (a string is forbidden if every each character differs from ... | [
"bitmasks",
"brute force",
"hashing",
"string suffix structures",
"strings",
"two pointers"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
const int N = 1000043;
int q;
char buf[N];
int n, k;
int ceilLog(int x)
{
int y = 0;
while((1 << y) < x)
y++;
return y;
}
int main()
{
scanf("%d", &q);
for(int i = 0; i < q; i++)
{
scanf("%d %d", &n, &k);
s... |
1469 | F | Power Sockets | // We decided to drop the legend about the power sockets but feel free to come up with your own :^)
Define a chain:
- a chain of length $1$ is a single vertex;
- a chain of length $x$ is a chain of length $x-1$ with a new vertex connected to the end of it with a single edge.
You are given $n$ chains of lengths $l_1,... | At first, let's realize that the tree structure doesn't matter that much. What we actually need is the array $cnt_i$ such that it stores the number of white vertices on depth $i$. Initially, $cnt_0=1$ and all other are zero. If you take a chain and attach it to some vertex on depth $d$, then the number of vertices on d... | [
"binary search",
"data structures",
"greedy"
] | 2,600 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int INF = 1e9;
int n, k, nn;
vector<long long> t, ps;
void push(int v, int l, int r){
if (l < r - 1){
ps[v * 2] += ps[v];
ps[v * 2 + 1] += ps[v];
}
t[v] += ps[v] * (r - l);
ps[v] = 0;
}
void upd(int v,... |
1470 | A | Strange Birthday Party | Petya organized a strange birthday party. He invited $n$ friends and assigned an integer $k_i$ to the $i$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $m$ unique presents available, the $j$-th present costs $c_j$ dollars ($1 \le c_1 \le c_2 \le \ldots \le c_m$). It's ... | Let's note that it is beneficial to give cheaper gifts to people with a larger $k_i$ value. Suppose that in the optimal answer a pair of people $A$ and $B$, such that $k_A \ge k_B$ get gifts with values $a \ge b$. Then we can give a gift $b$ to a person $A$ and to a person $B$ give a gift $a$ or $min(a, c_{k_B})$ dolla... | [
"binary search",
"dp",
"greedy",
"sortings",
"two pointers"
] | 1,300 | null |
1470 | B | Strange Definition | Let us call two integers $x$ and $y$ adjacent if $\frac{lcm(x, y)}{gcd(x, y)}$ is a perfect square. For example, $3$ and $12$ are adjacent, but $6$ and $9$ are not.
Here $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$, and $lcm(x, y)$ denotes the least common multiple (LCM) of integers $x... | It is well known that $lcm(x, y)=\frac{x \cdot y}{gcd(x, y)}$, and it immediately follows that $\frac{lcm(x, y)}{gcd(x, y)}$ $=$ $\frac{x \cdot y}{gcd(x, y)^2}$, which means that numbers $x$ and $y$ are adjacent if and only if $x \cdot y$ is a perfect square. Let $alpha_x$ be the maximum possible integer such that $p^{... | [
"bitmasks",
"graphs",
"hashing",
"math",
"number theory"
] | 1,900 | null |
1470 | C | Strange Shuffle | This is an interactive problem.
$n$ people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from $1$ to $n$, so that players $i$ and $i+1$ are neighbours (as well as players $1$ and $n$). Each of them has exactly $k$ cards, where $k$ is \textbf{even}. The left neighbour of a player $... | Short version: note that, during the first $\frac{n}{2}$ iterations the number of people with more than $k$ cards, increases. Let's find at least one such person. To do this, let's wait for $\sqrt{n}$ iterations. After this there is always a continuous segment of length $\sqrt{n}$ with elements $>k$. To find it, we can... | [
"binary search",
"brute force",
"constructive algorithms",
"interactive"
] | 2,500 | null |
1470 | D | Strange Housing | Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold:
- All passages between two houses will be closed, if there are n... | One can prove that the answer always exists if the graph is connected, and the algorithm proves it. Let us paint all vertices with black and white colors. Let us pick any vertex and paint it black, and let us paint all its neighbours with white. Then let's pick any uncoloured vertex that is connected to a white one, pa... | [
"constructive algorithms",
"dfs and similar",
"graph matchings",
"graphs",
"greedy"
] | 2,200 | null |
1470 | E | Strange Permutation | Alice had a permutation $p_1, p_2, \ldots, p_n$. Unfortunately, the permutation looked very boring, so she decided to change it and choose some \textbf{non-overlapping} subranges of this permutation and reverse them. The cost of reversing a single subrange $[l, r]$ (elements from position $l$ to position $r$, inclusive... | Let call the cost of rotation of segment $[L, R]$ value $R - L$ coins. Let's calculate how many ways can we apply to the array of length $len$ with total cost less or equal to $c$. We can fix $len - 1$ bars between neighbouring elements of array. There is a bijection between ways to select $c$ of them and ways to apply... | [
"binary search",
"combinatorics",
"data structures",
"dp",
"graphs",
"implementation",
"two pointers"
] | 3,200 | null |
1470 | F | Strange Covering | You are given $n$ points on a plane.
Please find the minimum sum of areas of two axis-aligned rectangles, such that each point is contained in at least one of these rectangles.
Note that the chosen rectangles can be degenerate. Rectangle contains all the points that lie inside it or on its boundary. | It is clear that there are only 3 structurally different ways to pick two rectangles optimally: Two rectangles do not intersect: In this case one can iterate over all horizontal / vertical lines, separating those rectangles, find the extremal points in both halfplanes, and pick the rectangles with corners in the extrem... | [
"divide and conquer"
] | 3,500 | null |
1471 | A | Strange Partition | You are given an array $a$ of length $n$, and an integer $x$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $[3, 6, 9]$, in a single operation one can replace the last two elements b... | Note that, $\left\lceil \frac{a + b}{x} \right\rceil \leq \left\lceil \frac{a}{x} \right\rceil + \left\lceil \frac{b}{x} \right\rceil$. It means that the maximal sum is attained if we do not apply any operations, and the minimal one is attained if we replace all the element with a single one, equal to the sum of all el... | [
"greedy",
"math",
"number theory"
] | 900 | null |
1471 | B | Strange List | You have given an array $a$ of length $n$ and an integer $x$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $q$. If $q$ is divisible by $x$, the robot adds $x$ copies of the integer $\frac{q}{x}$ to the end of the array, and moves on to... | Solution 1. Let's represent each element $a_{i}$ as $x^{b_{i}} \cdot c_{i}$, where $b_{i}$ is the maximal possible. Let's take minimum over all values $b_{i}$, and let's assume it's attained at position $j$. The robot will add each element to the array $b_{j}$ times (element at position $j$ will be the first one, which... | [
"brute force",
"greedy",
"implementation",
"math"
] | 1,100 | null |
1472 | A | Cards for Friends | For the New Year, Polycarp decided to send postcards to all his $n$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $w \times h$, which can be cut into pieces.
Polycarp can cut any sheet of paper $w \times h$ that he has in only two cases:
- If $w$ is even, th... | If we cut the sheet in width, we will reduce its width by half, without changing the height. Therefore, the width and height dimensions do not affect each other in any way. Let's calculate the maximum number of sheets that we can get by cutting. Let's say that initially this number is $1$. Let's cut the sheet in width.... | [
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int w, h, n;
cin >> w >> h >> n;
int res = 1;
while (w % 2 == 0) {
w /= 2;
res *= 2;
}
while (h % 2 == 0) {
h /= 2;
res *= 2;
}
cout << (res >= n ? "YES\n" : "NO\n");
}
int main() {
int t;
cin >> t;... |
1472 | B | Fair Division | Alice and Bob received $n$ candies from their parents. \textbf{Each candy weighs either 1 gram or 2 grams}. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.
Check if they can do that.
Note that candies \textbf{are no... | If the sum of all the weights is not divisible by two, then it is impossible to divide the candies between two people. If the sum is divisible, then let's count the number of candies with a weight of $1$ and $2$. Now, if we can find a way to collect half the sum with some candies, then these candies can be given to Ali... | [
"dp",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
int cnt1 = 0, cnt2 = 0;
for (int i = 0; i < n; i++) {
int c;
cin >> c;
if (c == 1) {
cnt1++;
} else {
cnt2++;
}
}
if ((cnt1 + 2 * cnt2) % 2 != 0) {
cout << "NO\n";
} el... |
1472 | C | Long Jumps | Polycarp found under the Christmas tree an array $a$ of $n$ elements and instructions for playing with it:
- At first, choose index $i$ ($1 \leq i \leq n$) — starting position in the array. Put the chip at the index $i$ (on the value $a_i$).
- While $i \leq n$, add $a_i$ to your score and move the chip $a_i$ positions... | Let $score(i)$ be the result of the game if we chose $i$ as the starting position. Let's look at some starting position $j$. After making a move from it, we will get $a[j]$ points and move to the position $j + a[j]$, continuing the same game. This means that by choosing the position $j$, we can assume that we will get ... | [
"dp",
"graphs"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
vector<int> dp(n);
for (int i = n - 1; i >= 0; i--) {
dp[i] = a[i];
int j = i + a[i];
if (j < n) {
dp[i] += dp[j];
}
}
cout << *max_element(dp.begi... |
1472 | D | Even-Odd Game | During their New Year holidays, Alice and Bob play the following game using an array $a$ of $n$ integers:
- Players take turns, Alice moves first.
- Each turn a player chooses any element and removes it from the array.
- If Alice chooses \textbf{even value}, then she adds it to her score. If the chosen value is odd, A... | Let's look at an analogy for this game. If Alice takes an even number $x$, she adds $x$ points to the global result, otherwise $0$; If Bob takes an odd number $x$, he adds $-x$ points to the global result, otherwise $0$; Alice wants to maximize the global result and Bob wants to minimize it. Obviously, this game is com... | [
"dp",
"games",
"greedy",
"sortings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
vector<int> v(n);
for (int &e : v) {
cin >> e;
}
sort(v.rbegin(), v.rend());
ll ans = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
if (v[i] % 2 == 0) {
ans += v[i];
}
... |
1472 | E | Correct Placement | Polycarp has invited $n$ friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.
Each friend is characterized by two values $h_i$ (their height) and $w_i$ (their width). On the photo the $i$-th friend will occupy a rectan... | Let's sort all people by their height in descending order. Now let's go through all the people and look for the position of the person in the sorted array, the height of which is strictly less than ours (for example, by binary search). Obviously, only those people who are in the sorted array later than the found person... | [
"binary search",
"data structures",
"dp",
"sortings",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
struct man {
int h, w, id;
};
bool operator<(const man &a, const man &b) {
return tie(a.h, a.w, a.id) < tie(b.h, b.w, b.id);
}
struct my_min {
pii mn1, mn2;
};
vector<pair<int, my_min>> createPrefMins(const vector<man>& a) {
vector<p... |
1472 | F | New Year's Puzzle | Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size $2 \times n$, some cells of it are blocked. Y... | If the first column is empty, we can always cover it with a vertical tile: if the next column is also empty, then we will have to put either two vertical or two horizontal tiles, but they are obtained from each other by rotating; if the next column contains at least one blocked cell, then we have no other options but t... | [
"brute force",
"dp",
"graph matchings",
"greedy",
"sortings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, m;
cin >> n >> m;
map<int, int> v;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
v[y] |= (1 << (x - 1));
}
const int FULL = 3;
v[2e9] = FULL;
int hasLast = 0, lastColor = 0;
for (auto[x, ma... |
1472 | G | Moving to the Capital | There are $n$ cities in Berland. The city numbered $1$ is the capital. Some pairs of cities are connected by a \textbf{one-way} road of length 1.
Before the trip, Polycarp for each city found out the value of $d_i$ — the shortest distance from the capital (the $1$-st city) to the $i$-th city.
Polycarp begins his jour... | Find the distances to all vertices and construct a new graph that has only edges that goes from a vertex with a smaller distance to a vertex with a larger distance. Such a graph cannot contain cycles. Next, you need to run a dynamic programming similar to finding bridges in an undirected graph. First, we write the mini... | [
"dfs and similar",
"dp",
"graphs",
"shortest paths"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
vector<int> calcDist(vector<vector<int>> const &g) {
vector<int> dist(g.size(), -1);
dist[1] = 0;
queue<int> pq;
pq.push(1);
while (!pq.empty()) {
int u = pq.front();
pq.pop();
for (int v : g[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] ... |
1473 | A | Replacing Elements | You have an array $a_1, a_2, \dots, a_n$. All $a_i$ are positive integers.
In one step you can choose three distinct indices $i$, $j$, and $k$ ($i \neq j$; $i \neq k$; $j \neq k$) and assign the sum of $a_j$ and $a_k$ to $a_i$, i. e. make $a_i = a_j + a_k$.
Can you make all $a_i$ lower or equal to $d$ using the opera... | Let's note that since all $a_i$ are positive, any $a_i + a_j > \max(a_i, a_j)$. It means that we can't make the first and second minimums lower than they already are: suppose the first and second minimums are $mn_1$ and $mn_2$, if we choose any other element to replace, we can't make it less than $mn_1 + mn_2$ and if w... | [
"greedy",
"implementation",
"math",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tc;
cin >> tc;
while (tc--) {
int n, d;
cin >> n >> d;
vector<int> a(n);
for (int& x : a) cin >> x;
sort(a.begin(), a.end());
cout << (a.back() <= d || a[0] + a[1] <= d ? "YES" : "NO") << endl;
}
} |
1473 | B | String LCM | Let's define a multiplication operation between a string $a$ and a positive integer $x$: $a \cdot x$ is the string that is a result of writing $x$ copies of $a$ one after another. For example, "abc" $\cdot~2~=$ "abcabc", "a" $\cdot~5~=$ "aaaaa".
A string $a$ is divisible by another string $b$ if there exists an intege... | We should notice that if some string $x$ is a multiple of string $y$, then $|x|$ is a multiple of $|y|$. This fact leads us to the conclusion that $|LCM(s, t)|$ should be a common multiple of $|s|$ and $|t|$. Since we want to minimize the length of the string $LCM(s, t)$, then its length is $LCM(|s|, |t|)$. So we have ... | [
"brute force",
"math",
"number theory",
"strings"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
auto mul = [](string s, int k) -> string {
string res = "";
while (k--) res += s;
return res;
};
int tc;
cin >> tc;
while (tc--) {
string s, t;
cin >> s >> t;
int n = s.length(), m = t.length();
int g = __gcd(n, m);
... |
1473 | C | No More Inversions | You have a sequence $a$ with $n$ elements $1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$ ($k \le n < 2k$).
Let's call as inversion in $a$ a pair of indices $i < j$ such that $a[i] > a[j]$.
Suppose, you have some permutation $p$ of size $k$ and you build a sequence $b$ of size $n$ in the following manner... | At first, let's look at sequence $s$: $s_1, s_2, \dots, s_{p - 1}, s_{p}, s_{p - 1}, \dots s_2, s_1$. Let's prove that the number of inversions in $s$ is the same regardless of what $s_i$ are (the only condition is that $s_i$ should be distinct). Let's group all elements $s_i$ by their value - there will be $1$ or $2$ ... | [
"constructive algorithms",
"math"
] | 1,500 | fun main() {
repeat(readLine()!!.toInt()) {
val (n, k) = readLine()!!.split(' ').map { it.toInt() }
for (i in 1 until (k - (n - k)))
print("$i ")
for (i in k downTo (k - (n - k)))
print("$i ")
println("")
}
} |
1473 | D | Program | You are given a program that consists of $n$ instructions. Initially a single variable $x$ is assigned to $0$. Afterwards, the instructions are of two types:
- increase $x$ by $1$;
- decrease $x$ by $1$.
You are given $m$ queries of the following format:
- query $l$ $r$ — how many distinct values is $x$ assigned to ... | The value of $x$ always changes by $1$, thus, the set of values of $x$ is always some contiguous segment. The length of such segment can be determined by just its minimum and maximum values. So we have to solve two separate tasks for each query: find the minimum and the maximum value $x$ gets assigned to. I'll describe... | [
"data structures",
"dp",
"implementation",
"strings"
] | 1,700 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int t;
cin >> t;
forn(_, t){
int n, m;
string s;
cin >> n >> m;
cin >> s;
vector<int> sul(1, 0), sur(1, 0);
for (int i = n - 1; i >= 0; --i){
in... |
1473 | E | Minimum Path | You are given a weighted undirected connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of $k$ edges with indices $e_1, e_2, \dots, e_k$ as $\sum\limits_{i=1}^{k}{w_{e_i}} - \max\lim... | Let's consider a problem where you can subtract the weight of any edge (not only the maximum one) that belong to the current path and similarly add the weight of any edge (not only the minimum one) that belong to the current path. To solve that problem we can build a new graph where the node can be represented as the f... | [
"graphs",
"shortest paths"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int N = 200 * 1000 + 13;
int n, m;
vector<pair<int, int>> g[N];
long long d[N][2][2];
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int v, u, w;
scanf("%d%d%d", &v, &u, &w);
--v; --u;
g[v].emplace_back(u, w);
g[u].emplac... |
1473 | F | Strange Set | \textbf{Note that the memory limit is unusual.}
You are given an integer $n$ and two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$.
Let's call a set of integers $S$ such that $S \subseteq \{1, 2, 3, \dots, n\}$ strange, if, for every element $i$ of $S$, the following condition is met: for every $j \in [... | We will model the problem as the minimum cut in a flow network. Build a network as follows: create a source node $s$, a sink node $t$, and a vertex for every number from $1$ to $n$. Let's say that we are going to find the minimum $s$-$t$ cut in this network, and the vertices belonging to the same cut part with $s$ repr... | [
"flows",
"math"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
template<typename T>
struct dinic {
struct edge {
int u, rev;
T cap, flow;
};
int n, s, t;
T flow;
vector<int> lst;
vector<int> d;
vector<vector<edge>> g;
T scaling_lim;
bool scaling;
dinic() {}
... |
1473 | G | Tiles | Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.
The road is constructed as follows:
- the first row consists o... | The group of the rows where the number of rectangular tiles increases $a$ times and then decreases $b$ times can be represented as a rectangular table, with $a+b+1$ diagonals, where the size of the first diagonal is equal to the number of rectangular tiles before the operations are applied (let their number be $m$), an... | [
"combinatorics",
"dp",
"fft",
"math"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)
#define sz(a) int((a).size())
template<const int &MOD>
struct _m_int {
int val;
_m_int(int64_t v = 0) {
if (v < 0) v = v % MOD + MOD;
if (v >= MO... |
1474 | A | Puzzle From the Future | In the $2022$ year, Mike found two binary integers $a$ and $b$ of length $n$ (both of them are written only by digits $0$ and $1$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $d$ in the following way:
- he creates an integer $c$ as a result of bitwise summing of $a$ and $b... | Hint $1$: Should we always make first digit of $d$ not equal to $0$? How can we do it? Hint $2$: Try to choose such $a$ that $d$ will have $n$ digits. At first, we can make the first digit of $d$ not equal to $0$ by setting $1$ to the first digit of $a$. Now we say that $d$ doesn't have leading zeroes. In this case, mo... | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
string a;
cin >> a;
string b = "1";
for (int i = 1; i < n; i++)
{
if ('1' + a[i] != b[i - 1] + a[i - 1])
b += "1";
else
b += "0";
}
cout << b << "\n";
}
int mai... |
1474 | B | Different Divisors | Positive integer $x$ is called divisor of positive integer $y$, if $y$ is divisible by $x$ without remainder. For example, $1$ is a divisor of $7$ and $3$ is not divisor of $8$.
We gave you an integer $d$ and asked you to find \textbf{the smallest} positive integer $a$, such that
- $a$ has at least $4$ divisors;
- di... | Hint $1$: Integer have exactly $4$ divisors, if it is of form $pq$ or $p^3$ for some primes $p$ and $q$. In the first case it have divisors $1$, $p$, $q$, $pq$. In the second case it have divisors $1$, $p$, $p^2$, $p^3$. Hint $2$: Instead of finding integer with at least $4$ divisors, find integer with exactly $4$ divi... | [
"binary search",
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,000 | #include <iostream>
#include <vector>
using namespace std;
void solve()
{
int x;
cin >> x;
vector<int> p;
for (int i = x + 1; ; i++)
{
int t = 1;
for (int j = 2; j * j <= i; j++)
{
if (i % j == 0)
{
t = 0;
break;
... |
1474 | C | Array Destruction | You found a useless array $a$ of $2n$ positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of $a$.
It could have been an easy task, but it turned out that you should follow some rules:
- In the beginning, you select any positive integer $x$.
- Then you... | Hint $1$: How does $x$ changes after each operation? Hint $2$: Suppose, that you know $x$. What pairs of elements can you throw out now? Hint $3$: Suppose, that you did some operations. Note, that if you have integer $b$ that is greater or equal to $x$ and $b$ is still in array $a$, you can't remove $b$ from $a$, thus ... | [
"brute force",
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int A = 1e6 + 12;
int cnt[A];
void reset(vector<int> a)
{
for (int i = 0; i < a.size(); i++)
{
cnt[a[i]] = 0;
}
}
void solve()
{
int n;
cin >> n;
vector<int> a(2 * n);
for (int i = 0; i < 2 * n; i++)
{
cin >> a... |
1474 | D | Cleaning | During cleaning the coast, Alice found $n$ piles of stones. The $i$-th pile has $a_i$ stones.
Piles $i$ and $i + 1$ are neighbouring for all $1 \leq i \leq n - 1$. If pile $i$ becomes empty, piles $i - 1$ and $i + 1$ \textbf{doesn't} become neighbouring.
Alice is too lazy to remove these stones, so she asked you to t... | Hint $1$: How to solve the promblem if we are not allowed to use a superabilty (in linear time)? Hint $2$: Look at the first pile. There is only one way to remove stone from the first pile. Hint $3$: If you swap $i$-th and $(i + 1)$-th piles of stones, nothing changes in way you remove stones from $1$-st, $2$-nd, $\ldo... | [
"data structures",
"dp",
"greedy",
"math"
] | 2,200 | #include <iostream>
#include <vector>
using namespace std;
int check(vector<long long> a)
{
for (int i = 0; i + 1 < a.size(); i++)
{
if (a[i] > a[i + 1])
{
return 0;
}
a[i + 1] -= a[i];
a[i] = 0;
}
if (a.back() == 0)
return 1;
return 0;... |
1474 | E | What Is It? | Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation $p$ of length $n$. Scientists found out, that to overcome an obstacle, the robot should make $p$ an identity permutation (make $p_i = i$ for all $i$).
Unfortunately, scientists can't control the robot. Thus the only way ... | Hint $1$: How many operations will robot make in the worst case? Hint $2$: How many times can robot spend $(n - 1)^2$ time on $1$ operation? Hint $3$: How many times can robot spend $(n - 2)^2$ time on $1$ operation? It is easyer to think about number of operations with time greater or equal to $(n - 2)^2$. Hint $4$: I... | [
"constructive algorithms",
"greedy"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
if (n == 1)
{
cout << 0 << "\n";
cout << 1 << "\n";
cout << 0 << "\n";
return;
}
long long ans = 0;
long long cnt = 1, st = n - 1, asz = 0;
while (asz < n - 1)
{
... |
1474 | F | 1 2 3 4 ... | Igor had a sequence $d_1, d_2, \dots, d_n$ of integers. When Igor entered the classroom there was an integer $x$ written on the blackboard.
Igor generated sequence $p$ using the following algorithm:
- initially, $p = [x]$;
- for each $1 \leq i \leq n$ he did the following operation $|d_i|$ times:
- if $d_i \geq 0$, ... | Solution describes generalized version of algorigthm, corner cases are described later. It is easy to see that answer doesn't depend on $x$ given in the input, because we can substract $x$ from each element of $p$ and longest incerasing subsequences will remain the same. Let's look at $p$ as a function. If $p_i = x$ an... | [
"dp",
"math",
"matrices"
] | 3,000 | #include <bits/stdc++.h>
const long long MOD = 998244353;
using namespace std;
typedef long long ll;
vector<ll> binpow(int len, ll deg)
{
if (deg == 1) return vector<ll>(len, 1);
vector<ll> part = binpow(len, deg / 2);
vector<ll> whole(len);
auto D = [&](int i, int j){
assert(i <= j);
... |
1475 | A | Odd Divisor | You are given an integer $n$. Check if $n$ has an \textbf{odd} divisor, greater than one (does there exist such a number $x$ ($x > 1$) that $n$ is divisible by $x$ and $x$ is odd).
For example, if $n=6$, then there is $x=3$. If $n=4$, then such a number does not exist. | If the number $x$ has an odd divisor, then it has an odd prime divisor. To understand this fact, we can consider what happens when multiplying even and odd numbers: even $*$ even $=$ even; even $*$ odd $=$ even; odd $*$ even $=$ even; odd $*$ odd $=$ odd. There is only one even prime number - $2$. So, if a number has n... | [
"math",
"number theory"
] | 900 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
void solve() {
ll n;
cin >> n;
if (n & (n - 1)) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
} |
1475 | B | New Year's Number | Polycarp remembered the $2020$-th year, and he is happy with the arrival of the new $2021$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $n$ as the sum of a certain number of $2020$ and a certain number of $2021$.
For example, if:
- $n=4041$, then the number $n$ can be represent... | Let $x$ - the number of $2020$, $y$ - the number of $2021$ ($x, y \geq 0$). Let us write the required decomposition of the number $n$: $n = 2020 \cdot x + 2021 \cdot y = 2020 \cdot (x + y) + y$ $x = \frac{n - y}{2020} - y$ | [
"brute force",
"dp",
"math"
] | 900 | #include <bits/stdc++.h>
#include <utility>
using namespace std;
using pii = pair<int, int>;
int main() {
int test;
cin >> test;
while (test-- > 0) {
int n;
cin >> n;
int cnt2021 = n % 2020;
int cnt2020 = (n - cnt2021) / 2020 - cnt2021;
if (cnt2020 >= 0 && 2020 * cnt2020 + 2021 * cnt2021 ==... |
1475 | C | Ball in Berland | At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.
Each class must present two couples to the ball. In Vasya's class, $a$ boys and $b$ girls wish to participate. But not all boys and... | We can think that it is given a bipartite graph. Boys and girls are the vertices of the graph. If a boy and a girl are ready to dance together, then an edge is drawn between them. In this graph, you need to select two edges that do not intersect at the vertices. Let $deg(x)$ - the number of edges included in the vertex... | [
"combinatorics",
"graphs",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
void solve() {
int A, B, k;
cin >> A >> B >> k;
vector<int> a(A), b(B);
vector<pair<int, int>> edges(k);
for (auto &[x, y] : edges) {
cin >> x;
}
for (auto &[x, y] : edges) {
cin >> y;
}
for (auto &[x... |
1475 | D | Cleaning the Phone | Polycarp often uses his smartphone. He has already installed $n$ applications on it. Application with number $i$ takes up $a_i$ units of memory.
Polycarp wants to free at least $m$ units of memory (by removing some applications).
Of course, some applications are more important to Polycarp than others. He came up with... | Let's say we remove $x$ applications with $b_i=1$ and $y$ applications with $b_i=2$. Obviously, among all the applications with $b_i=1$, it was necessary to take $x$ maximum in memory (so we will clear the most memory). Let's split all the applications into two arrays with $b_i=1$ and $b_i=2$ and sort them. Then you ne... | [
"binary search",
"dp",
"sortings",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
void solve() {
int n, m;
cin >> n >> m;
vector<int> a, b;
vector<int> v(n);
for (int &e : v) {
cin >> e;
}
for (int &e : v) {
int x;
cin >> x;
if (x == 1) {
a.push_back(e);
} else {
... |
1475 | E | Advertising Agency | Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of $n$ different bloggers. Blogger numbered $i$ has $a_i$ followers.
Since Masha has a limited budget, she can only sign a contract with $k$ different bloggers. O... | It is obvious that Masha will enter into agreements only with bloggers that have the most subscribers. You can sort all the bloggers and greedily select the prefix. Let $x$ - be the minimum number of subscribers for the hired blogger. Then we must hire all the bloggers who have more subscribers. Let $m$ - the number of... | [
"combinatorics",
"math",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int mod = 1e9 + 7;
int fast_pow(int a, int p) {
int res = 1;
while (p) {
if (p % 2 == 0) {
a = a * 1ll * a % mod;
p /= 2;
} else {
res = res * 1ll * a % mod;
p--;
}
}
return res;
}
... |
1475 | F | Unusual Matrix | You are given two binary square matrices $a$ and $b$ of size $n \times n$. A matrix is called binary if each of its elements is equal to $0$ or $1$. You can do the following operations on the matrix $a$ \textbf{arbitrary} number of times (0 or more):
- vertical xor. You choose the number $j$ ($1 \le j \le n$) and for ... | It is clear that the order of operations does not affect the final result, also it makes no sense to apply the same operation more than once (by the property of the xor operation). Let's construct a sequence of operations that will reduce the matrix $a$ to the matrix $b$ (if the answer exists). Let's try iterate over: ... | [
"2-sat",
"brute force",
"constructive algorithms"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
bool check(vector<vector<int>> a, vector<vector<int>> const &b) {
int n = (int) a.size();
for (int j = 0; j < n; j++) {
if (a[0][j] != b[0][j]) {
for (int i = 0; i < n; i++) {
a[i][j] ^= 1;
}
}
}
for (int i =... |
1475 | G | Strange Beauty | Polycarp found on the street an array $a$ of $n$ elements.
Polycarp invented his criterion for the beauty of an array. He calls an array $a$ beautiful if at least one of the following conditions must be met \textbf{for each different pair of indices} $i \ne j$:
- $a_i$ is divisible by $a_j$;
- or $a_j$ is divisible b... | Let's calculate for each number $x$ how many times it occurs in the array $a$. Let's denote this number as $cnt_x$. Let's use the dynamic programming method. Let $dp(x)$ be equal to the maximum number of numbers not greater than $x$ such that for each pair of them one of the conditions above is satisfied. More formally... | [
"dp",
"math",
"number theory",
"sortings"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int N = (int) 2e5 + 100;
int dp[N];
int cnt[N];
void solve() {
int n;
cin >> n;
fill(dp, dp + N, 0);
fill(cnt, cnt + N, 0);
for (int i = 0; i < n; i++) {
int x;
cin >> x;
cnt[x]++;
}
for (int i = 1; i < N; i++) {
dp[i] += cnt[i];
f... |
1476 | A | K-divisible Sum | You are given two integers $n$ and $k$.
You should create an array of $n$ \textbf{positive integers} $a_1, a_2, \dots, a_n$ such that the sum $(a_1 + a_2 + \dots + a_n)$ is divisible by $k$ and maximum element in $a$ is minimum possible.
What is the minimum possible maximum element in $a$? | Let's denote $s$ as the sum of array $a$. From one side, since $s$ should be divisible by $k$ then we can say $s = cf \cdot k$. From other side, since all $a_i$ are positive, then $s \ge n$. It's quite obvious that the smaller $s$ - the smaller maximum $a_i$ so we need to find the smallest $cf$ that $cf \cdot k \ge n$.... | [
"binary search",
"constructive algorithms",
"greedy",
"math"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while(t--) {
long long n, k;
cin >> n >> k;
long long cf = (n + k - 1) / k;
k *= cf;
cout << (k + n - 1) / n << endl;
}
return 0;
} |
1476 | B | Inflation | You have a statistic of price changes for one product represented as an array of $n$ positive integers $p_0, p_1, \dots, p_{n - 1}$, where $p_0$ is the initial price of the product and $p_i$ is how the price was increased during the $i$-th month.
Using these price changes you are asked to calculate the inflation coeff... | Suppose we decided to increase some $p_i$ by $x > 0$. How does it affect all inflation coefficients? Let's the $j$-th inflation coefficient be $cf_j$. We now that $cf_j = \frac{p_j}{p_0 + \dots + p_{j - 1}}$. If $j < i$, then $cf_j$ doesn't change. If $j > i$ then it's denominator increases by $x$ and $cf_j$ decreases.... | [
"binary search",
"brute force",
"greedy",
"math"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
const int INF = int(1e9);
int main() {
int t; cin >> t;
while(t--) {
int n, k;
cin >> n >> k;
vector<int> p(n);
for (int i = 0; i < n; i++)
cin >> p[i];
li x = 0;
li pSum = p[0];
for (int i = 1; i < n; i++)... |
1476 | C | Longest Simple Cycle | You have $n$ chains, the $i$-th chain consists of $c_i$ vertices. Vertices in each chain are numbered independently from $1$ to $c_i$ along the chain. In other words, the $i$-th chain is the undirected graph with $c_i$ vertices and $(c_i - 1)$ edges connecting the $j$-th and the $(j + 1)$-th vertices for each $1 \le j ... | Suppose, we've built the graph and chosen any simple cycle. Due to the nature of the graph, any simple cycle right part is part of one of the chains. So, let's for each chain calculate the longest simple path with its right part on this chain and denote it as $len_i$. Obviously, $len_1 = 0$. Now, let's look at chain $i... | [
"dp",
"graphs",
"greedy"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> c(n), a(n), b(n);
for (int i = 0; i < n; i++)
cin >> c[i];
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
c... |
1476 | D | Journey | There are $n + 1$ cities, numbered from $0$ to $n$. $n$ roads connect these cities, the $i$-th road connects cities $i - 1$ and $i$ ($i \in [1, n]$).
Each road has a direction. The directions are given by a string of $n$ characters such that each character is either L or R. If the $i$-th character is L, it means that ... | There are two key observations to this problem: after each pair of moves, the directions go back to the original ones; after each move, we can immediately go back (and combining these observations, we can derive that if we go from city $i$ to some other city $j$, we can always go back). One of the solutions we can writ... | [
"dfs and similar",
"dp",
"dsu",
"implementation"
] | 1,700 | t = int(input())
for _ in range(t):
n = int(input())
s = input()
dpl = [i for i in range(n + 1)]
dpr = [i for i in range(n + 1)]
for i in range(n + 1):
if i == 0 or s[i - 1] == 'R':
dpl[i] = i
elif i == 1 or s[i - 2] == 'L':
dpl[i] = i - 1
else:
... |
1476 | E | Pattern Matching | You are given $n$ patterns $p_1, p_2, \dots, p_n$ and $m$ strings $s_1, s_2, \dots, s_m$. Each pattern $p_i$ consists of $k$ characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string $s_j$ consists of $k$ lowercase Latin letters.
... | Let's write down the indices of the pattern that the $j$-th string matches. If $mt_j$ is not among these, then the answer is NO. Otherwise, all the patterns except $mt_j$ should go in the resulting ordering after $mt_j$. Consider that as a graph. Let's add an edge from $mt_j$ to each of the matches. If you add the edge... | [
"bitmasks",
"data structures",
"dfs and similar",
"graphs",
"hashing",
"sortings",
"strings"
] | 2,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct pattern{
string s;
int i;
};
bool operator <(const pattern &a, const pattern &b){
return a.s < b.s;
}
vector<vector<int>> g;
vector<int> used, ord;
bool cyc;
void ts(int v){
used[v] = 1;
for (int u :... |
1476 | F | Lanterns | There are $n$ lanterns in a row. The lantern $i$ is placed in position $i$ and has power equal to $p_i$.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the $i$-th lantern is turned to the left, it illuminates all such lanterns $j$ that $j \in [i - p_i, i -... | The main idea of the solution is to calculate the following dynamic programming: $dp_i$ is the maximum prefix we can fully cover with $i$ first lanterns. Let's look at how can we solve it in $O(n^2)$ with this kind of dynamic programming. First of all, let's write it forward. Which transitions from $dp_i$ do we have? i... | [
"binary search",
"data structures",
"dp"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
const int INF = int(1e9);
struct segTree
{
int n;
bool mx;
vector<int> t;
void fix(int v)
{
t[v] = (mx ? max(t[v * 2 + 1], t[v * 2 + 2]) : min(t[v * 2 + 1], t[v * 2 + 2]));
}
void build(int v, int l, int r)
{
if(l == r - 1... |
1476 | G | Minimum Difference | You are given an integer array $a$ of size $n$.
You have to perform $m$ queries. Each query has one of two types:
- "$1$ $l$ $r$ $k$" — calculate the minimum value $dif$ such that there are exist $k$ \textbf{distinct} integers $x_1, x_2, \dots, x_k$ such that $cnt_i > 0$ (for every $i \in [1, k]$) and $|cnt_i - cnt_j... | Let's consider a problem without queries of the second type. Now we can try to solve the problem using Mo's algorithm. Let's maintain array $cnt_i$ - the number of occurrences of $i$ on the current segment and array $ord$ - array $cnt$ sorted in descending order. Let's take a look at how we should handle adding an elem... | [
"data structures",
"hashing",
"sortings",
"two pointers"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef pair<int, int> pt;
const int N = 100 * 1000 + 13;
const int P = 2000;
struct query {
int t, l, r, k, i;
};
int main() {
int n, m;
scanf("%d... |
1477 | A | Nezzar and Board | $n$ \textbf{distinct} integers $x_1,x_2,\ldots,x_n$ are written on the board. Nezzar can perform the following operation multiple times.
- Select two integers $x,y$ (not necessarily distinct) on the board, and write down $2x-y$. Note that you don't remove selected numbers.
Now, Nezzar wonders if it is possible to hav... | Let's first assume that $x_1=0$ (Otherwise, we could subtract $x_1$ for $x_1,x_2,\ldots,x_n$ and $k$). We will now prove that the answer is "YES" if and only if $k$ can be divided by $g=\gcd(x_2,x_3,\ldots,x_n)$. One direction is straightforward. Note that any number written on the board should be divisible by $g$, whi... | [
"constructive algorithms",
"math",
"number theory"
] | 1,800 | #include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=200007;
int t;
int n,k;
int x[maxn];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>t;
while (t--){
cin>>n>>k;
for (int i=0;i<n;++i) cin>>x[i];
sort(x,x+n);
in... |
1477 | B | Nezzar and Binary String | Nezzar has a binary string $s$ of length $n$ that he wants to share with his best friend, Nanako. Nanako will spend $q$ days inspecting the binary string. At the same time, Nezzar wants to change the string $s$ into string $f$ during these $q$ days, because it looks better.
It is known that Nanako loves consistency so... | The operations can be described backward: Iterate days in reverse order and start with $f$. In $i$-th day, if there is a strict majority of $0$s or $1$s between $l_i$ and $r_i$, change ALL element inside the range to be the majority. Otherwise, declare that the operation failed. We can see that the "backward" operation... | [
"data structures",
"greedy"
] | 1,900 | #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0;i<(int)(n);++i)
#define rep1(i,n) for (int i=1;i<=(int)(n);++i)
#define range(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define pb push_back
#define F first
#define S second
typedef long long ll;
typedef unsigned long long ull;
typed... |
1477 | C | Nezzar and Nice Beatmap | Nezzar loves the game osu!.
osu! is played on beatmaps, which can be seen as an array consisting of \textbf{distinct} points on a plane. A beatmap is called nice if for any three consecutive points $A,B,C$ listed in order, the angle between these three points, centered at $B$, is \textbf{strictly less than} $90$ degre... | There are two different approaches to solve this task. Furthest Points Pick an arbitrary point, and in each iteration, select the furthest point from previously chosen point among all available points. Indeed, we can prove the correctness by contradiction. Insertion Sorting Notice that in any triangle (possibly degener... | [
"constructive algorithms",
"geometry",
"greedy",
"math",
"sortings"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
const int maxn=6007;
int n;
int x[maxn],y[maxn];
vector<int> perm;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n;
for (int i=0;i<n;++i) cin>>x[i]>>y[i];
for (int i=0;i<n;++i){
perm.push_back(i);
for (int j... |
1477 | D | Nezzar and Hidden Permutations | Nezzar designs a brand new game "Hidden Permutations" and shares it with his best friend, Nanako.
At the beginning of the game, Nanako and Nezzar both know integers $n$ and $m$. The game goes in the following way:
- Firstly, Nezzar hides two permutations $p_1,p_2,\ldots,p_n$ and $q_1,q_2,\ldots,q_n$ of integers from ... | We can describe the problem in graph theory terms: We are given a graph $G$ of $n$ vertices and $m$ edge. The $i$-th edge connects vertices $l_i$ and $r_i$. We need to write down two numbers on each vertices, on $i$-th vertex we write $p_i$ and $q_i$ on it, so that: $p$ and $q$ forms a permutation from $1$ to $n$, For ... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
const int maxn=500007;
struct info{
int idx,val;
friend bool operator<(info u,info v){
return u.val==v.val?u.idx<v.idx:u.val<v.val;
}
};
struct stars{
int rt;
vector<int> leaves;
};
set<int> rv; // remained vertices
set<int> g[maxn]; // orig... |
1477 | E | Nezzar and Tournaments | In the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points.
The first team consists of $n$ players, and the second team consists of $m$ players. Each player has a potential: the potential of the $i$-th player in the first team is $a_i$, and the poten... | Let's firstly consider a simplified problem where the scoring device will not reset to $0$. For any player, his score will be fully determined by his potential as well as the potential of first player when $k$ is fixed. Indeed, similar property still holds in our setting. Observation 1. For any fixed arrangement of pla... | [
"data structures",
"greedy"
] | 3,300 | //#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
//#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0;i<(int)(n);++i)
#define rep1(i,n) for (int i=1;i<=(int)(n);++i)
#define range(x) begin(x), end(x)
#defin... |
1477 | F | Nezzar and Chocolate Bars | Nezzar buys his favorite snack — $n$ chocolate bars with lengths $l_1,l_2,\ldots,l_n$. However, chocolate bars might be too long to store them properly!
In order to solve this problem, Nezzar designs an interesting process to divide them into small pieces. Firstly, Nezzar puts all his chocolate bars into a black box. ... | Let's firstly solve an easier version where $n=1$. Part 1 ($n = 1$) Let's firstly rephrase the original task and solve it for case $n=1$. - Let $p_k$ the probability of event that $X_{(i)}-X_{(i-1)} \le K$ for $1 \le i \le k$ and $L - X_{(k)} \le K$. Here, $k$ real numbers $X_1,X_2,\ldots,X_k$ are chosen uniformly from... | [
"combinatorics",
"fft",
"math",
"probabilities"
] | 3,500 | //#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
//#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define int long long
using namespace std;
#define rep(i,n) for (int i=0;i<(int)(n);++i)
#define rep1(i,n) for (int i=1;i<=(int)(n);++i)
#define range(x) b... |
1478 | A | Nezzar and Colorful Balls | Nezzar has $n$ balls, numbered with integers $1, 2, \ldots, n$. Numbers $a_1, a_2, \ldots, a_n$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $a_i \leq a_{i+1}$ for all $1 \leq i < n$.
Nezzar wants to color the balls using the minimum number of colors, such ... | For positions which numbers are the same, they cannot be colored using same color. Let us color the $i$-th occurrence of any number using color $i$. We can see that: We cannot use fewer colors: if there are $k$ occurrence of any number, at least $k$ color is needed. The assignment of color is valid: Since the sequence ... | [
"brute force",
"greedy"
] | 800 | #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0;i<(int)(n);++i)
#define rep1(i,n) for (int i=1;i<=(int)(n);++i)
#define range(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define pb push_back
#define F first
#define S second
typedef long long ll;
typedef unsigned long long ull;
typed... |
1478 | B | Nezzar and Lucky Number | Nezzar's favorite digit among $1,\ldots,9$ is $d$. He calls a \textbf{positive} integer lucky if $d$ occurs at least once in its decimal representation.
Given $q$ integers $a_1,a_2,\ldots,a_q$, for each $1 \le i \le q$ Nezzar would like to know if $a_i$ can be equal to a sum of several (one or more) lucky numbers. | For any given $d$, We can observe the following: $10d$ to $10d + 9$ contains $d$ as one of its digit Let $k = 10d + 9$ be the upper bound of such range For every number $x > k$, we can keep reducing $x$ by $d$, $x$ will eventually fall into the range mentioned above, which contains $d$ as digit. Therefore, for numbers ... | [
"brute force",
"dp",
"greedy",
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
const int maxn=207;
int t,d,q;
bool dp[maxn];
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>t;
while (t--){
memset(dp,0,sizeof(dp));
dp[0]=1;
cin>>q>>d;
if (!d) d+=10;
int mx=d*10;
for... |
1478 | C | Nezzar and Symmetric Array | Long time ago there was a symmetric array $a_1,a_2,\ldots,a_{2n}$ consisting of $2n$ \textbf{distinct integers}. Array $a_1,a_2,\ldots,a_{2n}$ is called symmetric if for each integer $1 \le i \le 2n$, there exists an integer $1 \le j \le 2n$ such that $a_i = -a_j$.
For each integer $1 \le i \le 2n$, Nezzar wrote down ... | WLOG, we may assume that $0 < a_1 < a_2 < \ldots < a_n$, and $a_{i+n}=-a_i$ for each $1 \le i \le n$. Let's sort array $d$ firstly. It can be observed that the array $d$ satisfied the following property: $d_{2i-1}=d_{2i}$ for each $1 \le i \le n$; $d_{2i} \neq d_{2i+2}$ for each $1 \le i < n$. $d_{2i}$ must be generate... | [
"implementation",
"math",
"sortings"
] | 1,700 | #include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=200007;
int t;
int n,a[maxn],b[maxn],d[maxn];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>t;
while (t--){
cin>>n;
for (int i=0;i<2*n;++i) cin>>a[i];
sort(a,a+2*n,gr... |
1479 | A | Searching Local Minimum | \textbf{This is an interactive problem}.
Homer likes arrays a lot and he wants to play a game with you.
Homer has hidden from you a permutation $a_1, a_2, \dots, a_n$ of integers $1$ to $n$. You are asked to find any index $k$ ($1 \leq k \leq n$) which is a local minimum.
For an array $a_1, a_2, \dots, a_n$, an inde... | We maintain by binary search a range $[l, r]$ which has a local minimum. Moreover, we assume that $a_{l-1} > a_l$ and $a_r < a_{r+1}$. Initially, $[l, r] = [1, n]$. In each iteration, let $m$ be the midpoint of $l$ and $r$. Case 1. If $a_m < a_{m+1}$, then the range becomes $[l, m]$. Case 2. If $a_m > a_{m+1}$, then th... | [
"binary search",
"interactive",
"ternary search"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n;
int a[MAXN];
int query(int x)
{
if (1 <= x && x <= n)
{
printf("? %d\n", x);
fflush(stdout);
scanf("%d", &a[x]);
}
}
int main()
{
scanf("%d", &n);
a[0] = a[n + 1] = n + 1;
int L = 1, R = n;
while (L < R)
{
int m = (L... |
1479 | B1 | Painting the Array I | \textbf{The only difference between the two versions is that this version asks the maximal possible answer.}
Homer likes arrays a lot. Today he is painting an array $a_1, a_2, \dots, a_n$ with two kinds of colors, \textbf{white} and \textbf{black}. A painting assignment for $a_1, a_2, \dots, a_n$ is described by an ar... | Formally, for every sequence $a_1, a_2, \dots, a_n$, and we assume that $a_1, a_2, \dots, a_n$ are positive integers, the number of segments in $a$ is defined to be $\mathit{seg}(a) = \sum_{i=1}^n [ a_{i-1} \neq a_{i} ],$ Let's restate the problem as Problem. Given a sequence $a_1, a_2, \dots, a_n$, divide it into two ... | [
"constructive algorithms",
"data structures",
"dp",
"greedy",
"implementation"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n;
int a[MAXN];
int pos[MAXN], nxt[MAXN];
void solve()
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for (int i = 0; i <= n; ++i)
pos[i] = n + 1;
for (int i = n; i >= 0; --i)
{
nxt[i] = pos[a[i]];
pos[a... |
1479 | B2 | Painting the Array II | \textbf{The only difference between the two versions is that this version asks the minimal possible answer.}
Homer likes arrays a lot. Today he is painting an array $a_1, a_2, \dots, a_n$ with two kinds of colors, \textbf{white} and \textbf{black}. A painting assignment for $a_1, a_2, \dots, a_n$ is described by an ar... | There are two approaches from different perspectives. DP Approach The first observation is that merging adjacent elements with the same value will not influence the answer. Therefore, without loss of generality, we may assume that there are no adjacent elements with the same value, i.e. $a_{i} \neq a_{i+1}$ for every $... | [
"constructive algorithms",
"data structures",
"dp",
"greedy",
"implementation"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n;
int a[MAXN];
int pos[MAXN], nxt[MAXN];
void solve()
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for (int i = 0; i <= n; ++i)
pos[i] = n + 1;
for (int i = n; i >= 0; --i)
{
nxt[i] = pos[a[i]];
pos[a... |
1479 | C | Continuous City | Some time ago Homer lived in a beautiful city. There were $n$ blocks numbered from $1$ to $n$ and $m$ directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road be... | The answer is always "YES". For convenience, we write $(x, y, z)$ for a directed road from block $x$ to block $y$ of length $z$. Step 1. We can solve the case $L = 1$ and $R = 2^k$ for $k \geq 0$ inductively. The case for $k = 0$ is trivial, i.e. only one edge $(1, 2, 1)$. Suppose there is a city of $k + 2$ blocks for ... | [
"bitmasks",
"constructive algorithms"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
vector<tuple<int, int, int>> edges;
void addedge(int x, int y, int z)
{
edges.push_back({ x, y, z });
}
int solve(int L, int R)
{
if (L > 1)
{
int k = solve(1, R - L + 1);
addedge(k, k + 1, L - 1);
return k + 1;
}
if ((R & -R) == R) // if L == 1 and R is ... |
1479 | D | Odd Mineral Resource | In Homer's country, there are $n$ cities numbered $1$ to $n$ and they form a tree. That is, there are $(n-1)$ undirected roads between these $n$ cities and every two cities can reach each other through these roads.
Homer's country is an industrial country, and each of the $n$ cities in it contains some mineral resourc... | Let $s(u, v, c)$ denote the number of cities between city $u$ and city $v$, whose mineral resource is $c$. We restate the problem that for each query $u, v, l, r$, find an integer $c$ such that $l \leq c \leq r$ and $s(u, v, c) \not\equiv 0 \pmod 2$. We give a randomized algorithm with success probability extremely hig... | [
"binary search",
"bitmasks",
"brute force",
"data structures",
"probabilities",
"trees"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 300010;
const int MAXK = 20;
mt19937_64 rd(chrono::steady_clock::now().time_since_epoch().count());
int n, q;
int a[MAXN];
uint64_t h[MAXN];
vector<int> v[MAXN];
int pre[MAXN][MAXK];
int dis[MAXN];
struct node
{
node* Lc, * Rc;
uint64_t val;
no... |
1479 | E | School Clubs | In Homer's school, there are $n$ students who love clubs.
Initially, there are $m$ clubs, and each of the $n$ students is in exactly one club. In other words, there are $a_i$ students in the $i$-th club for $1 \leq i \leq m$ and $a_1+a_2+\dots+a_m = n$.
The $n$ students are so unfriendly that every day one of them (c... | Section 1. The Expected Value of Stopping Time There may be several ways to deal with the expected value of stopping time. Here, we decide to give an elegant way to derive the expected stopping time inspired by MiFaFaOvO's comment. Here, we are going to introduce the mathematical tool we will use in the following descr... | [
"dp",
"fft",
"math",
"number theory",
"probabilities"
] | 3,500 | null |
1480 | A | Yet Another String Game | Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string $s = s_1 s_2 \dots s_n$ of length $n$ consisting of lowercase English letters. They move in turns alternatively and \textbf{Alice makes the first move}.
In a move, a player \textbf{must} choose ... | After some observations, we can see that the players should always choose the most significant letter to change, because it coordinates the lexicographical order of the final string most. Therefore, Alice will choose all odd indices while Bob will choose all even indices, and then Alice will change all letters she choo... | [
"games",
"greedy",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
string s;
cin >> s;
for (int i = 0; i < s.size(); ++i)
{
if (i % 2 == 0)
{
s[i] = s[i] == 'a' ? 'b' : 'a';
}
else
{
s[i] = s[i] == 'z' ? 'y' : 'z';
}
}
cout << s << endl;
}
int main()
{
int tests;
cin >> tests;
while (tests--)... |
1480 | B | The Great Hero | The great hero guards the country where Homer lives. The hero has attack power $A$ and initial health value $B$. There are $n$ monsters in front of the hero. The $i$-th monster has attack power $a_i$ and initial health value $b_i$.
The hero or a monster is said to be living, if his or its health value is positive (gre... | The hero needs $\lceil b_i/A \rceil$ attacks to kill the $i$-th monster, and he will obtain $\lceil b_i/A \rceil a_i$ damage after that. Suppose the $k$-th monster is the last monster killed by the hero. Then the health value of the hero before the last attack is $h_k = B - \sum_{i=1}^n \left\lceil \frac {b_i} {A} \rig... | [
"greedy",
"implementation",
"sortings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int A, B, n;
int a[MAXN], b[MAXN];
void solve()
{
scanf("%d%d%d", &A, &B, &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for (int i = 1; i <= n; ++i)
scanf("%d", &b[i]);
int64_t damage = 0;
for (int i = 1; i <= n; ++i)
dama... |
1481 | A | Space Navigation | You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.
Space can be represented as the $XY$ plane. You are starting at point $(0, 0)$, and Planetforces is located in ... | Hint 1: You can think of this problem as 2 independent 1D questions (one is up and down , and the other is left and right) instead of 1 2D question. Hint 2: For each 1D part what is the interval of positions that you can reach and see if the end point is in this interval. Hint 3: The interval of up and down is [-The co... | [
"greedy",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;cin>>t;
while(t--){
int x,y;cin>>x>>y;
string s;cin>>s;
int u=0,d=0,l=0,r=0;
for(int i=0;i<s.length();i++){
if(s[i]=='U')u++;
else if(s[i]=='R')r++;
else if(s[i]=='D')d++;
... |
1481 | B | New Colony | After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).
You are given an array $h_1, h_2, \dots, h_n$, ... | The two key observation here is that if one boulder fall into the collection system all later boulders will fall into the collection system too and the number of boulders that will end up at any mountain is too small (Hence it will be at most $(n-1) \cdot (100 - 1)$). So we can simulate all boulders throwing until one ... | [
"brute force",
"greedy",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define fast ios::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main(){
fast
int t;
cin>>t... |
1481 | C | Fence Painting | You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it.
You have a fence consisting of $n$ planks, where the $i$-th plank has the color $a_i$. You want to repaint the fence in such a way that the ... | We must first see that the most important painter is the last one (and he will paint plank $x$ where $b_x = c_m$) because of two reasons: when he paints plank $x$ it won't be changed and if some other painter have a color that we don't need we can make him paint plank $x$, which will be repainted later. Now we need to ... | [
"brute force",
"constructive algorithms",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 1000000010
const int N = 300010;
int n , m;
int a[N] , b[N] , c[N] , ans[N];
vector< int > g[N];
void solve(){
scanf("%d%d",&n,&m);
for(int i = 1 ;i <= n;i++) g[i].clear();
for(int i = 0 ;i < n;i++)
scanf("%d",&a[i]);
for(int i = ... |
1481 | D | AB Graph | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
You are given... | If you can find any two nodes $x$, $y$ such that the edge going from $x$ to $y$ has the same value as the edge going from $y$ to $x$, then the answer is obviously YES. If not, if $m$ is odd you can just choose any two nodes $x$ and $y$ and keep going $y \xrightarrow{} x \xrightarrow{} y \xrightarrow{} x \xrightarrow{} ... | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define mod 998244353
#define oo 1000000010
const int N = 1010;
int n , m;
char grid[N][N];
int has[N][2];
void solve(){
scanf("%d%d",&n,&m);
for(int i = 0 ;i <= n;i++) has[i][0] = has[i][1] = -1;
for(int i = 0 ;i < n;i++){
scanf("%s",grid[i]);
for(int j = 0 ;j < ... |
1481 | E | Sorting Books | One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first.
There are $n$ books standing in a row on the shelf, the $i$-th book has color $a_i$.
You'd like to rearrange the books to make the shelf look beautiful.... | Lets try to solve the opposite version of the problem where you want to find the maximum number of books that will stay unmoved, so we will choose number of books that will stay unmoved and then move the rest in a way that will make the shelf beautiful. To do that lets first for each color $c$ find the leftmost and rig... | [
"data structures",
"dp",
"greedy"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define fast ios::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main(){
fast
int n;
cin>>n... |
1481 | F | AB Tree | Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.
The problem is:
You are given a connected tree rooted at node $1$.
You should ass... | let the diameter of the tree (the maximum distance between a root and a leaf) be $d$, then the answer couldn't be less than $d+1$ because you will add strings of all lengths between $1$ and $d+1$. In order to have the answer $d+1$, you need all strings with the same length to be equal, so all nodes on the same level mu... | [
"dp",
"greedy",
"trees"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
#define mod 998244353
#define oo 1000000010
const int N = 100010;
const int SQ = 500;
int n , x , p;
vector< int > g[N] , cur[N];
char c[N];
int mx;
vector< pair<int,int> > v , v2;
pair< int , char > a , b;
int sz[N];
bool comp(int u,int v){
return (sz[u] < sz[v]);
}... |
1482 | A | Prison Break | Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.
The prison can be represented as a rectangle $a\times b$ which is divided int... | Each broken wall increases the number of connected regions of the plane at most by one. Since in the end every single cell must be in the same region as the outside of the prison, there has to be only one connected region, hence the answer is at least $nm$ (because there were $nm + 1$ connected regions at the beginning... | [
"math"
] | 800 | null |
1482 | B | Restore Modulo | For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.
This generator takes four non-negative n... | Handle the case of $c = 0$ separately. For this check whether for every $i$ from $1\leq i < n$ there holds an equality $arr[i] = arr[i + 1]$ (or in other words, all numbers are the same). If this is true then the modulo can be arbitrarily large. Otherwise, if $arr[i] = arr[i + 1]$ holds for at least one $i$, then $c$ m... | [
"implementation",
"math"
] | 1,500 | null |
1482 | C | Basic Diplomacy | Aleksey has $n$ friends. He is also on a vacation right now, so he has $m$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $m$ days.
On each of these days some friends will be available for playing, and all others will not. On each day Aleksey m... | First, for each day we select an arbitrary friend from the list. With this choice, at most one friend will play more than $\left\lceil\dfrac{m}{2}\right\rceil$ times. Let's call him $f$. We want to fix schedule such that $f$ will play exactly $\left\lceil\dfrac{m}{2}\right\rceil$ times. To do this, we go through all th... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation"
] | 1,600 | null |
1482 | D | Playlist | Arkady has a playlist that initially consists of $n$ songs, numerated from $1$ to $n$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $1$. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the... | Let's call a pair of songs bad if GCD of their genres is $1$. It is easy to check if two songs are bad with Euclid's algorithm in $O(\log{C})$. There are at most $n$ deletions, so simulation is fine in terms of time limit, but we should be able to find the next deleted song quickly. Let's maintain an ordered set of son... | [
"data structures",
"dsu",
"implementation",
"shortest paths"
] | 1,900 | null |
1482 | E | Skyline Photo | Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help.
There are $n$ buildings in the city, the $i$-th of them has positive height $h_i$. ... | We can solve this problem with DP. A trivial $O(n^2)$ algorithm would look like this: Define $dp_i$ as the maximum beauty that can be achieved if we have a set of photos of buildings from $1$ to $i$. We can check every possible splitting point $j \le i$ for the rightmost picture of the set, and keep the biggest answer.... | [
"data structures",
"divide and conquer",
"dp"
] | 2,100 | null |
1482 | F | Useful Edges | You are given a weighted undirected graph on $n$ vertices along with $q$ triples $(u, v, l)$, where in each triple $u$ and $v$ are vertices and $l$ is a positive integer. An edge $e$ is called useful if there is at least one triple $(u, v, l)$ and a path (not necessarily simple) with the following properties:
- $u$ an... | Find all distances between vertices via Floyd's algorithm for $O(n^3)$. Consider all triples with fixed endpoint, say, $v$. Let's find all useful edges corresponding to such triples. An edge $(a, b, w)$ is useful, if there is a triple $(v, u_i, l_i)$ with $dist(v, a) + w + dist(b, u_i)\leq l_i\Leftrightarrow -l_i + dis... | [
"graphs",
"shortest paths"
] | 2,400 | null |
1482 | G | Vabank | Gustaw is the chief bank manager in a huge bank. He has unlimited access to the database system of the bank, in a few clicks he can move any amount of money from the bank's reserves to his own private account. However, the bank uses some fancy AI fraud detection system that makes stealing more difficult.
Gustaw knows ... | Our solution consists of two parts. First of all find an upper bound for $M$. To achieve this, we try to query $1$, $2$, $4$, $8$ and so on until we fail. After the first unsuccessful query we will have $0$ euro and know that the answer is on some segment $[2^k, 2^{k+1})$. It takes at most 47 queries. Now one could do ... | [
"binary search",
"interactive"
] | 3,200 | null |
1482 | H | Exam | This year a Chunin Selection Exam is held again in Konoha, and taking part in it are $n$ ninjas named $s_1$, $s_2$, ..., $s_n$. All names are distinct. One of the exam stages consists of fights between the participants. This year the rules determining the ninjas for each fight are the following: ninjas $i$ and $j$ figh... | Fix a particular string $s$ and find all edges outgoing from it. For each position $i$ of the string let's find the value of $left_i$ being the starting position of the longest substring which ends at the position $i$ and is one of the strings $s_j$. It's easy to see that such strings are the only ones where the outgoi... | [
"data structures",
"string suffix structures",
"trees"
] | 3,400 | null |
1485 | A | Add and Divide | You have two positive integers $a$ and $b$.
You can perform two kinds of operations:
- $a = \lfloor \frac{a}{b} \rfloor$ (replace $a$ with the integer part of the division between $a$ and $b$)
- $b=b+1$ (increase $b$ by $1$)
Find the minimum number of operations required to make $a=0$. | Suppose that you can use $x$ operations of type $1$ and $y$ operations of type $2$. Try to reorder the operations in such a way that $a$ becomes the minimum possible. You should use operations of type $2$ first, then moves of type $1$. How many operations do you need in the worst case? ($a = 10^9$, $b = 1$) You need at... | [
"brute force",
"greedy",
"math",
"number theory"
] | 1,000 | #include <iostream>
using namespace std;
void solve(){
long long A,B,a,b,res,i,ans;
cin>>A>>B;
if(!A){
cout<<0<<endl;
return;
}
res=A+3;
for(i=(B<2?2-B:0); i<res; ++i){
b=B+i;
a=A;
ans=i;
while(a){
a/=b;
++ans;
}
if(ans<res)res=ans;
}
cout<<res<<endl;
}
int main(){
int t;
cin>>t;
... |
1485 | B | Replace and Keep Sorted | Given a positive integer $k$, two arrays are called $k$-similar if:
- they are \textbf{strictly increasing};
- they have the same length;
- all their elements are positive integers between $1$ and $k$ (inclusive);
- they differ in \textbf{exactly} one position.
You are given an integer $k$, a \textbf{strictly increas... | You can make a $k$-similar array by assigning $a_i = x$ for some $l \leq i \leq r$ and $1 \leq x \leq k$. How many $k$-similar arrays can you make if $x$ is already equal to some $a_i$ ($l \leq i \leq r$)? How many $k$-similar arrays can you make if either $x < a_l$ or $x > a_r$? How many $k$-similar arrays can you mak... | [
"dp",
"implementation",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main(){
cin.tie(0);
ios_base::sync_with_stdio(NULL);
int N,Q,K;
cin >> N >> Q >> K;
vector<int> v(N);
for(int &x: v)cin >> x;
int l,r;
while(Q--){
cin >> l >> r;
cout << K + v[r-1] - v[l-1] - 2*(r - l) - 1 << "\n";
}
return 0;
} |
1485 | C | Floor and Mod | A pair of positive integers $(a,b)$ is called \textbf{special} if $\lfloor \frac{a}{b} \rfloor = a \bmod b$. Here, $\lfloor \frac{a}{b} \rfloor$ is the result of the integer division between $a$ and $b$, while $a \bmod b$ is its remainder.
You are given two integers $x$ and $y$. Find the number of special pairs $(a,b)... | Let $\lfloor \frac{a}{b} \rfloor = a~\mathrm{mod}~b = k$. Is there an upper bound for $k$? $k \leq \sqrt x$. For a fixed $k$, can you count the number of special pairs such that $a \leq x$ and $b \leq y$ in $O(1)$? We can notice that, if $\lfloor \frac{a}{b} \rfloor = a~\mathrm{mod}~b = k$, then $a$ can be written as $... | [
"binary search",
"brute force",
"math",
"number theory"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(){
ll x, y;
cin >> x >> y;
ll ans = 0;
for(ll i = 1; i*i < x; i++)ans+=max(min(y,x/i-1)-i,0LL);
cout << ans << endl;
return;
}
int main(){
int T = 1;
cin >> T;
while(T--){
solve();
}
return 0;
} |
1485 | D | Multiples and Power Differences | You are given a matrix $a$ consisting of positive integers. It has $n$ rows and $m$ columns.
Construct a matrix $b$ consisting of positive integers. It should have the same size as $a$, and the following conditions should be met:
- $1 \le b_{i,j} \le 10^6$;
- $b_{i,j}$ is a multiple of $a_{i,j}$;
- the absolute value... | Brute force doesn't work (even if you optimize it): there are relatively few solutions. There may be very few possible values of $b_{i,j}$, if $b_{i-1,j}$ is fixed. The problem arises when you have to find a value for a cell with, e.g., $4$ fixed neighbors. Try to find a possible property of the neighbors of $(i, j)$, ... | [
"constructive algorithms",
"graphs",
"math",
"number theory"
] | 2,200 | #include <iostream>
using namespace std;
int main(){
unsigned h,w,x,y,t;
cin>>h>>w;
for(y=0; y<h; ++y){
for(x=0; x<w; ++x){
cin>>t;
if((x^y)&1)
cout<<"720720 ";
else cout<<720720+t*t*t*t<<' ';
}
cout<<'\n';
}
return 0;
} |
1485 | E | Move and Swap | You are given $n - 1$ integers $a_2, \dots, a_n$ and a tree with $n$ vertices rooted at vertex $1$. The leaves are all at the same distance $d$ from the root.
Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All... | What happens if you can't swap coins? Let $dp_i$ be the maximum score that you can reach after $dist(1, i)$ moves if there is a red coin on node $i$ after step $3$. However, after step $2$, the coin on node $i$ may be either red or blue. Try to find transitions for both cases. If you consider only the first case, you s... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
#define INF (ll)1e18
ll i, i1, j, k, k1, t, n, m, res, check1, a[200010], a1, b, d, v, dist[200010], dp[200010], s, s1, s2;
vector<ll> adj[200010];
vector<array<ll, 3>> dadj[200010];
bool visited[200010];
void dfs(ll s) {
for... |
1485 | F | Copy or Prefix Sum | You are given an array of integers $b_1, b_2, \ldots, b_n$.
An array $a_1, a_2, \ldots, a_n$ of integers is \textbf{hybrid} if for each $i$ ($1 \leq i \leq n$) at least one of these conditions is true:
- $b_i = a_i$, or
- $b_i = \sum_{j=1}^{i} a_j$.
Find the number of hybrid arrays $a_1, a_2, \ldots, a_n$. As the re... | Why isn't the answer $2^{n-1}$? What would you overcount? Find a dp with time complexity $O(n^2\log n)$. Let $dp_{i, j}$ be the number of hybrid prefixes of length $i$ and sum $j$. The transitions are $dp_{i, j} \rightarrow dp_{i+1, j+b_i}$ and $dp_{i,j} \rightarrow dp_{i+1,b_i}$. Can you optimize it to $O(n\log n)$? F... | [
"combinatorics",
"data structures",
"dp",
"sortings"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
#define nl "\n"
#define nf endl
#define ll long long
#define pb push_back
#define _ << ' ' <<
#define INF (ll)1e18
#define mod 1000000007
#define maxn 200010
ll i, i1, j, k, k1, t, n, m, res, flag[10], a, b[maxn], tt;
map<ll, ll> mp;
int main() {
ios::sync_with_... |
1486 | A | Shifting Stacks | You have $n$ stacks of blocks. The $i$-th stack contains $h_i$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $i$-th stack (if there is at least one block) and put it to the $i + 1$-th stack. Can you make the sequence of heights strictly increasing?
Note that the number... | What's the lower bound for the amount of blocks for the answer to be $\texttt{YES}$? Check the predicate for every prefix. Let's consider the smallest amount of blocks we need to make the first $i$ heights ascending. As heights are non-negative and ascending the heights should look like $0, 1, 2, 3, ..., i - 1$, so the... | [
"greedy",
"implementation"
] | 900 | t = int(input())
for i in range(t):
n = int(input())
need = 0
have = 0
ans = True
a = [int(i) for i in input().split()]
for j in range(n):
need += j
have += a[j]
if have < need:
ans = False
if ans:
print("YES")
else:
print("NO") |
1486 | B | Eastern Exhibition | You and your friends live in $n$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with inte... | Is problem really two dimensional? How to solve the problem if $y = 0$? At first let's see that the problem is not two dimensional. If we change the $x$ coordinate the sum of distances by $y$ is not changed at all. So we just need to calculate the number of good points on a line with points having coordinates $x$ and t... | [
"binary search",
"geometry",
"shortest paths",
"sortings"
] | 1,500 | t = int(input())
def solve(x):
x.sort()
return x[len(x) // 2] - x[(len(x) - 1) // 2] + 1
for i in range(t):
n = int(input())
x, y = [], []
for j in range(n):
px, py = map(int, input().split())
x.append(px)
y.append(py)
print(solve(x) * solve(y)) |
1486 | C1 | Guessing the Greatest (easy version) | \textbf{The only difference between the easy and the hard version is the limit to the number of queries}.
\textbf{This is an interactive problem.}
There is an array $a$ of $n$ \textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position o... | Binary search? How to check if the maximum element is in the left or the right part of the array in two queries? Let's solve for some subsegment $[l, r)$ and $mid = (l + r) / 2$. Now let's check if the max element is in $[l, mid)$ or $[mid, r)$. Let's find the second max element in $[l, r)$ and call it $smax$. Now let'... | [
"binary search",
"interactive"
] | 1,600 | from sys import stdout
def ask(l, r):
if l == r:
return -1
print('?', l, r)
stdout.flush()
return int(input())
l = 1
r = int(input()) + 1
while r - l > 1:
mid = (r + l) // 2
was = ask(l, r - 1)
if was < mid:
if ask(l, mid - 1) == was:
r = mid
else:
... |
1486 | C2 | Guessing the Greatest (hard version) | \textbf{The only difference between the easy and the hard version is the limit to the number of queries}.
\textbf{This is an interactive problem.}
There is an array $a$ of $n$ \textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position o... | Kudos to Aleks5d for proposing a solution to this subproblem. Binary search AGAIN? How to solve the problem if the second maximum element is at position $1$? How to check if the maximum element is to the left or the right of the second maximum in two queries? Let's find second max $smax$. Now let's check if the max ele... | [
"binary search",
"interactive"
] | 1,900 | from sys import stdout
def ask(l, r):
if l == r:
return -1
print('?', l, r)
stdout.flush()
return int(input())
n = int(input())
smax = ask(1, n)
if smax == 1 or ask(1, smax) != smax:
l = smax
r = n
while r - l > 1:
mid = (l + r) // 2
if ask(smax, mid) == smax:
... |
1486 | D | Max Median | You are a given an array $a$ of length $n$. Find a subarray $a[l..r]$ with length at least $k$ with the largest median.
A median in an array of length $n$ is an element which occupies position number $\lfloor \frac{n + 1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example: $median([1, 2, 3, 4]... | How to solve the problem if all the values are $-1$ and $1$? Binary search ONCE MORE? How to check if the answer is at least $x$? Let's binary search the answer. Now let's check if the answer is at least $x$. Replace all values that are at least $x$ with 1 and values that are less than $x$ with $-1$. Now if for some se... | [
"binary search",
"data structures",
"dp"
] | 2,100 | n, k = map(int, input().split())
a = [int(i) for i in input().split()]
l = 1
r = n + 1
while r - l > 1:
mid = (r + l) // 2
b = [1 if i >= mid else -1 for i in a]
for i in range(1, len(b)):
b[i] += b[i - 1]
ans = False
if b[k - 1] > 0:
ans = True
mn = 0
for i in range(k, len(b... |
1486 | E | Paired Payment | There are $n$ cities and $m$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph \textbf{is not guaranteed to be connected}. Each road has it's own parameter $w$. You can travel through the roads, but the government made a new law: you can only go through two roads ... | Did you read that $w$ is at most $50$? How to change the graph for dijkstra algorithm to work with this rule? Add some fake vertices and edges to make things work. Let's think about it this way. For a middle vertex we only care what are the weights of the edges that pass through it. Now for every vertex $v$ let's creat... | [
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> G(n * 51);
auto addedge = [&](int u, int v, int w) {
G[u * 51].push_back({v * 51 + w, 0});
for (int was... |
1486 | F | Pairs of Paths | You are given a tree consisting of $n$ vertices, and $m$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $(i, j)$ $(1 \leq i < j \leq m)$ such that $path_i$ and $path_j$ have exactly one vertex in common. | Root the tree. After rooting the tree, how does the intersection of two paths look? After rooting the tree, what are the two types of intersection? Let's root the tree at some vertex. Now the intersection vertex is lca for at least one path. If the vertex wasn't lca for both paths it would mean that there are either tw... | [
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define FIXED cout << fixed << setprecision(12)
#define ll long long
#define pii pair<int, int>
#define graph vector<vector<int>>
#define pb push_back
#define f first
#define s second
#define sz(a) signed(... |
1487 | A | Arena | $n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$.
Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (\textbf{it's even possible that it is the same two heroes that were fighting during the last minute}).
When two heroes of equa... | If for some hero $i$, no other hero is weaker than $i$, then the $i$-th hero cannot win any fights and is not a possible winner. Otherwise, the hero $i$ is a possible winner - he may fight the weakest hero $100^{500}$ times and be declared the winner. So the solution to the problem is calculating the number of minimum ... | [
"implementation",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
cout << n - count(a.begin(), a.end(), *min_element(a.begin(), a.end())) << endl;
}
} |
1487 | B | Cat Cycle | Suppose you are living with two cats: A and B. There are $n$ napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
- Cat A changes its napping place in order: $n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$ In other wor... | If $n$ is even, then each hour A and B are on the spots with different parity, so they will never meet. Otherwise, let's look closely what happens. At the start, A in $n$ and B in $1$. But since we can form a cycle from spots then it means that $n$ and $1$ in reality are neighbors. After that, A and B (starting from ne... | [
"math",
"number theory"
] | 1,200 | fun main() {
repeat(readLine()!!.toInt()) {
var (n, k) = readLine()!!.split(' ').map { it.toInt() }
k--
val floor = n / 2
println((k + (n % 2) * k / floor) % n + 1)
}
} |
1487 | C | Minimum Ties | A big football championship will occur soon! $n$ teams will compete in it, and each pair of teams will play exactly one game against each other.
There are two possible outcomes of a game:
- the game may result in a tie, then both teams get $1$ point;
- one team might win in a game, then the winning team gets $3$ poin... | If $n$ is odd, then we can solve the problem without any ties: each team should win exactly $\lfloor\frac{n}{2}\rfloor$ matches and lose the same number of matches. Finding which matches each team wins and which matches each team loses can be done with some graph algorithms (like Eulerian cycles or circulations), or wi... | [
"brute force",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"implementation",
"math"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int n;
cin >> n;
if(n % 2 == 1)
{
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(j - i <= n / 2)
... |
1487 | D | Pythagorean Triples | A Pythagorean triple is a triple of integer numbers $(a, b, c)$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $a$, $b$ and $c$, respectively. An example of the Pythagorean triple is $(3, 4, 5)$.
Vasya studies the properties of ... | We have to find the number of triples ($a, b, c$) such that equations $a^2+b^2=c^2$ and $a^2-b=c$ are satisfied. Let's subtract one equation from another and get that $b^2+b=c^2-c \implies b(b+1)=c(c-1)$. So we know that $c=b+1$ and after substituting, we get that $a^2=2b+1$. We can see that there is only one correct v... | [
"binary search",
"brute force",
"math",
"number theory"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int ans = 0;
for (int i = 3; i * i <= 2 * n - 1; i += 2)
++ans;
cout << ans << '\n';
}
} |
1487 | E | Cheap Dinner | Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.
There are $n_1$ different types of first courses Ivan can buy (the $i$-th of them costs $a_i$ coins), $n_2$ different types of second courses (the $i$-th of them costs $b_i$ coins), $n_3$ differen... | The main solution is dynamic programming: let $dp_i$ for every possible dish $i$ be the minimum cost to assemble a prefix of a dinner ending with the dish $i$ (here, $i$ can be a dish of any type: first course, second course, drink, or dessert). Then, the answer to the problem is the minimum value among all desserts. T... | [
"brute force",
"data structures",
"graphs",
"greedy",
"implementation",
"sortings",
"two pointers"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> ns(4);
for(int i = 0; i < 4; i++)
scanf("%d", &ns[i]);
vector<vector<int>> cs(4);
for(int i = 0; i < 4; i++)
{
cs[i].resize(ns[i]);
for(int j = 0; j < ns[i]; j++)
scanf("%d", &cs[i][j]);
... |
1487 | F | Ones | You are given a positive (greater than zero) integer $n$.
You have to represent $n$ as the sum of integers (possibly negative) consisting only of ones (digits '1'). For example, $24 = 11 + 11 + 1 + 1$ and $102 = 111 - 11 + 1 + 1$.
Among all possible representations, you have to find the one that uses the minimum numb... | Let's build the number from the lowest digit to the highest digit with the following dynamic programming: $dp_{i,carry,cp,cn}$ - the minimum number of ones, if $i$ least significant digits are already fixed, the carry to the next digit is $carry$ (can be negative), there are $cp$ positive numbers (of the form $111 \cdo... | [
"dp",
"greedy",
"shortest paths"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 250;
const int M = 28;
const int INF = 1e9;
int dp[2][M * 2 + 1][N][N];
int main() {
string s;
cin >> s;
reverse(s.begin(), s.end());
s += "0";
forn(carry, M * ... |
1487 | G | String Counting | You have $c_1$ letters 'a', $c_2$ letters 'b', ..., $c_{26}$ letters 'z'. You want to build a beautiful string of length $n$ from them (obviously, you cannot use the $i$-th letter more than $c_i$ times). \textbf{Each $c_i$ is greater than $\frac{n}{3}$}.
A string is called beautiful if there are no palindromic contigu... | Suppose there is no constraint on the number of letters used. Then this problem can be solved with the following dynamic programming: let $dp_{i, j, k}$ be the number of strings of length $i$ ending with characters $j$ and $k$ that don't contain palindromes of odd length greater than $1$ (obviously, each forbidden pali... | [
"combinatorics",
"dp",
"fft",
"math"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 402;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int sub(int x, int y)
{
return add(x, -y);
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int c[2... |
1490 | A | Dense Array | Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $i$ ($1 \le i \le n-1$), this condition must be satisfied: $$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$
For example, the arrays $[1, 2, 3, 4, 3]$, $[1, 1, 1]$ and ... | Note that adding elements between positions $i$ ($1 \le i \le n - 1$) and $i + 1$ will not change the ratio of the adjacent elements, except for the ones just added. Therefore, for each pair of adjacent numbers, the problem can be solved independently. Let us solve the problem for a adjacent pair of numbers $a_i$ and $... | [
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
int last;
cin >> last;
int ans = 0;
for (int i = 1; i < n; i++) {
int nw;
cin >> nw;
int a = min(last, nw), b = max(last, nw);
while (a * 2 < b) {
ans++;
a *= 2;
}
last =... |
1490 | B | Balanced Remainders | You are given a number $n$ (\textbf{divisible by $3$}) and an array $a[1 \dots n]$. In one move, you can increase any of the array elements by one. Formally, you choose the index $i$ ($1 \le i \le n$) and \textbf{replace} $a_i$ with $a_i + 1$. You can choose the same index $i$ multiple times for different moves.
Let's... | Note that the numbers in the $a$ array are not important to us, so initially we will calculate the values of $c_0$, $c_1$, $c_2$. Now applying a move for the number $a_i$ is equivalent to: decreasing $c_{a_i\ mod\ 3}$ by $1$; and increasing $c_{(a_i + 1)\ mod\ 3}$ by $1$; We will perform the following greedy algorithm:... | [
"brute force",
"constructive algorithms",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
int res = 0;
vector<int> cnt(3);
for (int x = 0; x <= 2; x++) {
for (int i = 0; i < n; i++) {
if (a[i] % 3 == x) {
cnt[x]++;
}
... |
1490 | C | Sum of Cubes | You are given a positive integer $x$. Check whether the number $x$ is representable as the sum of the cubes of two positive integers.
Formally, you need to check if there are two integers $a$ and $b$ ($1 \le a, b$) such that $a^3+b^3=x$.
For example, if $x = 35$, then the numbers $a=2$ and $b=3$ are suitable ($2^3+3^... | In this problem, we need to find $a$ and $b$ such that $x=a^3+b^3$ and $a \ge 1, b \ge 1$. Since $a$ and $b$ are positive, $a^3$ and $b^3$ are also positive. Hence $a^3 \le a^3 + b^3 \le x$. Therefore, the number $a$ can be iterated from $1$ to $\sqrt[3]{x}$. Since in all tests $x \le 10^{12}$, then $a \le 10^4$. For e... | [
"binary search",
"brute force",
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const ll N = 1'000'000'000'000L;
unordered_set<ll> cubes;
void precalc() {
for (ll i = 1; i * i * i <= N; i++) {
cubes.insert(i * i * i);
}
}
void solve() {
ll x;
cin >> x;
for (ll i = 1; i * i * i <= x; i++) ... |
1490 | D | Permutation Transformation | A permutation — is a sequence of length $n$ integers from $1$ to $n$, in which all the numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ — permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ — no.
Polycarp was recently gifted a permutation $a[1 \dots n]$ of length $n$. Polycarp likes trees m... | We will construct the required tree recursively. Let us describe the state of tree construction by three values $(l, r, d)$, where $[l, r]$ - is the segment of the permutation, and $d$ - is the current depth. Then the following transitions can be described: find the position $m$ of the maximum element on the segment $[... | [
"dfs and similar",
"divide and conquer",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void build(int l, int r, vector<int> const &a, vector<int> &d, int curD = 0) {
if (r < l) {
return;
}
if (l == r) {
d[l] = curD;
return;
}
int m = l;
for (int i = l + 1; i <= r; i++) {
if (a[m] < a[i]) {
m = i;
}
}
d[m] = curD;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.