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 ⌀ |
|---|---|---|---|---|---|---|---|
1265 | E | Beautiful Mirrors | Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$.
Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he as... | Let $p_i$ be the probability that the $i$-th mirror will answer YES when it is asked. That is, this $p_i$ equals to $p_i$ in the problem statement divide by 100. Let $e_i$ be the expected number of days until Creatnx becomes happy when initially he is at the $i$-th mirror. For convenient, let $e_{n+1} = 0$ (because whe... | [
"data structures",
"dp",
"math",
"probabilities"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 119 << 23 | 1;
int inv(int a) {
int r = 1, t = a, k = MOD - 2;
while (k) {
if (k & 1) r = (long long) r * t % MOD;
t = (long long) t * t % MOD;
k >>= 1;
}
return r;
}
int main() {
int n; cin >> n;
vector<int... |
1266 | A | Competitive Programmer | Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $n$ of them how much effort they needed to reach red.
"Oh, I just spent $x_i$ \textbf{hours} solving problems", said the $i$-th of them.
Bob wants to train h... | Thanks to Chinese remainder theorem, a number is divisible by $60$ if and only if it is divisible by $3$ and $20$. A number is divisible by $3$ if and only if the sum of its digits is divisible by $3$. Note that as the sum doesn't change if we reorder digits, it applies also to the sum of digits of $s$. A number is div... | [
"chinese remainder theorem",
"math"
] | 1,000 | null |
1266 | B | Dice Tower | Bob is playing with $6$-sided dice. A net of such standard cube is shown below.
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For examp... | Consider a die other than the top-most one. As the sum of numbers on the opposite faces of a die is always $7$, the sum of numbers on the visible faces is always $14$, regardless of its orientation. For the top-most die, the numbers on the sides also add up to $14$, and there is an additional number on top of the die. ... | [
"constructive algorithms",
"math"
] | 1,000 | null |
1266 | C | Diverse Matrix | Let $a$ be a matrix of size $r \times c$ containing positive integers, not necessarily distinct. Rows of the matrix are numbered from $1$ to $r$, columns are numbered from $1$ to $c$. We can construct an array $b$ consisting of $r + c$ integers as follows: for each $i \in [1, r]$, let $b_i$ be the greatest common divis... | As the example reveals, the case when $r = c = 1$ is impossible. It turns out that this is the only impossible case. We will prove this by providing a construction that always achieves a magnitude of $r + c$. If $r = 1$, one optimal solution is $A = (2, 3, \dots, c+1)$. The case where $c = 1$ is similar. Assume $r, c \... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,400 | null |
1266 | D | Decreasing Debts | There are $n$ people in this world, conveniently numbered $1$ through $n$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $d(a,... | Consider a solution which minimises the total debt. Assume for contradiction that there is a triple of vertices $u \neq v \neq w$, such that $d(u,v) > 0$ and $d(v,w) > 0$. We can use the first rule with $a = u$, $b = c = v$, $d = w$ and $z = min(d(u,v), d(v,w))$ and then the second rule with $a = v$ and the same $z$. W... | [
"constructive algorithms",
"data structures",
"graphs",
"greedy",
"implementation",
"math",
"two pointers"
] | 2,000 | null |
1266 | E | Spaceship Solitaire | Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are $n$ types of resources, numbered $1$ through $n$. Bob needs at least $a_i$ pieces of the $i$-th resource to build the spaceship.... | Consider a fixed game. Let $m_i$ be the total number of milestones having $u_j = i$, that is, the maximum possible number of "free" units of resource $i$ that can be obtained. We claim that in optimal solution, we (manually) produce this resource exactly $p_i = \max\left(a_i - m_i, 0\right)$ times. It is obvious that w... | [
"data structures",
"greedy",
"implementation"
] | 2,100 | null |
1266 | F | Almost Same Distance | Let $G$ be a simple graph. Let $W$ be a non-empty subset of vertices. Then $W$ is \textbf{almost-$k$-uniform} if for each pair of distinct vertices $u,v \in W$ the distance between $u$ and $v$ is either $k$ or $k+1$.
You are given a tree on $n$ vertices. For each $i$ between $1$ and $n$, find the maximum size of an al... | There are three cases of how an almost-$k$-uniform set looks like depending on the value of $k$. The first case is when $k = 1$. In this case, any maximal almost-$1$-uniform set is a vertex plus all of its neighbours. We can simply check each vertex and find the one with the highest degree. The second case is when $k$ ... | [
"dfs and similar",
"graphs"
] | 2,900 | null |
1266 | G | Permutation Concatenation | Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $P$. For example, if $n = 3$, then $P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence is $n \cdot n!$.
Let $1 \leq i \leq j \leq n \cdot n!$ ... | Let $LCP$ be the longest-common-prefix array associated with a suffix tree of the sequence $p$. The answer is $|p| \cdot (|p| + 1) - \sum_{i=1}^{p} LCP[i]$. Let's calculate $c_i$ - the number of positions for which $LCP[j] = i$. The following holds: $c_0 = n$ $c_i = \frac{n!}{(n-i+1)!} * ((n-i) * (n-i) + 1)$ for all $i... | [
"string suffix structures"
] | 3,300 | null |
1266 | H | Red-Blue Graph | There is a directed graph on $n$ vertices numbered $1$ through $n$ where each vertex (except $n$) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex $1$. In one second, the vertex with t... | Consider a fixed query $\{s_i\}_{i=1}^{n-1}$ and $v$. Let $x_i$ be the number of times the red arc from $i$ was traversed, and $y_i$ the number of times the blue arc was traversed. The answer for a given query, should the $x_i$ and $y_i$ exist, is the sum of all of them. Let's try to find these values. When the blue ar... | [
"dp",
"graphs",
"math",
"matrices",
"meet-in-the-middle"
] | 3,400 | null |
1268 | A | Long Beautiful Integer | You are given an integer $x$ of $n$ digits $a_1, a_2, \ldots, a_n$, which make up its decimal notation in order from left to right.
Also, you are given a positive integer $k < n$.
Let's call integer $b_1, b_2, \ldots, b_m$ \textbf{beautiful} if $b_i = b_{i+k}$ for each $i$, such that $1 \leq i \leq m - k$.
You need ... | At first, let's set $a_i=a_{i-k}$ for all $i>k$. If it is at least the initial $a$, then you can print it as the answer. Otherwise, Let's find the last non-nine digit among the first $k$, increase it by one, and change all $9$'s on the segment from it to $k$-th character to $0$. After that, again set $a_i = a_{i-k}$ fo... | [
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | 1,700 | null |
1268 | B | Domino for Young | You are given a Young diagram.
Given diagram is a histogram with $n$ columns of lengths $a_1, a_2, \ldots, a_n$ ($a_1 \geq a_2 \geq \ldots \geq a_n \geq 1$).
\begin{center}
{\small Young diagram for $a=[3,2,2,2,1]$.}
\end{center}
Your goal is to find the largest number of non-overlapping dominos that you can draw in... | Let's color diagram into two colors as a chessboard. I claim that the Young diagram can be partitioned into domino if and only if the number of white cells inside it is equal to the number of black cells inside it. If the Young diagram has two equal rows (or columns) you can delete one domino, and the diagram will stil... | [
"dp",
"greedy",
"math"
] | 2,000 | null |
1268 | C | K Integers | You are given a permutation $p_1, p_2, \ldots, p_n$.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\ldots, k$, in other words in the end there should be an integer $i$, $1 \leq i \leq n-k+1$ such that $p_i = 1, p_{i... | At first, let's add to the answer number of inversions among numbers $1,2,\ldots,k$. After that, let's say that $x \leq k$ is one, and $x > k$ is zero. Then you need to calculate the smallest number of swaps to make segment $1,1,\ldots,1$ of length $k$ appear in the permutation. For this, let's call $p_i$ the number of... | [
"binary search",
"data structures"
] | 2,300 | null |
1268 | D | Invertation in Tournament | You are given a tournament — complete directed graph.
In one operation you can pick any vertex $v$ and change the direction of all edges with $v$ on one of the ends (i.e all edges $u \to v$ change their orientation to $v \to u$ and vice versa).
You want to make the tournament strongly connected with the smallest poss... | Lemma: for $n>6$ it is always possible to invert one vertex. Start by proving that for $n \geq 4$ in the strongly connected tournament it is possible to invert one vertex so it will remain strongly connected, it is possible by induction. If there is a big SCC (with at least four vertices), invert good vertex in it. If ... | [
"brute force",
"divide and conquer",
"graphs",
"math"
] | 3,200 | null |
1268 | E | Happy Cactus | You are given a cactus graph, in this graph each edge lies on at most one simple cycle.
It is given as $m$ edges $a_i, b_i$, weight of $i$-th edge is $i$.
Let's call a path in cactus \textbf{increasing} if the weights of edges on this path are increasing.
Let's call a pair of vertices $(u,v)$ \textbf{happy} if there... | At first, let's solve for the tree. Let $dp_v$ be the number of answer for vertex $v$. Let's look at edges in the order of decreasing weight. How $dp$ is changing when you are looking at edge $i$? I claim that $dp'_v = dp_v$ for $v \neq a_i$and $v \neq b_i$. And $dp'_{a_i} = dp'_{b_i} = dp_{a_i} + dp_{b_i}$. Why? I lik... | [
"dp"
] | 3,400 | null |
1269 | A | Equation | Let's call a positive integer \textbf{composite} if it has at least one divisor other than $1$ and itself. For example:
- the following numbers are composite: $1024$, $4$, $6$, $9$;
- the following numbers are not composite: $13$, $1$, $2$, $3$, $37$.
You are given a positive integer $n$. Find two composite integers ... | Print $9n$ and $8n$. | [
"brute force",
"math"
] | 800 | null |
1269 | B | Modulo Equality | You are given a positive integer $m$ and two integer sequence: $a=[a_1, a_2, \ldots, a_n]$ and $b=[b_1, b_2, \ldots, b_n]$. Both of these sequence have a length $n$.
Permutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6... | There exists some $i$, such that $(a_i + x) \bmod m = b_1$. Let's enumerate it, then $x$ is $(b_1 - a_i) \bmod m$. Like that you can get $O(n)$ candidates, each of them can be checked in $O(n \log n)$ with sort or in $O(n)$ if you will note that the order is just cyclically shifting. Also, this problem can be solved in... | [
"brute force",
"sortings"
] | 1,500 | null |
1270 | A | Card Game | Two players decided to play one interesting card game.
There is a deck of $n$ cards, with values from $1$ to $n$. The values of cards are \textbf{pairwise different} (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that ea... | We can show that the player who has the largest card (the one with value $n$) has the winning strategy! Indeed, if a player has the card with value $n$, he can choose to play it every time, taking the card from the opponent every time (as every other card has a value smaller than $n$). In at most $n-1$ moves, the oppon... | [
"games",
"greedy",
"math"
] | 800 | "#include <bits/stdc++.h>\nusing namespace std;\n\n\nvoid solve()\n{\n int n, k1, k2;\n cin >> n >> k1 >> k2;\n \n vector<int> a(n);\n for (int i = 0; i<n; i++) cin>>a[i];\n for (int i = 0; i < k1; i++) \n {\n if (a[i] == n) {\n cout << \"YES\"<<endl;\n return;\n ... |
1270 | B | Interesting Subarray | For an array $a$ of integers let's denote its maximal element as $\max(a)$, and minimal as $\min(a)$. We will call an array $a$ of $k$ integers \textbf{interesting} if $\max(a) - \min(a) \ge k$. For example, array $[1, 3, 4, 3]$ isn't interesting as $\max(a) - \min(a) = 4 - 1 = 3 < 4$ while array $[7, 3, 0, 4, 3]$ is a... | We will show that if some interesting nonempty subarray exists, then also exists some interesting subarray of length $2$. Indeed, let $a[l..r]$ be some interesting nonempty subarray, let $a_{max}$ be the maximal element, $a_{min}$ - minimal, without loss of generality, $max > min$. Then $a_{max} - a_{min} \ge r - l + 1... | [
"constructive algorithms",
"greedy",
"math"
] | 1,200 | "#ifdef DEBUG\n#define _GLIBCXX_DEBUG\n#endif\n#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nconst int maxN = (int)3e5 + 100;\nint a[maxN];\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n //freopen(\"input.t... |
1270 | C | Make Good | Let's call an array $a_1, a_2, \dots, a_m$ of nonnegative integer numbers \textbf{good} if $a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$, where $\oplus$ denotes the bitwise XOR operation.
For example, array $[1, 2, 3, 6]$ is good, as $1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplu... | Let the sum of numbers be $S$, and their $\oplus$ be $X$. Solution 1: If $S\le 2X$ and $S$ was even, it would be enough to add into the array $2$ numbers $\frac{2X-S}{2}, \frac{2X-S}{2}$: $X$ wouldn't change, and the sum would become $2X$. How to achieve this? Let's add to the array number $2^{50} + (S\bmod 2)$. If new... | [
"bitmasks",
"constructive algorithms",
"math"
] | 1,400 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve()\n{\n int n;\n cin>>n;\n int temp;\n ll Sum = 0;\n ll Xor = 0;\n for (int i = 0; i<n; i++)\n {\n cin>>temp;\n Sum+=temp;\n Xor^=temp;\n }\n vector<ll> answer;\n ll good = (1ll<<50... |
1270 | D | Strange Device | \textbf{This problem is interactive}.
We have hidden an array $a$ of $n$ \textbf{pairwise different} numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon.
This device can answer queries of the following form: in response to the... | We will show how to guess $m$ with $k+1\le n$ queries. Let's leave only first $k+1$ elements of the array. We will ask $k+1$ queries: $i$-th question - about all elements from $1$-th to $k+1$-th, except $i$-th. Denote elements from $1$-th to $k+1$-th in decreasing order as $b_1 < b_2 < \dots < b_{k+1}$. Then, if we thr... | [
"constructive algorithms",
"interactive",
"math",
"sortings"
] | 1,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(nullptr);\n\n int n, k;\n cin>>n>>k;\n vector<int> elements;\n for (int i = 1; i<=k+1; i++)\n {\n cout<<\"? \";\n \n for (int j = 1; j<=k+1; j++) if (j!=i) cout<<j<<' ';\... |
1270 | E | Divide Points | You are given a set of $n\ge 2$ \textbf{pairwise different} points with integer coordinates. Your task is to partition these points into two \textbf{nonempty} groups $A$ and $B$, such that the following condition holds:
For every two points $P$ and $Q$, write the Euclidean distance between them on the blackboard: if t... | Let's divide all points into $4$ groups by parity of their coordinates: $A_{00}$ - (even, even), $A_{01}$ - (even, odd), $A_{10}$ -(odd, even), $A_{11}$ - (odd, odd). If all points belong to one group, for example, $A_{00}$, let's divide all coordinates by $2$ and start again. We just scaled down the image in $2$ times... | [
"constructive algorithms",
"geometry",
"math"
] | 2,300 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(nullptr);\n\n int n;\n cin>>n;\n vector<pair<int, int>> p(n);\n for (int i = 0; i<n; i++) {cin>>p[i].first>>p[i].second; p[i].first+=1e6; p[i].second+=1e6;}\n\n while (true)\n {\n v... |
1270 | F | Awesome Substrings | Let's call a binary string $s$ \textbf{awesome}, if it has at least $1$ symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are \textbf{awesome}, but 0, 110, 01010 aren't.
You are given a binary string $s$. Count the number of its \textbf{awesome} substrings.
A string ... | It will be easier for us to think that string is actually an array of ones and zeroes. Let's calculate array of preffix sums - $pref[]$. It's easy to see that, substring $[l;r]$ will be awesome, iff $r - l + 1 = k \cdot (pref[r] - pref[l - 1])$ for some integer $k$. It's equivalent to $r - k \cdot pref[r] = l - 1 - k \... | [
"math",
"strings"
] | 2,600 | "#define _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n/*\n#pragma GCC target (\"avx2\")\n#pragma GCC optimization (\"O3\")\n#pragma GCC optimization (\"unroll-loops\")*/\n\nusing namespace std;\n\n#define ll long long\n#define ld long double\n#define mp make_pair\n\n\nll solve1 (string s)\n{\n\n int n = s.size... |
1270 | G | Subset with Zero Sum | You are given $n$ integers $a_1, a_2, \dots, a_n$, such that for each $1\le i \le n$ holds $i-n\le a_i\le i-1$.
Find some nonempty subset of these integers, whose sum is equal to $0$. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find an... | Note that the condition $i-n \le a_i \le i-1$ is equivalent to $1 \le i - a_i \le n$. Let's build an oriented graph $G$ on $n$ nodes with the following principle: for each $i$ from $1$ to $n$, draw an oriented edge from vertex $i$ to vertex $i - a_i$. In this graph, there is an outgoing edge from every vertex, so it ha... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"math"
] | 2,700 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n int n;\n cin >> n;\n vector<int> a(n+1);\n for (int i = 1; i <= n; i++) cin >> a[i];\n vector<bool> visited(n+1);\n int cur = 1;\n while (!visited[cur])\n {\n visited[cur] = true;\n cur = cur - a[cur];\n }\n ... |
1270 | H | Number of Components | Suppose that we have an array of $n$ distinct numbers $a_1, a_2, \dots, a_n$. Let's build a graph on $n$ vertices as follows: for every pair of vertices $i < j$ let's connect $i$ and $j$ with an edge, if $a_i < a_j$. Let's define \textbf{weight} of the array to be the number of connected components in this graph. For e... | Firstly, note that all connected components form segments of sequential indexes. Indeed, let numbers $i$ and $j$ lie in one component and let's consider $i < x < j$. Because $i$ and $j$ lie in one component, there exists a path, which connects them: $v_1 = i, \ldots, v_t = j$, such that $v_k$ and $v_{k+1}$ are connecte... | [
"data structures"
] | 3,300 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass SegTree {\nprivate:\n int n;\n vector<int> val, cnt, lazy;\n \n void push(int x, int l, int r) {\n if (lazy[x] == 0) return;\n val[x] += lazy[x];\n if (l != r) {\n lazy[x * 2] += lazy[x];\n lazy[x * 2 + 1] ... |
1270 | I | Xor on Figures | There is given an integer $k$ and a grid $2^k \times 2^k$ with some numbers written in its cells, cell $(i, j)$ initially contains number $a_{ij}$. Grid is considered to be a torus, that is, the cell to the right of $(i, 2^k)$ is $(i, 1)$, the cell below the $(2^k, i)$ is $(1, i)$ There is also given a lattice figure $... | Let's fix first cell of fiqure - $(x_1, y_1)$. Then if figure is lied in a such way, that first cell will be cell $(p,q)$ of the original board, other figure cells will be in the cells $(a + x_i - x_1, b + y_i - y_1)$ of the original board. Let's name such shifts $(x_i - x_1, y_i - y_1)$ as $(c_i, d_i)$. Then let's com... | [
"constructive algorithms",
"fft",
"math"
] | 3,500 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define ll long long\n#define mp make_pair \n\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(nullptr);\n\n int k;\n cin>>k;\n int n = 1<<k;\n vector<vector<ll>> a(n, vector<ll>(n));\n for (int i = 0; i<n; i++)\n for (int j = 0; j<... |
1271 | A | Suits | A new delivery of clothing has arrived today to the clothing store. This delivery consists of $a$ ties, $b$ scarves, $c$ vests and $d$ jackets.
The store does not sell single clothing items — instead, it sells suits of two types:
- a suit of the first type consists of one tie and one jacket;
- a suit of the second ty... | There are two ways to approach this problem. The first way is to iterate on the number of suits of one type that we will compose and calculate the number of suits of the second type we can compose from the remaining items. The second way is to use the fact that if $e > f$, then we have to make as many suits of the firs... | [
"brute force",
"greedy",
"math"
] | 800 | null |
1271 | B | Blocks | There are $n$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two \textbf{adjacent} blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequen... | Suppose we want to make all blocks white (if we want to make them black, the following algorithm still works with a few changes). The first block has to be white, so if it is black, we have to invert the pair $(1, 2)$ once, otherwise we should not invert it at all (inverting twice is the same as not inverting at all). ... | [
"greedy",
"math"
] | 1,300 | null |
1271 | C | Shawarma Tent | The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.
The main school of the capital is located in $(s_x,... | Suppose that the point $(t_x, t_y)$ is the answer. If the distance between this point $t$ and the school is greater than $1$, then there exists at least one point $(T_x, T_y)$ such that: the distance between $T$ and the school is exactly $1$; $T$ lies on the shortest path between the school and $t$. Now we claim that t... | [
"brute force",
"geometry",
"greedy",
"implementation"
] | 1,300 | null |
1271 | D | Portals | You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.
Let's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th c... | Note, that for every castle $i$ there is some list of castles $x$, such that you can defend castle $i$ standing in the castle $x$. The key observation is that it's always optimal to defend castle $i$ (assuming we decided to defend it) in the latest possible castle. Since it gives you more warriors in between of $i$ and... | [
"data structures",
"dp",
"greedy",
"implementation",
"sortings"
] | 2,100 | null |
1271 | E | Common Number | At first, let's define function $f(x)$ as follows: $$ \begin{matrix} f(x) & = & \left\{ \begin{matrix} \frac{x}{2} & \mbox{if } x \text{ is even} \\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} $$
We can see that if we choose some value $v$ and will apply function $f$ to it, then apply $f$ to $f(v)$, an... | Let's introduce a function $count(x)$ - the number of $y \in [1, n]$ such that $x \in path(y)$. The problem is now to find the greatest number $x$ such that $count(x) \ge k$. How can we calculate $count(x)$? First, let's consider the case when $x$ is odd. $x$ is contained in $path(x)$; then $x$ is contained in $path(2x... | [
"binary search",
"combinatorics",
"dp",
"math"
] | 2,100 | null |
1271 | F | Divide The Students | Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-y... | Suppose we have only students of types $1$, $4$, $6$ and $7$ (all students attend either all subjects or only one subject). We can divide these students into two subgroups in $O(1)$: the first subgroup can accomodate no more than $min(a_1, b_1, c_1)$ students of the first type; the second subgroup can accomodate no mor... | [
"brute force"
] | 2,700 | null |
1272 | A | Three Friends | Three friends are going to meet each other. Initially, the first friend stays at the position $x = a$, the second friend stays at the position $x = b$ and the third friend stays at the position $x = c$ on the coordinate axis $Ox$.
In one minute \textbf{each friend independently} from other friends can change the posit... | This problem can be solved with simple simulation. Let $na \in \{a - 1, a, a + 1\}$ be the new position of the first friend, $nb \in \{b - 1, b, b + 1\}$ and $nc \in \{c - 1, c, c + 1\}$ are new positions of the second and the third friends correspondingly. For the fixed positions you can update the answer with the val... | [
"brute force",
"greedy",
"math",
"sortings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int calc(int a, int b, int c) {
return abs(a - b) + abs(a - c) + abs(b - c);
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int a, b, c;
cin >> a >> b ... |
1272 | B | Snow Walking Robot | Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid.
You also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can m... | Let $cnt[L]$ be the number of occurrences of the character 'L' in the initial string, $cnt[R]$ - the number of occurrences of the character 'R', $cnt[U]$ and $cnt[D]$ are the same things for remaining characters. It is obvious that in every answer the number of 'L' equals the number of 'R' and the same for 'D' and 'U'.... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const string MOVES = "LRUD";
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
string s;
cin >> s;
map<char, int> cnt;
for (auto c : MOVES) cnt[c] = 0;
... |
1272 | C | Yet Another Broken Keyboard | Recently, Norge found a string $s = s_1 s_2 \ldots s_n$ consisting of $n$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $s$. Yes, all $\frac{n (n + 1)}{2}$ of them!
A substring of $s$ is a non-empty string $x = s[a \ldots b] = s_{a} s_{a + 1} \ldot... | Let's replace all characters of $s$ with zeros and ones (zero if the character is unavailable and one otherwise). Then we have the binary string and we have to calculate the number of contiguous segments of this string consisting only of ones. It can be done with two pointers approach. If we are staying at the position... | [
"combinatorics",
"dp",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
string s;
cin >> s;
set<char> st;
for (int i = 0; i < k; ++i) {
char c;
cin >> c;
st.insert(c);
}
long long ans = 0;
for... |
1272 | D | Remove One Element | You are given an array $a$ consisting of $n$ integers.
You can remove \textbf{at most one} element from this array. Thus, the final length of the array is $n-1$ or $n$.
Your task is to calculate the maximum possible length of the \textbf{strictly increasing} contiguous subarray of the remaining array.
Recall that th... | Firstly, let's calculate for each $i$ from $1$ to $n$ two following values: $r_i$ and $l_i$. $r_i$ means the maximum length of the increasing sequence starting in the position $i$, and $l_i$ means the maximum length of the increasing sequence ending in the position $i$. Initially, all $2n$ values are $1$ (the element i... | [
"brute force",
"dp"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int ans = 1;
vector<int> rg(n, 1);
for (int i = n - 2; i >= 0; --i) {
... |
1272 | E | Nearest Opposite Parity | You are given an array $a$ consisting of $n$ integers. In one move, you can jump from the position $i$ to the position $i - a_i$ (if $1 \le i - a_i$) or to the position $i + a_i$ (if $i + a_i \le n$).
For each position $i$ from $1$ to $n$ you want to know the minimum the number of moves required to reach any position ... | In this problem, we have directed graph consisting of $n$ vertices (indices of the array) and at most $2n-2$ edges. Some vertices have the value $0$, some have the value $1$. Our problem is to find for every vertex the nearest vertex having the opposite parity. Let's try to solve the problem for odd numbers and then ju... | [
"dfs and similar",
"graphs",
"shortest paths"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n;
vector<int> a;
vector<int> ans;
vector<vector<int>> g;
void bfs(const vector<int> &start, const vector<int> &end) {
vector<int> d(n, INF);
queue<int> q;
for (auto v : start) {
d[v] = 0;
q.push(v);
}
while (!q.empty()) {
int v = q.f... |
1272 | F | Two Bracket Sequences | You are given two bracket sequences (not necessarily regular) $s$ and $t$ consisting only of characters '(' and ')'. You want to construct the shortest \textbf{regular} bracket sequence that contains both given bracket sequences as \textbf{subsequences} (not necessarily contiguous).
Recall what is the regular bracket ... | Firstly, notice that the length of the answer cannot exceed $400$ ($200$ copies of ()). Now we can do some kind of simple dynamic programming. Let $dp_{i, j, bal}$ be the minimum possible length of the prefix of the regular bracket sequence if we are processed first $i$ characters of the first sequence, first $j$ chara... | [
"dp",
"strings",
"two pointers"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = 202;
const int INF = 1e9;
int dp[N][N][2 * N];
pair<pair<int, int>, pair<int, char>> p[N][N][2 * N];
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
string s, t;
cin >> s >> t;
int n = s.size... |
1276 | A | As Simple as One and Two | You are given a non-empty string $s=s_1s_2\dots s_n$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a \textbf{substring}. In other words, Polycarp does not like the string $s$ if there i... | Consider each occurrence of substrings one and two. Obviously, at least one character have to be deleted in such substrings. These substrings cannot intersect in any way, except for one case: twone. Thus, the answer is necessarily no less than the value $c_{21}+c_{1}+c_{2}$, where $c_{21}$ is the number of occurrences ... | [
"dp",
"greedy"
] | 1,400 | string s;
cin >> s;
vector<int> r;
for (string t: {"twone", "one", "two"}) {
for (size_t pos = 0; (pos = s.find(t, pos)) != string::npos;) {
s[pos + t.length() / 2] = '?';
r.push_back(pos + t.length() / 2);
}
}
cout << r.size() << endl;
for (auto rr: r)
cout << rr + 1 << " ";
cout << endl;
|
1276 | B | Two Fairs | There are $n$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $1$ to $n$.
Two fairs are currently taking place in Berland — they are held in two different cities $a$ and $b$ ($1 \le... | This problem has a simple linear solution (just two depth-first searches) without involving cut points, biconnected components, and other advanced techniques. Let's reformulate this problem in the language of graph theory: you are given an undirected graph and two vertices $a$ and $b$, you need to find the number of pa... | [
"combinatorics",
"dfs and similar",
"dsu",
"graphs"
] | 1,900 | void dfs(int u, int c) {
if (color[u] == 0) {
color[u] = c;
for (int v: g[u])
dfs(v, c);
}
}
vector<int> groups(int f) {
color = vector<int>(n);
color[f] = -1;
int c = 0;
forn(i, n)
if (i != f && color[i] == 0)
dfs(i, ++c);
return color;
}
//... |
1276 | C | Beautiful Rectangle | You are given $n$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $n$ numbers may not be chosen.
A rectangle (rectangular mat... | First, let's formulate the criteria that from the given set of numbers $x_1, x_2, \dots, x_k$ we can create a beautiful rectangle $a \times b$ (where $a \cdot b = k, a \le b$). Obviously, if some number occurs more than $a$ times, then among $a$ rows there will be such row that will contain two or more occurrences of t... | [
"brute force",
"combinatorics",
"constructive algorithms",
"data structures",
"greedy",
"math"
] | 2,300 | cout << best << endl << best_a << " " << best_b << endl;
vector<vector<int>> r(best_a, vector<int>(best_b));
int x = 0, y = 0;
for (int i = n; i >= 1; i–)
for (auto val: val_by_cnt[i])
forn(j, min(i, best_a)) {
if (r[x][y] != 0)
x = (x + 1) % best_a;
if (r[x][y] == 0... |
1276 | D | Tree Elimination | Vasya has a tree with $n$ vertices numbered from $1$ to $n$, and $n - 1$ edges numbered from $1$ to $n - 1$. Initially each vertex contains a token with the number of the vertex written on it.
Vasya plays a game. He considers all edges of the tree by increasing of their indices. For every edge he acts as follows:
- I... | First of all, counting different sequences is the same as counting the number of different playbacks of the elimination process (that is, different combinations of which token was removed on each step). Indeed, if we consider any resulting sequence, we can simulate the process and unambiguously determine which endpoint... | [
"dp",
"trees"
] | 2,900 | null |
1276 | E | Four Stones | There are four stones on an infinite line in integer coordinates $a_1, a_2, a_3, a_4$. The goal is to have the stones in coordinates $b_1, b_2, b_3, b_4$. The order of the stones does not matter, that is, a stone from any position $a_i$ can end up in at any position $b_j$, provided there is a required number of stones ... | First, when is the task impossible? If all $a_i$ have the same remainder $d$ modulo an integer $g$, then it will always be true regardless of our moves. The largest $g$ we can take is equal to $\mathrm{GCD}(a_2 - a_1, a_3 - a_1, a_4 - a_1)$. Remark: case when all $a_i$ are equal is special. If the GCD's or the remainde... | [
"constructive algorithms"
] | 3,500 | null |
1276 | F | Asterisk Substrings | Consider a string $s$ of $n$ lowercase English letters. Let $t_i$ be the string obtained by replacing the $i$-th character of $s$ with an asterisk character *. For example, when $s = \mathtt{abc}$, we have $t_1 = \tt{*bc}$, $t_2 = \tt{a*c}$, and $t_3 = \tt{ab*}$.
Given a string $s$, count the number of distinct string... | There are two types of substrings we have to count: with and without the *. The substrings without * are just all substrings of the intial string $s$, which can be counted in $O(n)$ or $O(n \log n)$ using any standard suffix structure. We now want to count the substrings containing *. Consider all such substrings of th... | [
"string suffix structures"
] | 3,400 | null |
1277 | A | Happy Birthday, Polycarp! | Hooray! Polycarp turned $n$ years old! The Technocup Team sincerely congratulates Polycarp!
Polycarp celebrated all of his $n$ birthdays: from the $1$-th to the $n$-th. At the moment, he is wondering: how many times he turned beautiful number of years?
According to Polycarp, a positive integer is beautiful if it cons... | It seems that one of the easiest ways to solve this problem is to iterate over all beautiful numbers up to $10^9$ and check each of the numbers to ensure that it does not exceed $n$. First of all, you can iterate over a length from $1$ to $8$, supporting a number of the form 11...1 of this length, and inside iterate ov... | [
"implementation"
] | 1,000 | cin >> n;
int b = 0, ans = 0;
for (int len = 1; len <= 9; len++) {
b = b * 10 + 1;
for (int m = 1; m <= 9; m++)
if (b * m <= n)
ans++;
}
cout << ans << endl;
|
1277 | B | Make Them Odd | There are $n$ positive integers $a_1, a_2, \dots, a_n$. For the one move you can choose any even value $c$ and divide by two \textbf{all} elements that equal $c$.
For example, if $a=[6,8,12,6,3,12]$ and you choose $c=6$, and $a$ is transformed into $a=[3,8,12,3,3,12]$ after the move.
You need to find the minimal numb... | Consider the greatest positive value in the set. Anyway, once we will divide it by two. It is always optimal to do it on the first move because the result of the division can be divided again (if needed) later. So, the optimal way to solve this problem is: as long as there is at least one even value in the set, we need... | [
"greedy",
"number theory"
] | 1,200 | cin >> n;
set<int> a;
for (int i = 0; i < n; i++) {
int elem;
cin >> elem;
a.insert(elem);
}
int result = 0;
while (!a.empty()) {
int m = *a.rbegin();
a.erase(m);
if (m % 2 == 0) {
result++;
a.insert(m / 2);
}
}
cout << result << endl;
|
1277 | D | Let's Play the Words? | Polycarp has $n$ \textbf{different} binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of $n$ binary words to play a game "words". In this game, players name words and each next word (start... | For a concrete set of words, it's not hard to find a criteria for checking if there is a correct order of arrangement of words for playing a game. Let's call such sets of words correct. Firstly the set of words is correct if the number of words like 0...1 and the number of words like 1...0 differ by no more than $1$. S... | [
"data structures",
"hashing",
"implementation",
"math"
] | 1,900 | int n;
cin >> n;
vector<string> s(n);
set<string> s01;
set<string> s10;
vector<bool> u(2);
forn(i, n) {
cin >> s[i];
if (s[i][0] == '0' && s[i].back() == '1')
s01.insert(s[i]);
if (s[i][0] == '1' && s[i].back() == '0')
s10.insert(s[i]);
u[s[i][0] - '0'] = u[s[i].back() - '0'] = true;
}
i... |
1278 | A | Shuffle Hashing | Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.
Polycarp decided to store the hash of the password, generated by the following algorithm:
- take the password $p$, consisting of lowercase Latin letters, and shuffle the le... | The general idea of the solution is to check that string $h$ contains some substring which is a permutation of $p$. The constraints were so low you could do it with any algorithm, even $O(n^3 \log n)$ per test case could pass. The most straightforward way was to iterate over the substring of $h$, sort it and check if i... | [
"brute force",
"implementation",
"strings"
] | 1,000 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int AL = 26;
string p, h;
bool read(){
if (!(cin >> p >> h))
return false;
return true;
}
void solve(){
vector<int> cntp(AL), cnt(AL);
vector<bool> eq(AL);
int sum = 0;
auto chg = [&cntp, &cnt, &eq, &s... |
1278 | B | A and B | You are given two integers $a$ and $b$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $1$; during the second operation you choose one of these numbers and increase it by $2$, and so on. You choose the number of these operations yourself.
For exa... | Assume that $a > b$. Let's denote the minimum number of operations required to make $a$ and $b$ equal as $x$. There are two restrictions on $x$: At first, $\frac{x(x+1)}{2} \ge a - b$, because if $\frac{x(x+1)}{2} < a - b$ then $a$ will be greater than $b$ (after applying all operations); Secondly, integers $\frac{x(x+... | [
"greedy",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int t, a, b;
bool ok(int res, int d){
long long sum = res * 1LL * (res + 1) / 2;
if(sum < d) return false;
return sum % 2 == d % 2;
}
int main() {
cin >> t;
for(int tc = 0; tc < t; ++tc){
cin >> a >> b;
int d = abs(a - b);
if(d == 0){
cout << "0\n";
... |
1278 | C | Berry Jam | Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam.
All the $2n$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees... | Let's transit from counting strawberry and blueberry jam jars separately to their difference. Let $dif$ be equal to $\#of\_strawberry\_jars - \#of\_blueberry\_jars$. Then eating one strawberry jar decreases $dif$ by $1$ and eating one blueberry jar increases $dif$ by $1$. The goal is to make $dif$ equal to $0$. Let the... | [
"data structures",
"dp",
"greedy",
"implementation"
] | 1,700 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int n;
vector<int> a;
bool read(){
if (scanf("%d", &n) != 1)
return false;
a.resize(2 * n);
forn(i, 2 * n)
scanf("%d", &a[i]);
return true;
}
void solve(){
int cur = 0;
map<int, int> difr;
difr[0] = 0;
c... |
1278 | D | Segment Tree | As the name of the task implies, you are asked to do some work with segments and trees.
Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.
You are given $n$ segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$, $l_i < r_i$ for every $i$. I... | The main idea of the solution is to find a linear number of intersections of segments. Intersections can be found with sweep line approach. We will maintain a set for the endpoints open segments. When we add a segment, we find all segments which intersect with it - that is, all segments that end earlier than it. Obviou... | [
"data structures",
"dsu",
"graphs",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
typedef pair<li, li> pt;
const int N = 500010;
int n;
pt a[N];
vector<int> g[N];
b... |
1278 | E | Tests for problem D | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.
Given an undirected labeled tree consisting of $n$ vertices, find a set of segments such that:
- both endpoints of each segment are integers from $1$ to $2n$, and each integer from $1$ t... | For each vertex, we will build the following structure for its children: the segment for the second child is nested in the segment for the first child, the nested for the third child is nested in the segment for the second child, and so on; and the children of different vertices do not intersect at all. Let's solve the... | [
"constructive algorithms",
"dfs and similar",
"divide and conquer",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(), (a).end()
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef pair<int, int> pt;
const int N = 500 * 1000 + 13;
int n;
vector<in... |
1278 | F | Cards | Consider the following experiment. You have a deck of $m$ cards, and exactly one card is a joker. $n$ times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.
Let $x$ be the number of times you have taken the joker out of the deck during this experiment. Ass... | First of all, I would like to thank Errichto for his awesome lecture on expected value: part 1, part 2. This problem was invented after I learned the concept of estimating the square of expected value from that lecture - and the editorial uses some ideas that were introduced there. Okay, now for the editorial itself. W... | [
"combinatorics",
"dp",
"math",
"number theory",
"probabilities"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 5043;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)
{
if(y % 2 == 1... |
1279 | A | New Year Garland | Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them ... | Let $r \le g \le b$ (if it is not the case, do some swaps). If $b > r + g + 1$, then at least two blue lamps will be adjacent - so there is no solution. Otherwise the answer can be easily constucted. Place all blue lamps in a row. Then place red lamps: one between the first and the second blue lamp, one between the sec... | [
"math"
] | 900 | for t in range(int(input())):
a = sorted(list(map(int, input().split())))
print('Yes' if a[2] <= a[0] + a[1] + 1 else 'No') |
1279 | B | Verse For Santa | New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.
Vasya's verse contains $n$ parts. It takes $a_i$ seconds to recite the $i$-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes $a_1$ seconds, secondly — the part wh... | If $\sum\limits_{i=1}^n a_i \le s$ then answer is 0. Otherwise let's find we minimum index $x$ such that $\sum\limits_{i=1}^x a_i > s$. It's useless to skip a part $i > x$, because Vasya just has not time to recite previous part (it's change nothing). So he has to skip a part $i \le x$. And among such parts it's benefi... | [
"binary search",
"brute force",
"implementation"
] | 1,300 | for t in range(int(input())):
n, t = map(int, input().split())
a = list(map(int, input().split()))
id = 0
for i in range(n):
if a[i] > a[id]:
id = i
t -= a[i]
if t < 0:
break
if t >= 0:
id = -1
print(id + 1) |
1279 | C | Stack of Presents | Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.
Santa has a list of $m$ \textbf{distinct} presents he has to send: $b_1$, $b... | At first let's precalculate array $pos$ such that $pos_{a_i} = i$. Now presume that we have to calculate answer for $b_i$. Then there are two cases (let's denote $lst = \max\limits_{1 \le j < i} pos_{b_j}$, initially $lst = -1$): if $pos_{b_i} > lst$ then we have to spend $1 + 2 \cdot (pos_{b_i} - (i - 1))$ seconds on ... | [
"data structures",
"implementation"
] | 1,400 | for t in range(int(input())):
n, m = map(int, input().split())
a = [x - 1 for x in list(map(int, input().split()))]
b = [x - 1 for x in list(map(int, input().split()))]
pos = a[:]
for i in range(n):
pos[a[i]] = i
lst = -1
res = m
for i in range(m):
if pos[b[i]] > lst:
res += 2 * (pos[b[i]] - i)
lst ... |
1279 | D | Santa's Bot | Santa Claus has received letters from $n$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $i$-th kid asked Santa to give them one of $k_i$ different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he want... | First of all, how to deal with the fractions modulo $998244353$? According to Fermat's little theorem, $x^{\phi(m)} \equiv 1 (mod m)$ if $x$ is coprime with $m$. So, the inverse element for the denominator $y$ is $y^{\phi(998244353) - 1} = y^{998244351}$, taken modulo $998244353$. A cool property of fractions taken mod... | [
"combinatorics",
"math",
"probabilities"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define sqr(a) ((a) * (a))
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int MOD = 998244353;
const int N = 1e6 + 7;... |
1279 | E | New Year Permutations | Yeah, we failed to make up a New Year legend for this problem.
A permutation of length $n$ is an array of $n$ integers such that every integer from $1$ to $n$ appears in it exactly once.
An element $y$ of permutation $p$ is reachable from element $x$ if $x = y$, or $p_x = y$, or $p_{p_x} = y$, and so on.
The \textbf... | Let's calculate $cycle_n$ - the number of permutations of length $n$, which have a maximum at the position $1$ and consist of exactly one cycle. Each good permutation can be divided into such blocks, so we'll need this value later. It is easy to notice that $cycle_n = (n-2)!$. Let's calculate the following dynamic prog... | [
"combinatorics",
"dp"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define sqr(a) ((a) * (a))
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define fore(i, l, r) for (int i = int(l); i < int... |
1279 | F | New Year and Handle Change | New Year is getting near. So it's time to change handles on codeforces. Mishka wants to change his handle but in such a way that people would not forget who he is.
To make it work, he only allowed to change letters case. More formally, during \textbf{one} handle change he can choose any segment of his handle $[i; i + ... | Let's simplify the problem a bit: we need either to minimize the number of lowercase letters or to minimize the number of uppercase letters. Both variants can be described by the following model: we have a binary array $a$ where $a[i] = 0$ if $s[i]$ is in the correct case and $a[i] = 1$ otherwise. We can do at most $k$... | [
"binary search",
"dp"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 1000 * 1000 + 11;
const int INF = 1e9;
int n, k, l;
string s;
int a[N];
pair<int, int> dp[N];
int calc(int mid) {
for (int i = 0; i <= n; ++i) {
dp[i] = make_pair(INF, INF);
}
dp[0] = make_pair(0, 0);
for (int i = 0; i < n; ++i) {
if (dp[i + 1] > m... |
1280 | A | Cut and Paste | We start with a string $s$ consisting only of the digits $1$, $2$, or $3$. The length of $s$ is denoted by $|s|$. For each $i$ from $1$ to $|s|$, the $i$-th character of $s$ is denoted by $s_i$.
There is one cursor. The cursor's location $\ell$ is denoted by an integer in $\{0, \ldots, |s|\}$, with the following meani... | Let $S^t$ be the string $S$ after the $t$th round, and let $S^0$ be the initial $S$. We also denote by $S_{i\ldots }$ the suffix of $S$ from the $i$th character, $S_i$, onwards. A single round turns $S^{t-1}$ into $S^t$ by replicating the suffix $S_{t+1\ldots }^{t-1}$ exactly $S_t$ times. Hence, we have the recurrence ... | [
"implementation",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll mod = 1'000'000'007;
constexpr int N = 1111;
char _s[N];
ll solve() {
int x;
scanf("%d%s", &x, _s);
ll ls = strlen(_s);
vector<char> s(_s, _s + ls);
for (int i = 1; i <= x; i++) {
int v = s[i - 1] - '1';
... |
1280 | B | Beingawesomeism | You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beinga... | If everything is P, then it is clearly impossible (MORTAL). Otherwise, you can turn everything into A in at most $4$ moves, starting from any single A. Thus, the answer is between $0$ and $4$. We can exhaust all possibilities: The answer is $0$ if: Everything is an A. Otherwise, at least $1$ move is needed. Everything ... | [
"implementation",
"math"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int solve(int r, int c, vector<string> grid) {
vector<int> rows(r), cols(c);
int total = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (grid[i][j] == 'A') rows[i]++, cols[j]++, total++;
}
}
if (total == r... |
1280 | C | Jeremy Bearimy | Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of $k$ pairs of people who have arrived in a new inhabited neighborhood. You need to assign ... | Maximization Suppose we're maximizing the sum. Consider a single edge $(a,b)$, and consider the two components on either side of this edge. Then we have an important observation: in the optimal solution, the nodes of one component are all paired with nodes on the other component. This is because otherwise, there will b... | [
"dfs and similar",
"graphs",
"greedy",
"trees"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
n <<= 1;
vector<vector<pair<int,ll>>> adj(n);
for (int i = 0; i < n - 1; i++) {
int a, b; ll c;
cin >> a >> b >> c;
a--, b--;
adj[a].emplace_back(b, c);
adj[b... |
1280 | D | Miss Punyverse | The Oak has $n$ nesting places, numbered with integers from $1$ to $n$. Nesting place $i$ is home to $b_i$ bees and $w_i$ wasps.
Some nesting places are connected by branches. We call two nesting places \underline{adjacent} if there exists a branch between them. A \underline{simple path} from nesting place $x$ to $y$ ... | Let's say a region is winning if there are strictly more wasps than bees. Thus, we're maximizing the number of winning regions. Tree DP seems natural in this sort of situation. For example, after rooting the tree arbitrarily, you could probably come up with something like $f(i, r)$: Given the subtree rooted at $i$ and ... | [
"dp",
"greedy",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Group {
int win; ll adv;
Group(int win = -1, ll adv = 0): win(win), adv(adv) {}
Group operator+(const Group& o) const {
return Group(win + o.win, adv + o.adv);
}
Group operator+() const {
return Group(win + ... |
1280 | E | Kirchhoff's Current Loss | Your friend Kirchhoff is shocked with the current state of electronics design.
"Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting" he said.
The negativity ju... | Instead of minimizing the integer cost (which feels like a hard number theory problem), let's try to minimize the real number cost first. This is a bit easier, but it should help us solve the integer case by at least giving us a lower bound. If we're allowed to assign arbitrary real numbers as costs, then we can deduce... | [
"math"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL << 60;
class Circuit {
public:
ll w = -1;
ll width() {
if (w == -1) compute_width();
return w;
}
virtual void compute_width() {}
virtual void assign(ll value) {}
virtual ostream& write_to(ost... |
1280 | F | Intergalactic Sliding Puzzle | You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a $2 \times (2k + 1)$ rectangular grid. The alien has $4k + 1$ distinct organs, numbered $1$ to $4k + 1$.
In healthy such aliens, the organs are arranged in a particular ... | The "shortcuts" thing in the output section is basically a way for you to define subroutines, i.e., you can create simpler (useful) operations, and then you can combine them into more complex operations. Now, to solve the problem, we may represent the grid by the "circular permutation" obtained by going around the grid... | [
"combinatorics",
"constructive algorithms",
"math"
] | 3,400 | def solve(k, grid):
seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1)
flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]
m = {
'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
'C': 'l'*k + 'u' + 'r'*k + 'd',
'D': 'CC' + 'R'*(2*k + 1) + 'CC' + '... |
1281 | A | Suffix Three | We just discovered a new data structure in our research group: a \textbf{suffix three}!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machi... | The simplest way to solve it is to use your language's builtin string methods like ends_with. (It might be different in your preferred language.) Alternatively, if you know how to access the individual letters of a string, then you may implement something similar to ends_with yourself. To print the required output, you... | [
"implementation"
] | 800 | for cas in range(int(input())): print({'o': "FILIPINO", 'a': "KOREAN", 'u': "JAPANESE"}[input()[-1]]) |
1281 | B | Azamon Web Services | Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call \textbf{Azamon}. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to hav... | The problem becomes a bit easier if we try to answer a different question: What is the lexicographically smallest string we can form from $S$? We then simply compare this string with $C$. This works because if the smallest string we can form is not smaller than $C$, then clearly no other string we can form will be smal... | [
"greedy"
] | 1,600 | def solve(s, t):
mns = list(s)
for i in range(len(s)-2,-1,-1): mns[i] = min(mns[i], mns[i + 1])
for i in range(len(s)):
if s[i] != mns[i]:
j = max(j for j, v in enumerate(s[i:], i) if v == mns[i])
s = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
break
return s if ... |
1282 | A | Temporarily unavailable | Polycarp lives on the coordinate axis $Ox$ and travels from the point $x=a$ to $x=b$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis $Ox$ at the point $x=c$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $r$. Thus, if Polyc... | To get an answer, we need to subtract from the whole time the time that we will be in the coverage area. Let the left boundary of the cover be $L=c-r$, and the right boundary of the cover be $R=c+r$. Then the intersection boundaries will be $st=max(L,min(a,b))$, $ed=min(R, max(a,b))$. Then the answer is calculated by t... | [
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int a, b, c, r;
cin >> a >> b >> c >> r;
int L = max(min(a, b), c - r);
int R = min(max(a, b), c + r);
cout << max(a, b) - ... |
1282 | B2 | K for the Price of One (Hard Version) | This is the hard version of this problem. The only difference is the constraint on $k$ — the number of gifts in the offer. In this version: $2 \le k \le n$.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$k$ of goods for the price of one" ... | If you sort the array by costs, it will always be profitable to take segments of length $k$ with the cheapest possible end. It remains only to understand when you need to take gifts without a promotion. It makes no sense to take $k$ or more gifts without a promotion, so we can combine them and buy together. It also mak... | [
"dp",
"greedy",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int main() {
int cntTest;
cin >> cntTest;
for (int test = 0; test < cntTest; test++) {
int n, p, k;
cin >> n >> p >> k;
int pref = 0;
int ans = 0;
vector<int> a(n);
f... |
1282 | C | Petya and Exam | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.
The exam consists of $n$ problems that can be solved in $T$ minutes. Thus, the exam begins at time $0$ and ends at time $T$. Petya can leave the exam at any integer tim... | Sort all problems by time $t_i$. You may notice that it is profitably to leave the exam at only one of the time points $t_i-1$. $t_i$ - a time when the task with the number $i$ becomes mandatory. Leaving at any other time in the range from $t_{i-1}$ to $t_i-2$ does not make sense since new mandatory tasks cannot appear... | [
"greedy",
"sortings",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int main() {
int cntTest;
cin >> cntTest;
for (int test = 0; test < cntTest; test++) {
ll n, t, a, b;
cin >> n >> t >> a >> b;
vector<pair<ll, ll>> v;
vector<int> hard(n);
in... |
1282 | D | Enchanted Artifact | \textbf{This is an interactive problem.}
After completing the last level of the enchanted temple, you received a powerful artifact of the 255th level. Do not rush to celebrate, because this artifact has a powerful rune that can be destroyed with a single spell $s$, which you are going to find.
We define the spell as ... | Firstly, let's find out the number of letters a and b in the hidden string in two queries. This can be done, for example, using queries aaa ... aaa and bbb ... bbb of length $300$. Let the answers to these queries be $q_a$ and $q_b$, then the number of letters a and b would be $\#a = 300 - q_a$ and $\#b = 300 - q_b$ re... | [
"constructive algorithms",
"interactive",
"strings"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int f(string s) {
cout << s << endl;
int w;
cin >> w;
if (w == 0)
exit(0);
return w;
}
int main() {
const int N = 300;
int st = f(string(N, 'a'));
int n = 2 * N - (st + f(string(N, 'b')));
string t(n, 'a');
int A = N - st,... |
1282 | E | The Cake Is a Lie | We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.
Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought abo... | The problem can be solved in different ways: one can independently find both permutations, or use one to find another. Firstly, let's find $q$ - the order of cutting cake pieces. Let's take a look at the edges of the first piece. This triangle has a common side with no more than one other piece. If it has no common sid... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
void dfs_order(int u, int p, vector<vector<int>> const& g, vector<int> &order) {
for (auto v : g[u]) {
if (v != p) {
dfs_order(v, u, g, order);
}
}
order.push_back(u);
}
void get_order(map<pair<int, int>, vector<int>> const& in, in... |
1283 | A | Minutes Before the New Year | New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $h$ hours and $m$ minutes, where $0 \le hh < 24$ and $0 \le mm < 60$. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year co... | In this problem we just need to print $1440 - 60h - m$. | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
scanf("%d", &q);
for (int i = 0; i < q; ++i) {
int h, m;
scanf("%d %d", &h, &m);
printf("%d\n", 1440 - h * 60 - m);
}
return 0;
} |
1283 | B | Candies Division | Santa has $n$ candies and he wants to gift them to $k$ kids. He wants to divide as many candies as possible between all $k$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has $a$ candies and the kid who recieves... | Firstly, we can notice that we always can distribute $n - n \% k$ (where $\%$ is the modulo operation) candies between kids. In this case $a=\lfloor\frac{n}{k}\rfloor$ and the answer is at least $ak$. And then we can add the value $min(n \% k, \lfloor\frac{k}{2}\rfloor)$ to the answer. Why? Because there is only $n \% ... | [
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n, k;
cin >> n >> k;
int full = n - n % k;
full += min(n % k, k / 2);
cout << full << endl;
}
... |
1283 | C | Friends and Gifts | There are $n$ friends who want to give gifts for the New Year to each other. Each friend should give \textbf{exactly} one gift and receive \textbf{exactly} one gift. The friend \textbf{cannot} give the gift to himself.
For each friend the value $f_i$ is known: it is either $f_i = 0$ if the $i$-th friend doesn't know w... | In this problem, we need to print the permutation without fixed points (without values $p_i = i$) but some values are known in advance. Let's consider the permutation as a graph. We know that the permutation is the set of non-intersecting cycles. In this problem, we are given such a graph but some edges are removed. Ho... | [
"constructive algorithms",
"data structures",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> f(n);
vector<int> in(n), out(n);
for (int i = 0; i < n; ++i) {
cin >> f[i];
--f[i];
if (f[i] != -1) {
++out[i];
++in... |
1283 | D | Christmas Trees | There are $n$ Christmas trees on an infinite number line. The $i$-th tree grows at the position $x_i$. All $x_i$ are guaranteed to be distinct.
Each \textbf{integer} point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.
There are $m... | In this problem, we first need to consider all points adjacent to at least one Christmas tree, then all points at the distance two from the nearby Christmas tree and so on... What it looks like? Yes, well-known multi-source bfs. Let's maintain a queue of positions and the set of used positions (and the distance to each... | [
"graphs",
"greedy",
"shortest paths"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
mt19937 rnd(time(NULL));
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
vector<int> x(n);
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
queue<int> q;
map<int, int> d;
for (in... |
1283 | E | New Year Parties | Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
$n$ friends live in a city which can be represented as a number line. The $i$-th friend lives in a house with an integer coordinate $x_i$. The $i$-th friend can come celebrate the New Year to the house with coo... | At first treat the two subtasks as completely independent problems. For both solutions the array of frequences is more convinient to use, so let's build it ($cnt_i$ is the number of friends living in house $i$). 1) Minimum Collect the answer greedily from left to right. If $cnt_i = 0$ then proceed to $i+1$, otherwise a... | [
"dp",
"greedy"
] | 1,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int n;
vector<int> a, cnt;
int solvemin(){
int res = 0;
forn(i, n){
if (!cnt[i]) continue;
++res;
i += 2;
}
return res;
}
int solvemax(){
int res = 0;
int dist = 2;
bool right = false;
forn(i, n){
if (... |
1283 | F | DIY Garland | Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.
Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of $n$ l... | First of all, we don't like the fact that importance values can be integers up to $2^n$ (it is kinda hard to work with them). Let's rephrase the problem. The highest bit set to $1$ in the importance value denotes the maximum in the subtree rooted at the auxiliary lamp for the wire. So, we sort the wires according to th... | [
"constructive algorithms",
"greedy",
"trees"
] | 2,200 | #define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
vector<int> a(n - 1);
for (int i = 0; i < n - 1; i++)
{
scanf("%d", &a[i]);
a[i]--;
}
int root = a[0];
int last = -1;
vector<int> used(n, 0);
printf("%d\n", ro... |
1285 | A | Mezo Playing Zoma | Today, Mezo is playing a game. Zoma, a character in that game, is initially at position $x = 0$. Mezo starts sending $n$ commands to Zoma. There are two possible commands:
- 'L' (Left) sets the position $x: =x - 1$;
- 'R' (Right) sets the position $x: =x + 1$.
Unfortunately, Mezo's controller malfunctions sometimes. ... | Let $c_L$ and $c_R$ be the number of 'L's and 'R's in the string respectively. Note that Zoma may end up at any integer point in the interval $[-c_L, c_R]$. So, the answer equals $c_R - (-c_L) + 1 = n + 1$. | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define finish(x) return cout << x << endl, 0
#define ll long long
int n;
string s;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> s;
cout << n + 1 << endl;
} |
1285 | B | Just Eat It! | Today, Yasser and Adel are at the shop buying cupcakes. There are $n$ cupcake types, arranged from $1$ to $n$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $i$ is an integer $a_i$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.... | If there is at least a prefix or a suffix with non-positive sum, we can delete that prefix/suffix and end up with an array with sum $\geq$ the sum of the whole array. So, if that's the case, the answer is "NO". Otherwise, all the segments that Adel can choose will have sum $<$ than the sum of the whole array because th... | [
"dp",
"greedy",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
#define finish(x) return cout << x << endl, 0
#define ll long long
int n;
vector <int> a;
bool solve(){
cin >> n;
a.resize(n);
for(auto &i : a) cin >> i;
ll sum = 0;
for(int i = 0 ; i < n ; i++){
sum += a[i];
if(sum <= 0) return 0;
... |
1285 | C | Fadi and LCM | Today, Osama gave Fadi an integer $X$, and Fadi was wondering about the minimum possible value of $max(a, b)$ such that $LCM(a, b)$ equals $X$. Both $a$ and $b$ should be positive integers.
$LCM(a, b)$ is the smallest positive integer that is divisible by both $a$ and $b$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = ... | There will always be a solution where $a$ and $b$ are coprime. To see why, let's prime factorize $a$ and $b$. If they share a prime factor we can omit all its occurrences from one of them, precisely from the one that has fewer occurrences of that prime, without affecting their $LCM$. Now, let's prime factorize $X$. Sin... | [
"brute force",
"math",
"number theory"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
#define finish(x) return cout << x << endl, 0
#define ll long long
ll x;
ll lcm(ll a, ll b){
return a / __gcd(a, b) * b;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> x;
ll ans;
for(ll i = 1 ; i * i <= x ; i++){
if(x % i ==... |
1285 | D | Dr. Evil Underscores | Today, as a friendship gift, Bakry gave Badawy $n$ integers $a_1, a_2, \dots, a_n$ and challenged him to choose an integer $X$ such that the value $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$ is minimum possible, where $\oplus$ denotes the bitwise XOR operation.
As always, Badawy is too lazy, so you decided to he... | We will solve this problem recursively starting from the most significant bit. Let's split the elements into two groups, one with the elements which have the current bit on and one with the elements which have the current bit off. If either group is empty, we can assign the current bit of $X$ accordingly so that we hav... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define finish(x) return cout << x << endl, 0
#define ll long long
int n;
vector <int> a;
int solve(vector <int> &c, int bit){
if(bit < 0) return 0;
vector <int> l, r;
for(auto &i : c){
if(((i >> bit) & 1) == 0) l.push_back(i);
else r.push_back... |
1285 | E | Delete a Segment | There are $n$ segments on a $Ox$ axis $[l_1, r_1]$, $[l_2, r_2]$, ..., $[l_n, r_n]$. Segment $[l, r]$ covers all points from $l$ to $r$ inclusive, so all $x$ such that $l \le x \le r$.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is $l_i=r_i$... | Ok, looking for a new number of segments in a union is actually hard. Let $nw_i$ be the union of segments after erasing the $i$-th one. Obviously, each of the segments in $nw[i]$ has its left and right borders. Let me show you how to calculate the number of any of these two kinds. Let's choose left borders. I will call... | [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | 2,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define x first
#define y second
using namespace std;
const int INF = 2e9;
typedef pair<int, int> pt;
map<int, int> ls;
int get(vector<pt> a){
int cnt = 0;
int l = -INF, r = -INF;
sort(a.begin(), a.end());
forn(i, a.size()){
if (a[i... |
1285 | F | Classical? | Given an array $a$, consisting of $n$ integers, find:
$$\max\limits_{1 \le i < j \le n} LCM(a_i,a_j),$$
where $LCM(x, y)$ is the smallest positive integer that is divisible by both $x$ and $y$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = 12$, $LCM(2, 3) = 6$. | Since $LCM(x,y)=\frac{x*y}{GCD(x,y)}$, it makes sense to try and fix $GCD(x,y)$. Let's call it $g$. Now, let's only care about the multiples of $g$ in the input. Assume we divide them all by $g$. We now want the maximum product of 2 coprime numbers in this new array. Let's sort the numbers and iterate from the biggest ... | [
"binary search",
"combinatorics",
"number theory"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
#define MX 100000
int arr[100005],u[MX+5],cnt[MX+5];
vector<int> d[MX+5];
bool b[MX+5];
int coprime(int x)
{
int ret=0;
for (int i:d[x])
ret+=cnt[i]*u[i];
return ret;
}
void update(int x,int a)
{
for (int i:d[x])
cnt[i]+=a;
}
int main()
{
for (int i=1;i<=MX;i++)
{
... |
1286 | A | Garland | Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of $n$ light bulbs in a single row. Each bulb has a number from $1$ to $n$ (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the ga... | The problem can be solved using a greedy algorithm. Notice that the only information we need is parity of numbers on bulbs. So let's replace numbers by their remainders modulo $2$. Than complexity of garland will be the number of pairs of adjacent numbers that are different. Let's call such pairs as bad. Divide garland... | [
"dp",
"greedy",
"sortings"
] | 1,800 | null |
1286 | B | Numbers on Tree | Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $1$ to $n$. Each of its vertices also has an integer $a_i$ written on it. For each vertex $i$, Evlampiy calculated $c_i$ — the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$.
\begin{center}
Illustration for the se... | There are several approaches to this problem. We will tell one of them. Note that if $c_i$ for some vertex is greater than the number of vertices in its subtree, then there is no answer. Now we prove that we can always build the answer, so that all $a_i$ will be numbers from $1$ to $n$. On those numbers, let's build so... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | 1,800 | null |
1286 | C2 | Madhouse (Hard version) | \textbf{This problem is different with easy version only by constraints on total answers length}
\textbf{It is an interactive problem}
Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $s$ of length $n$, consisting only of lowercase English letters.... | Let's consider the solution that uses $2$ queries with the lengths $n$ and $n-1$ (it asks about too many substrings, so it will not pass all the tests, but it will help us further). Let's ask about substrings $[1..n]$ and $[1..n-1]$. For convenience, rearrange the letters in all strings in alphabetical order. Then note... | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | 2,800 | null |
1286 | D | LCC | An infinitely long Line Chillland Collider (LCC) was built in Chillland. There are $n$ pipes with coordinates $x_i$ that are connected to LCC. When the experiment starts at time 0, $i$-th proton flies from the $i$-th pipe with speed $v_i$. It flies to the right with probability $p_i$ and flies to the left with probabil... | Note, that the first collision will occur between two neighboring particles in the original array. These two particles have 3 options to collide: both particles move to the right, both move to the left, they move towards each other. Let's go through these options and calculate the time of the collision. Let's do this f... | [
"data structures",
"math",
"matrices",
"probabilities"
] | 3,100 | null |
1286 | E | Fedya the Potter Strikes Back | Fedya has a string $S$, initially empty, and an array $W$, also initially empty.
There are $n$ queries to process, one at a time. Query $i$ consists of a lowercase English letter $c_i$ and a nonnegative integer $w_i$. First, $c_i$ must be appended to $S$, and $w_i$ must be appended to $W$. The answer to the query is t... | Let $ans_{i}$ be the answer for the moment after $i$ queries. Then, $s_{i} = ans_{i} - ans_{i-1}$ is equal to the sum of suspiciousness of suffixes of the string after $i$ queries. If we calculate $s_{i}$, $ans$ will be the prefix sums of this array. Let's maintain the KMP tree of the string. Each vertex of the tree co... | [
"data structures",
"strings"
] | 3,200 | null |
1286 | F | Harry The Potter | To defeat Lord Voldemort, Harry needs to destroy all horcruxes first. The last horcrux is an array $a$ of $n$ integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations:
- choose an index $i$ ($1 \le i \l... | Assume that we have done $m$ queries of the second type. On the $i$th query we subtracted $x_i$ from $a_{p_i}$ and $x_i + 1$ from $a_{q_i}$. Let's construct undirected graph on $n$ vertices with edges $(p_i, q_i)$. Assume we have a cycle $c_1, c_2, ..., c_k$ in this graph, then, we can replace queries along this cycle ... | [
"brute force",
"constructive algorithms",
"dp",
"fft",
"implementation",
"math"
] | 3,100 | null |
1287 | A | Angry Students | It's a walking tour day in SIS.Winter, so $t$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
- "A" corresponds to an angry ... | We will take a look at two different solutions. First has complexity $O(\sum\limits_{i = 0}^{t - 1} {k_i} ^ {2})$. In this solution, we will simulate the events described in the statement. We will simulate every minute. Note that every minute (until we have found the answer) number of angry students will increase by at... | [
"greedy",
"implementation"
] | 800 | null |
1287 | B | Hyperset | Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every... | Firstly, we can notice that two cards uniquely identify the third, which forms a set with them. If the $i$-th feature of two cards is the same, then in the third card also has the same, otherwise, it has a different feature. Thus, we can check all pairs of cards, find their third one, which forms a set with them, and f... | [
"brute force",
"data structures",
"implementation"
] | 1,500 | null |
1288 | A | Deadline | Adilbek was assigned to a special project. For Adilbek it means that he has $n$ days to run a special program and provide its results. But there is a problem: the program needs to run for $d$ days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends $x$ ($x$ is a non-negative integer) ... | At first, let's note that if $x$ is integer and $x$ and $y$ are non-negative then $x + \left\lceil y \right\rceil = \left\lceil x + y \right\rceil$. So, instead of looking at $x + \left\lceil \frac{d}{x + 1} \right\rceil$ we can consider $\left\lceil x + \frac{d}{x + 1} \right\rceil$. It's easier since the function $x ... | [
"binary search",
"brute force",
"math",
"ternary search"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// int tt = clock();
#endif
int T; cin >> T;
while(T--) {
int n, d;
cin >> n >> d;
int x, MAG = (int)sqrt(d) + 10;
for(x = 0; x < MAG; x++) {
if(x + (d + x) / (x + 1) <= n)
break;
}
cou... |
1288 | B | Yet Another Meme Problem | You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). \textbf{$a$ and $b$ should... | Let's perform some conversions: $a \cdot b + a + b = conc(a, b)$ $a \cdot b + a + b = a \cdot 10^{|b|} + b$, where $|b|$ is the length of decimal representation of $b$. $a \cdot b + a = a \cdot 10^{|b|}$ $b + 1 = 10^{|b|}$ Thus, $b$ always look like $99 \dots 99$. So, the answer is $a * (|b + 1| - 1)$. | [
"math"
] | 1,100 | for t in range(int(input())):
a, b = map(int, input().split())
print(a * (len(str(b + 1)) - 1)) |
1288 | C | Two Arrays | You are given two integers $n$ and $m$. Calculate the number of pairs of arrays $(a, b)$ such that:
- the length of both arrays is equal to $m$;
- each element of each array is an integer between $1$ and $n$ (inclusive);
- $a_i \le b_i$ for any index $i$ from $1$ to $m$;
- array $a$ is sorted in non-descending order;
... | Let's consider the following sequence: $a_1, a_2, \dots, a_m, b_m, b_{m-1}, \dots , b_1$. It's sequence of length $2m$ sorted in non-descending order, where each element of each sequence is an integer between $1$ and $n$. We can find the number of such sequences by simple combinatorics - it's combination with repetitio... | [
"combinatorics",
"dp"
] | 1,600 | from math import factorial as fact
mod = 10**9 + 7
def C(n, k):
return fact(n) // (fact(k) * fact(n - k))
n, m = map(int, input().split())
print(C(n + 2*m - 1, 2*m) % mod) |
1288 | D | Minimax Problem | You are given $n$ arrays $a_1$, $a_2$, ..., $a_n$; each array consists of exactly $m$ integers. We denote the $y$-th element of the $x$-th array as $a_{x, y}$.
You have to choose two arrays $a_i$ and $a_j$ ($1 \le i, j \le n$, it is possible that $i = j$). After that, you will obtain a new array $b$ consisting of $m$ ... | We will use binary search to solve the problem. Suppose we want to know if the answer is not less than $x$. Each array can be represented by a $m$-bit mask, where the $i$-th bit is $1$ if the $i$-th element of the array is not less than $x$, or $0$ if the $i$-th element is less than $x$. If we want to verify that the a... | [
"binary search",
"bitmasks",
"dp"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
int n, m;
vector<vector<int> > a;
int a1, a2;
bool can(int mid)
{
vector<int> msk(1 << m, -1);
for(int i = 0; i < n; i++)
{
int cur = 0;
for(int j = 0; j < m; j++)
if(a[i][j] >= mid)
cur ^= (1 << j);
msk[cur]... |
1288 | E | Messenger Simulator | Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $n$ friends, numbered from $1$ to $n$.
Recall that a permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array.
So his recent chat list can be r... | So I have two slightly different approaches to the problem. There is a straightforward (no brain) one and a bit smarter one. The minimum place is the same in both solutions. For the $i$-th friend it's just $i$ if he never moves and $1$ otherwise. Obtaining the maximum place is trickier. For the first approach, take a l... | [
"data structures"
] | 2,000 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 600 * 1000 + 13;
int f[N];
void upd(int x, int val){
for (int i = x; i >= 0; i = (i & (i + 1)) - 1)
f[i] += val;
}
int get(int x){
int res = 0;
for (int i = x; i < N; i |= i + 1)
res += f[i];
re... |
1288 | F | Red-Blue Graph | You are given a bipartite graph: the first part of this graph contains $n_1$ vertices, the second part contains $n_2$ vertices, and there are $m$ edges. \textbf{The graph can contain multiple edges}.
Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it cost... | A lot of things in this problem may tell us that we should try thinking about a flow solution. Okay, let's try to model the problem as a flow network. First of all, our network will consist of vertices and edges of the original graph. We somehow have to denote "red", "blue" and "colorless" edges; we will do it as follo... | [
"constructive algorithms",
"flows"
] | 2,900 | #include<bits/stdc++.h>
using namespace std;
const int N = 443;
int n1, n2, m, r, b;
string s1, s2;
int u[N];
int v[N];
struct edge
{
int y, c, f, cost;
edge() {};
edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {};
};
int bal[N][N];
int s, t, oldS, oldT, V;
vector<int> g[N];
vector<... |
1290 | A | Mind Control | You and your $n - 1$ friends have found an array of integers $a_1, a_2, \dots, a_n$. You have decided to share it in the following way: All $n$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps ... | People behind you are useless, ignore them. Let's assume that $k \le m-1$. It's always optimal to control as many people as possible. Your strategy can be summarized by a single integer $x$, the number of people you force to take the first element (among the $k$ you control). Similarly, the strategy of your opponents c... | [
"brute force",
"data structures",
"implementation"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m, k;
cin >> n >> m >> k;
k = min(k, m - 1);
vector<int> a(n);
for(auto &x : a)
cin >> x;
vector<int> b;
for(int i = 0; i < m; i++)
b.push_back(max(a[i], a[i + n - m]));
int sz = m - k;
int ans = 0;
... |
1290 | B | Irreducible Anagrams | Let's call two strings $s$ and $t$ anagrams of each other if it is possible to rearrange symbols in the string $s$ to get a string, equal to $t$.
Let's consider two strings $s$ and $t$ \textbf{which are anagrams of each other}. We say that $t$ is a reducible anagram of $s$ if there exists an integer $k \ge 2$ and $2k$... | We claim that a string has at least one irreducible anagram if and only if one of the following conditions holds: Its length is equal to $1$. Its first and last characters are different. It contains at least three different characters. Once we have proven this characterization it is easy to solve the problem: For any g... | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
char s[N];
int n, q, l, r, sum[N][26];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> (s + 1);
n = strlen(s + 1);
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 26; j++) {
sum[i][j... |
1290 | C | Prefix Enlightenment | There are $n$ lamps on a line, numbered from $1$ to $n$. Each one has an initial state off ($0$) or on ($1$).
You're given $k$ subsets $A_1, \ldots, A_k$ of $\{1, 2, \dots, n\}$, such that the intersection of any three subsets is empty. In other words, for all $1 \le i_1 < i_2 < i_3 \le k$, $A_{i_1} \cap A_{i_2} \cap ... | The condition "the intersection of any three subsets is empty" can be easily rephrased in a more useful way: each element appears in at most two subsets. Let's suppose for the moment that each elements appears in exactly two subsets. We can think of each element as an edge between the subsets, it's a classical point of... | [
"dfs and similar",
"dsu",
"graphs"
] | 2,400 | #include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
const int N = 1E6 + 5, K = 1E6 + 5, INF = 1E9 + 7;
int n, k, c, v, ans = 0, dsu[K];
char s[N];
vector<int> adj[N];
struct node {
int l, r, xo;
node(int _l = 0, int _r = 0, int _xo = 0) : l(_l), r(_r), xo(_xo) {}
int get() ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.