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 ⌀ |
|---|---|---|---|---|---|---|---|
1380 | E | Merging Towers | You have a set of $n$ discs, the $i$-th disc has radius $i$. Initially, these discs are split among $m$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.
You would like to assemble one tower containing all of those discs. To do ... | First of all, let's try to find a simple way to evaluate the difficulty of a given set of towers. I claim that the difficulty is equal to the number of pairs of discs $(i, i + 1)$ that belong to different towers. The beginning of the proof during each operation we can "merge" at most one such pair: if we move discs to ... | [
"data structures",
"dsu",
"implementation",
"trees"
] | 2,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int n, m;
vector<int> p;
vector<vector<int>> val;
vector<int> who;
int getp(int a){
return a == p[a] ? a : p[a] = getp(p[a]);
}
int main(){
scanf("%d%d", &n, &m);
p.resize(m);
val.resize(m);
who.resize(n);
int a... |
1380 | F | Strange Addition | Let $a$ and $b$ be some non-negative integers. Let's define strange addition of $a$ and $b$ as following:
- write down the numbers one under another and align them by their least significant digit;
- add them up digit by digit and concatenate the respective sums together.
Assume that both numbers have an infinite num... | Let's solve the task as if there are no updates. This can be done with a pretty straightforward dp. $dp_i$ is the number of pairs $(a, b)$ such that the result of the strange addition of $a$ and $b$ is the prefix of $c$ of length $i$. $dp_0 = 1$. From each state you can add a single digit to $a$ and to $b$ at the same ... | [
"data structures",
"dp",
"matrices"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int N = int(5e5) + 9;
const int MOD = 998244353;
int mul(int a, int b) {
return (a * 1LL * b) % MOD;
}
void add(int &a, int x) {
a += x;
a %= MOD;
}
int bp(int a, int n) {
int res = 1;
for (; n > 0; n >>= 1) {
if (n & 1) res = mul(res,... |
1380 | G | Circular Dungeon | You are creating a level for a video game. The level consists of $n$ rooms placed in a circle. The rooms are numbered $1$ through $n$. Each room contains exactly one exit: completing the $j$-th room allows you to go the $(j+1)$-th room (and completing the $n$-th room allows you to go the $1$-st room).
You are given th... | Idea: BledDest At first, let's say that the expected value is equal to the average of total earnings over all positions and is equal to the sum of earnings over all positions divided by $n$. So we can trasition to minimizing the sum. Let's learn how to solve the task for some fixed $k$. Fix some arrangement and rotate ... | [
"greedy",
"math",
"probabilities"
] | 2,600 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int mul(int a, int b){
return a * 1ll * b % MOD;
}
int binpow(int a, int b){
int res = 1;
... |
1381 | A1 | Prefix Flip (Easy Version) | \textbf{This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.}
There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symb... | The easy version has two main solutions: Solution 1: $O(n)$ time with $3n$ operations The idea is to fix the bits one-by-one. That is, make $s_1=t_1$, then make $s_2=t_2$, etc. To fix the bit $i$ (when $s_i\ne t_i$), we can flip the prefix of length $i$, then flip the prefix of length $1$, and again flip the prefix of ... | [
"constructive algorithms",
"data structures",
"strings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
// Solution 2 from editorial
// Fix the bits one-by-one in reverse order.
// Simulate the operations manually, achieving O(n^2) time complexity
int t, n;
string a, b;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> t;
while(t--) {
... |
1381 | A2 | Prefix Flip (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.}
There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symb... | There are several ways to solve the hard version as well. Solution 1 Given an arbitrary binary string $s$, we can make all bits $0$ in at most $n$ operations. Simply scan the string from left to right. If bits $i$ and $i+1$ disagree, apply the operation to the prefix of length $i$. This is also easy to simulate in $O(n... | [
"constructive algorithms",
"data structures",
"implementation",
"strings",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
// Solution 2 from editorial
// instead of simulating, we store two variables idx and flip
// they tell us enough information to ask the value of the first bit during the process
// If flip is false, it means the substring s[idx, ..., idx + i) is currently the beginning... |
1381 | B | Unmerge | Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows:
- If one of the arrays is empty, the result is the other array. That is, $\mathrm{merge}(\emptyset,b)=b$ and $\mathrm{merge}(a,\emptyse... | Consider the maximum element $2n$ of $p$. Assume without loss of generality that it comes from array $a$. Then the merge algorithm will exhaust array $b$ before it takes the element $2n$. Therefore, if $2n$ appears at index $i$ in $p$, the entire suffix of $p$ beginning at index $i$ must be a contiguous block in one of... | [
"dp"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
// compute block lengths, and do subset sum.
// O(n^2) subset sum is a standard dp
// For educational purposes, here is the O(n sqrt(n)) solution
// we treat each distinct length independently, and remember the number of occurrences
// use the helper array a to update t... |
1381 | C | Mastermind | In the game of Mastermind, there are two players — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of $n$ colors. There are exactly $n+1$ colors in the entire universe, numbered from $1$ to $n+1$ inclusive.
When Bob guesses a code, Alice tells him some informati... | Suppose we have already decided which $x$ indices agree on color. We should shuffle the remaining $n-x$ indices in a way that minimizes the number of matches. We should also replace $n-y$ indices with a color that doesn't contribute to the multiset intersection. Because there are $n+1>n$ colors, there is some color $c$... | [
"constructive algorithms",
"graph matchings",
"greedy",
"implementation",
"sortings",
"two pointers"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
// ind[color] = list of indices that have this color
// hist[frequency] = list of colors with this frequency
// a solution with priority_queue is perhaps simpler to implement,
// but here is an O(n) solution because we can.
const int N = 1e5 + 5;
int t, n, x, y, b[N],... |
1381 | D | The Majestic Brown Tree Snake | There is an undirected tree of $n$ vertices, connected by $n-1$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $a$ and its tail is at vertex $b$. The snake's body occupies all vertices on the unique simple path between $a$ and $b$.
The snake wants to know if it can reverse ... | Let the length of the snake be $L$. Let's call a node $p$ a "pivot" if there exist three edge-disjoint paths of length $L$ extending from $p$. Clearly, if one of the snake's endpoints (head or tail) can reach a pivot, then the snake can rotate through these $3$ paths, reversing itself. I claim two things: If a snake's ... | [
"dfs and similar",
"dp",
"greedy",
"trees",
"two pointers"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
// This is the O(n) two-pointer solution from the editorial
const int N = 1e5 + 5;
int t, n, a, b, u, v, par[N], branch[N], depth[N];
vector<int> adj[N], Q[N];
// find largest branch lengths from each node, using 2 DFS's.
// first DFS is for root = a
// second DFS is ... |
1381 | E | Origami | After being discouraged by 13 time-limit-exceeded verdicts on an ugly geometry problem, you decided to take a relaxing break for arts and crafts.
There is a piece of paper in the shape of a simple polygon with $n$ vertices. The polygon may be non-convex, but we all know that proper origami paper has the property that ... | First, let's imagine the problem in one dimension. And let's see how the length of the folded segment changes as we sweep the fold line from left to right. If the fold line is to the left of the paper, it's just the length of the segment. Then as the fold line enters the left side of the paper, we subtract the length o... | [
"geometry",
"math",
"sortings"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
// pro-tip: use complex<double> if you're really lazy
// and don't like typing a custom point struct
#define pt complex<double>
#define x real()
#define y imag()
const int N = 1e5 + 5;
int n, q;
double f[N], ans[N];
pt p[N];
// list of events (x coordinate, query in... |
1382 | A | Common Subsequence | You are given two arrays of integers $a_1,\ldots,a_n$ and $b_1,\ldots,b_m$.
Your task is to find a \textbf{non-empty} array $c_1,\ldots,c_k$ that is a subsequence of $a_1,\ldots,a_n$, and also a subsequence of $b_1,\ldots,b_m$. If there are multiple answers, find one of the \textbf{smallest} possible length. If there ... | If there is any common subsequence, then there is a common element of $a$ and $b$. And a common element is also a common subsequence of length $1$. Therefore, we need only find a common element of the two arrays, or say that they share no elements. Complexity is $O(nm)$ if we compare each pair of elements, $O((n+m)\log... | [
"brute force"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int t, n, m, a[N], b;
bool vis[N];
// vis[x] = true if x appears in array a
// for each element b[i], we check if it is also in a
// don't forget to reset vis array before the next test case
int main() {
ios::sync_with_stdio(false);
cin.t... |
1382 | B | Sequential Nim | There are $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the \textbf{first non-empty pile} (the pile with the minimal index, that has at least one stone). The first p... | Suppose $a_1>1$. If removing the entire first pile is winning, player 1 will do that. Otherwise, player 1 can leave exactly one stone in the first pile, forcing player 2 to remove it, leaving player 1 in the winning position. Otherwise, if $a_1=1$, then it is forced to remove the first pile. So, whichever player gets t... | [
"dp",
"games"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int t, n, a[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> t;
while(t--) {
cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
// count number of 1's in the prefix
... |
1383 | A | String Transformation 1 | \textbf{Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects must be strictly greater alphabetically than $x$ (read statement for better understanding). You can make hacks in these problems independently.}
Koa the ... | First of all, if there exists some $i$ such that $A_i > B_i$ there isn't a solution. Otherwise, create a graph where every character is a node, and put a directed edge between node $u$ and node $v$ if character $u$ must be transformed into character $v$ (ie. from $A_i$ to $B_i$ for all $i$). We must select a list with ... | [
"dsu",
"graphs",
"greedy",
"sortings",
"strings",
"trees",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int Alp = 20;
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0);
int test;
cin >> test;
while (test--)
{
int n;
string a, b;
cin >> n >> a >> b;
bool bad = false;
vector<vector<int>> adj(Alp);
for (int i = 0; i < n; ++i)
if (a[i] != b[i... |
1383 | B | GameGame | Koa the Koala and her best friend want to play a game.
The game starts with an array $a$ of length $n$ consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to $0$. Koa starts.
Let's describe a move in the game:
- During his move, a player chooses any elemen... | Let $x$ be the number of ones and $y$ be the numbers of zeros in the most significant bit of the numbers: if $x$ is even, whatever decision players take, both will end with the same score in that bit, so go to the next bit (if it doesn't exist the game ends in a draw). Indeed, the parity of the result of both players w... | [
"bitmasks",
"constructive algorithms",
"dp",
"games",
"greedy",
"math"
] | 1,900 | import sys
input = sys.stdin.readline
d = { 1: 'WIN', 0: 'LOSE', -1: 'DRAW' }
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = map(int, input().split())
f = [0] * 30
for x in a:
for b in range(30):
if x >> b & 1:
... |
1383 | C | String Transformation 2 | \textbf{Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects can be any letter from the first $20$ lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problem... | The only difference between this problem and the previous problem is that the underlying graph might have cycles. Each weakly connected component can be solved independently and the answer is $2 \cdot n - |LDAG| - 1$ where $n$ is the number of nodes in the component and $|LDAG|$ is the size of the largest Directed Acyc... | [
"bitmasks",
"dp",
"graphs",
"trees"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
const int Alp = 20;
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0);
int test;
cin >> test;
while (test--)
{
int len;
string a, b;
cin >> len >> a >> b;
vector<int> adj(Alp);
vector<vector<int>> G(Alp);
for (int i = 0; i < len; ++i)
if (a... |
1383 | D | Rearrange | Koa the Koala has a matrix $A$ of $n$ rows and $m$ columns. Elements of this matrix are distinct integers from $1$ to $n \cdot m$ (each number from $1$ to $n \cdot m$ appears exactly once in the matrix).
For any matrix $M$ of $n$ rows and $m$ columns let's define the following:
- The $i$-th row of $M$ is defined as $... | Let $A$ be a matrix of size $n \cdot m$ that is formed by a permutation of elements from $1$ to $n \cdot m$. Find the maximum element on each row and column (i.e. the spectrum) Now we are going to build the answer adding numbers one by one in decreasing order. We start with an empty 2 dimensional matrix (both dimension... | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"sortings"
] | 2,800 | #include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> mat(n, vector<int>(m));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
cin >> mat[i][j];
vec... |
1383 | E | Strange Operation | Koa the Koala has a binary string $s$ of length $n$. Koa can perform no more than $n-1$ (possibly zero) operations of the following form:
In one operation Koa selects positions $i$ and $i+1$ for some $i$ with $1 \le i < |s|$ and sets $s_i$ to $max(s_i, s_{i+1})$. Then Koa deletes position $i+1$ from $s$ (after the rem... | Firstly the described operation can be seen as divide $s$ in sub-strings and take the bitwise or in each one. For each possible resultant string $w$ let's think in the following way of obtain it from $s$: Suppose we already have a $1$ in $w$ in previous steps (if not it can be handled later) and we used the firsts $i$ ... | [
"combinatorics",
"data structures",
"dp"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
string s; cin >> s;
int n = s.length();
vector<int> dist(n);
for (int i = 0; i < n; ++i)
if (s[i] == '0') dist[i] = (i ? dist[i-1] : 0) + 1;
vector<int> dp(n + 2), nxt(n+2, n);
a... |
1383 | F | Special Edges | Koa the Koala has a \textbf{directed} graph $G$ with $n$ nodes and $m$ edges. Each edge has a capacity associated with it. Exactly $k$ edges of the graph, numbered from $1$ to $k$, are special, such edges initially have a capacity equal to $0$.
Koa asks you $q$ queries. In each query she gives you $k$ integers $w_1, w... | Finding maximum flow from $1$ to $n$ is equivalent to find the minimum cut from $1$ to $n$. Let's use the later interpretation to solve the problem. Suppose there is a single special edge ($k = 1$), on each query there are two options, either this edge belong to the minimum cut or it doesn't. If the edge doesn't belong... | [
"flows",
"graphs"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
template<typename C, typename R = C>
struct dinic
{
typedef C flow_type;
typedef R result_type;
static_assert(std::is_arithmetic<flow_type>::value, "flow_type must be arithmetic");
static_assert(std::is_arithmetic<result_type>::value, "result_type must be arithmetic"... |
1384 | A | Common Prefixes | The length of the \textbf{longest common prefix} of two strings $s = s_1 s_2 \ldots s_n$ and $t = t_1 t_2 \ldots t_m$ is defined as the maximum integer $k$ ($0 \le k \le min(n,m)$) such that $s_1 s_2 \ldots s_k$ equals $t_1 t_2 \ldots t_k$.
Koa the Koala initially has $n+1$ strings $s_1, s_2, \dots, s_{n+1}$.
For eac... | The problem asks to find $n+1$ strings such that $LCP(s_i, s_{i + 1}) = a_i$ for all $i$ ($1 \le i \le n$). A way to solve this problem is the following: Set $s_1 =$ "aaaa...aaaaaaa" (ie. $200$ times 'a'). For $i$ such that ($1 \le i \le n$) set $s_{i + 1} := s_i$ and then flip $(a_i + 1)$-th character of $s_{i + 1}$ (... | [
"constructive algorithms",
"greedy",
"strings"
] | 1,200 | import sys
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
mx = max(a)
ans = [ 'a' * (mx + 1) ] * (n + 1)
for i, x in enumerate(a):
who = 'a' if ans[i][x] == 'b' el... |
1384 | B1 | Koa and the Beach (Easy Version) | \textbf{The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.}
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters ... | For this version you can just simulate each possible action of Koa. Let $(pos, tide, down)$ a state where $pos$ is the current position of Koa (ie $0$ is the shore, from $1$ to $n$ is the $i$-th meter of sea and $n+1$ is the island), $tide$ is the current increment of the tide, and $down$ is a boolean that is true if t... | [
"brute force",
"dp",
"greedy"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0);
int test;
cin >> test;
while (test--)
{
int n, k, l;
cin >> n >> k >> l;
vector<int> d(n+2, -k);
for (int i = 1; i <= n; ++i)
cin >> d[i];
set<tuple<int, int, bool>> mark;
function<bool(int, int,... |
1384 | B2 | Koa and the Beach (Hard Version) | \textbf{The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.}
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters... | Let's define positions $i$ such that ($1 \le i \le n$) and $d_i + k \le l$ as safe positions, also positions $0$ and $n + 1$ are safe too (ie. the shore and the island respectively). Remaining positions are unsafe. Koa can wait indefinitely on safe positions without drowning, so she can reach the island (ie. position $... | [
"constructive algorithms",
"dp",
"greedy",
"implementation"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0);
int test;
cin >> test;
while (test--)
{
int n, k, l;
cin >> n >> k >> l;
vector<int> d(n+1), safe = { 0 };
for (int i = 1; i <= n; ++i)
{
cin >> d[i];
if (d[i] + k <= l)
safe.push_back(i);
... |
1385 | A | Three Pairwise Maximums | You are given three positive (i.e. strictly greater than zero) integers $x$, $y$ and $z$.
Your task is to find positive integers $a$, $b$ and $c$ such that $x = \max(a, b)$, $y = \max(a, c)$ and $z = \max(b, c)$, or determine that it is impossible to find such $a$, $b$ and $c$.
You have to answer $t$ independent test... | Suppose $x \le y \le z$. If $y \ne z$ then the answer is -1, because $z$ is the overall maximum among all three integers $a$, $b$ and $c$ and it appears in two pairs (so it should appear at most twice among $x$, $y$ and $z$). Otherwise, the answer exists and it can be $x$, $x$ and $z$ (it is easy to see that this tripl... | [
"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 t;
cin >> t;
while (t--) {
vector<int> a(3);
for (auto &it : a) cin >> it;
sort(a.begin(), a.end());
if (a[1] != a[2]) {
cout << "NO" << endl;
... |
1385 | B | Restore the Permutation by Merger | A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not.
There was a permutation $p[1 \dots n]$. It was merged with itself. In other words... | The solution is pretty simple: it's obvious that the first element of $a$ is the first element of the permutation $p$. Let's take it to $p$, remove it and its its copy from $a$. So we just have the smaller problem and can solve it in the same way. It can be implemented as "go from left to right, if the current element ... | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(2 * n);
for (auto &it : a) cin >> it;
vector<int> used(n);
vector<int> p;
for (int ... |
1385 | C | Make It Good | You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \dots, a_n]$ is a subarray consisting several first elements: the prefix of the array $a$... | Consider the maximum element $a_{mx}$ of the good array $a$ of length $k$. Then we can notice that the array $a$ looks like $[a_1 \le a_2 \le \dots \le a_{mx} \ge \dots \ge a_{k-1} \ge a_k]$. And this is pretty obvious that if the array doesn't have this structure, then it isn't good (you can see it yourself). So we ne... | [
"greedy"
] | 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 t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) cin >> it;
int pos = n - 1;
while (pos > 0 && a[pos - 1] >= a[... |
1385 | D | a-Good String | You are given a string $s[1 \dots n]$ consisting of lowercase Latin letters. It is guaranteed that $n = 2^k$ for some integer $k \ge 0$.
The string $s[1 \dots n]$ is called $c$-good if \textbf{at least one} of the following three conditions is satisfied:
- The length of $s$ is $1$, and it consists of the character $c... | Consider the problem in $0$-indexation. Define the function $calc(l, r, c)$ which finds the minimum number of changes to make the string $s[l \dots r)$ $c$-good string. Let $mid = \frac{l + r}{2}$. Then let $cnt_l = \frac{r - l}{2} - count(s[l \dots mid), c) + calc(mid, r, c + 1)$ and $cnt_r = \frac{r - l}{2} - count(s... | [
"bitmasks",
"brute force",
"divide and conquer",
"dp",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int calc(const string &s, char c) {
if (s.size() == 1) {
return s[0] != c;
}
int mid = s.size() / 2;
int cntl = calc(string(s.begin(), s.begin() + mid), c + 1);
cntl += s.size() / 2 - count(s.begin() + mid, s.end(), c);
int cntr = calc(string(s.begin() + mid, s.en... |
1385 | E | Directing Edges | You are given a graph consisting of $n$ vertices and $m$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.
You have to direct undirected edges in such... | Firstly, if the graph consisting of initial vertices and only directed edges contains at least one cycle then the answer is "NO". Otherwise, the answer is always "YES". Let's build it. Let's build the topological sort of the graph without undirected edges. Then let's check for each directed edge if it's going from left... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
vector<int> ord;
vector<int> used;
vector<vector<int>> g;
void dfs(int v) {
used[v] = 1;
for (auto to : g[v]) {
if (!used[to]) dfs(to);
}
ord.push_back(v);
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endi... |
1385 | F | Removing Leaves | You are given a tree (connected graph without cycles) consisting of $n$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles.
In one move, you can choose exactly $k$ leaves (leaf is such a vertex that is connected to only one another vertex) connected \textbf{to the same vertex} and ... | This is mostly implementation problem. We can notice that all leaves are indistinguishable for us. So if we have some vertex with at least $k$ leaves attached to it, we can choose it, remove these leaves from the tree and continue the algorithm. The rest is just an implementation: let's maintain for each vertex $v$ the... | [
"data structures",
"greedy",
"implementation",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int n, k, ans;
vector<set<int>> g;
vector<set<int>> leaves;
struct comp {
bool operator() (int a, int b) const {
if (leaves[a].size() == leaves[b].size()) return a < b;
return leaves[a].size() > leaves[b].size();
}
};
int main() {
#ifdef _DEBUG
freopen("input.txt... |
1385 | G | Columns Swaps | You are given a table $a$ of size $2 \times n$ (i.e. two rows and $n$ columns) consisting of integers from $1$ to $n$.
In one move, you can choose some \textbf{column} $j$ ($1 \le j \le n$) and swap values $a_{1, j}$ and $a_{2, j}$ in it. Each column can be chosen \textbf{no more than once}.
Your task is to find the ... | Firstly, we can determine that the answer is -1 if some number has not two occurrences. Otherwise, the answer exists (and we actually don't need to prove it because we can check it later). Let's find for each number $i$ from $1$ to $n$ indices of columns in which it appears $c_1[i]$ and $c_2[i]$. Consider some number $... | [
"2-sat",
"dfs and similar",
"dsu",
"graphs",
"implementation"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int cnt0, cnt1;
vector<int> col, comp;
vector<vector<pair<int, int>>> g;
void dfs(int v, int c, int cmp) {
col[v] = c;
if (col[v] == 0) ++cnt0;
else ++cnt1;
comp[v] = cmp;
for (auto [to, change] : g[v]) {
if (col[to] == -1) {
dfs(to, c ^ change, cmp);
}
}
}
... |
1386 | A | Colors | Linda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference — so Linda always knows whether Archie has spotted the difference o... | Subtask 1 ($N \leq 64$) We will use the colors in this order: $1$, $N$, $2$, $N-1$, $3$, $N-2$, $\ldots$; this way we will check each difference $N-1$, $N-2$, $N-3$, $N-4$, $\ldots$ and the answer is the first difference that is not recognized by Archie. Complexity: $N$ queries. Subtask 2 ($N \leq 125$) We can first as... | [
"*special",
"binary search",
"constructive algorithms",
"interactive"
] | 2,700 | null |
1386 | B | Mixture | Serge, the chef of the famous restaurant "Salt, Pepper & Garlic" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening.
Even though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as ... | The crux of solving this problem is to think about it from a geometric perspective and discover a couple of properties, afterwards it's a matter of implementing efficient ways / data structures to process the queries accordingly. There are a couple of possible approaches, but it seems easiest to translate it to a 2D ge... | [
"*special",
"data structures",
"geometry",
"math",
"sortings"
] | 2,900 | null |
1386 | C | Joker | Joker returns to Gotham City to execute another evil plan. In Gotham City, there are $N$ street junctions (numbered from $1$ to $N$) and $M$ streets (numbered from $1$ to $M$). Each street connects two distinct junctions, and two junctions are connected by at most one street.
For his evil plan, Joker needs to use an o... | In this task, you are given a graph with $N$ nodes and $M$ edges. Furthermore, you are required to answer $Q$ queries. In every query, all the edges from the interval $[l_i,r_i]$ are temporarily removed and you should check whether the graph contains an odd cycle or not. Thanks for the solutions to the Germany (Subtask... | [
"*special",
"bitmasks",
"data structures",
"divide and conquer",
"dsu"
] | 2,800 | null |
1387 | A | Graph | You are given an undirected graph where each edge has one of two colors: black or red.
Your task is to assign a real number to each node so that:
- for each black edge the sum of values at its endpoints is $1$;
- for each red edge the sum of values at its endpoints is $2$;
- the sum of the absolute values of all assi... | Subtasks 1-4 These subtasks essentially are for the solutions that have the correct idea (see Subtask 5), but with slower implementation. Subtask 5 According to the last example in the task statement it is clear that the graph may actually be a multigraph, i.e., may contain more than one edge between a pair of vertices... | [
"*special",
"binary search",
"dfs and similar",
"dp",
"math",
"ternary search"
] | 2,100 | null |
1387 | B1 | Village (Minimum) | \textbf{This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth $50$ points.}
There are $N$ houses in a certain village. A single villager lives in each of the houses... | Subtask 1 We can try each permutation of villagers, claculate the total distance and find the answer. Complexity: $O(N!)$. Subtask 2 See the Subtask 3 solution; here we can store the tree in slower data structures and work with the tree slower. Complexity: $O(N^2)$. Subtask 3 Each villager needs to move to a new place ... | [
"*special",
"dp",
"greedy",
"trees"
] | 2,100 | null |
1387 | B2 | Village (Maximum) | \textbf{This problem is split into two tasks. In this task, you are required to find the maximum possible answer. In the task Village (Minimum) you are required to find the minimum possible answer. Each task is worth $50$ points.}
There are $N$ houses in a certain village. A single villager lives in each of the houses... | Subtask 1 We can try each permutation of villagers, claculate the total distance and find the answer. Complexity: $O(N!)$. Subtask 2 See the Subtask 3 solution; here we can store the tree in slower data structures and work with the tree slower. Complexity: $O(N^2)$. Subtask 3 In the beginning let's think about each edg... | [
"*special",
"dfs and similar",
"trees"
] | 2,500 | null |
1387 | C | Viruses | The Committee for Research on Binary Viruses discovered a method of replication for a large family of viruses whose genetic codes are sequences of zeros and ones. Each virus originates from a single gene; for simplicity genes are denoted by integers from $0$ to $G - 1$. At each moment in time a virus is a sequence of g... | From reading the task you may think that there aren't enough constraints. This is not true as you actually have enough information. $k$. You are given that the sum of all values $k$ does not exceed 100, so naturally, $1 \leq k \leq 100$. $l$. You are given that the sum of all values $l$ does not exceed 50, so naturally... | [
"*special",
"dp",
"shortest paths",
"string suffix structures"
] | 2,900 | null |
1388 | A | Captain Flint and Crew Recruitment | Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | Consider the three smallest nearly prime numbers: $6, 10$ and $14$: if $n \le 30=6+10+14$, then the answer is NO. otherwise the answer is YES. The easiest way is to display $6, 10, 14, n-30$ in cases where $n-30 \neq 6, 10, 14$. If $n = 36, 40, 44,$ then we can output $6, 10, 15, n-31$. In addition, it was possible to ... | [
"brute force",
"greedy",
"math",
"number theory"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int q;
cin >> q;
while(q--){
int n; cin >> n;
if(n <= 30){
cout << "NO" << endl;
}
else{
cout << "YES" << endl;... |
1388 | B | Captain Flint and a Long Voyage | Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | Statement: $x$ consists of digits $8-9$. This is so, because if $x$ contains digits $0-7$, which in their binary notation are shorter than digits $8-9$, then the number $k$ written on the board, and therefore the number $r$ (obtained by removing the last $n$ digits of the number $k$) will be shorter than if you use onl... | [
"greedy",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int q;
cin >> q;
while (q--) {
int n; cin >> n;
int x = (n + 3) / 4;
for (int i = 0; i < n - x; ++i) {
cout << 9;
}
... |
1388 | C | Uncle Bogdan and Country Happiness | Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.
There are $n$ cities and $n−1$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Citi... | For each city $v$ count $a_v$ - how many people will visit it. Knowing this value and the value of the level of happiness - $h_v$, we can calculate how many people visited the city in a good mood: $g_v=\frac {a_v + h_v} {2}$. We can single out the $3$ criterions for the correctness of the values of the happiness indice... | [
"dfs and similar",
"greedy",
"math",
"trees"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
vector < int > gr[N];
bool access = true;
int p[N], h[N], a[N], g[N];
void dfs(int v, int ancestor = -1) {
a[v] = p[v];
int sum_g = 0;
for (int to : gr[v]) {
if (to == ancestor) continue;
dfs(to, v);
sum_g += ... |
1388 | D | Captain Flint and Treasure | Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like t... | Let's construct a graph $G$ with $n$ vertices and directed edges $(i; b_i)$. Note that it is not profitable to process the vertex $i$ if the vertices $j$, for which $b_j=i$, have not yet been processed, since it is possible to process these vertices $j$ so that they will not decrease $a_i$. We will do the following ope... | [
"data structures",
"dfs and similar",
"graphs",
"greedy",
"implementation",
"trees"
] | 2,000 | #include <bits/stdc++.h>
#define Vanya Unstoppable
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int n;
cin >> n;
long long a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
set < int > s;
for (int ... |
1388 | E | Uncle Bogdan and Projections | After returning to shore, uncle Bogdan usually visits the computer club "The Rock", to solve tasks in a pleasant company. One day, uncle Bogdan met his good old friend who told him one unusual task...
There are $n$ non-intersecting horizontal segments with ends in integers points on the plane with the standard cartesi... | It is easy to understand that there is an optimal vector at which the value we need is minimal and at least one pair of projections is touching. Note also that the vector is completely described by the angle between it and the positive direction of the $OX$ axis. If two line segments are at different heights, then ther... | [
"data structures",
"geometry",
"sortings"
] | 2,700 | #include <bits/stdc++.h>
#define pb push_back
#define x first
#define y second
using namespace std;
const int N = 1e5 + 10;
const double eps = 1e-9;
double xl[N], xr[N], y[N], pi = acos(-1), mn_x, mx_x;
int ind_l, ind_r;
double point_pr(double x, double y, double ctg) {
return x - y * ctg;
}
signed main() {
... |
1389 | A | LCM Problem | Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$.
You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$. | Suppose we have chosen $x$ and $y$ as the answer, and $x$ is not a divisor of $y$. Since $LCM(x, y)$ belongs to $[l, r]$, we could have chosen $x$ and $LCM(x, y)$ instead. So if the answer exists, there also exists an answer where $x$ is a divisor of $y$. If $2l > r$, then there is no pair $(x, y)$ such that $l \le x <... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 800 | t = int(input())
for i in range(t):
l, r = map(int, input().split())
if l * 2 > r:
print(-1, -1)
else:
print(l, l * 2) |
1389 | B | Array Walk | You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ \textbf{positive} integers.
Initially you are standing at index $1$ and have a score equal to $a_1$. You can perform two kinds of moves:
- move right — go from your current index $x$ to $x+1$ and add $a_{x+1}$ to your score. This move can only be perfor... | Notice that your final position is determined by the number of moves to the left you make. Let there be exactly $t$ moves to the left, that leaves us with $k - t$ moves to the right. However, let's interpret this the other way. You have $t$ pairs of moves (right, left) to insert somewhere inside the sequence of $k - 2t... | [
"brute force",
"dp",
"greedy"
] | 1,600 | for _ in range(int(input())):
n, k, z = map(int, input().split())
a = [int(x) for x in input().split()]
ans = 0
s = 0
mx = 0
for i in range(k + 1):
if i < n - 1:
mx = max(mx, a[i] + a[i + 1])
s += a[i]
if i % 2 == k % 2:
tmp = (k - i) // 2
if tmp <= z:
ans = max(ans, s + mx * tmp)
print(ans) |
1389 | C | Good String | Let's call left cyclic shift of some string $t_1 t_2 t_3 \dots t_{n - 1} t_n$ as string $t_2 t_3 \dots t_{n - 1} t_n t_1$.
Analogically, let's call right cyclic shift of string $t$ as string $t_n t_1 t_2 t_3 \dots t_{n - 1}$.
Let's say string $t$ is \textbf{good} if its left cyclic shift is equal to its right cyclic ... | Let's analyze when the string is good. Suppose it is $t_1t_2 \dots t_k$. The cyclic shifts of this string are $t_kt_1t_2 \dots t_{k-1}$ and $t_2t_3 \dots t_k t_1$. We get the following constraints for a good string: $t_k = t_2$, $t_1 = t_3$, $t_2 = t_4$, ..., $t_{k - 2} = t_k$, $t_{k - 1} = t_1$. If the string has odd ... | [
"brute force",
"dp",
"greedy",
"two pointers"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
int solve(const string& s, int x, int y) {
int res = 0;
for (auto c : s) if (c - '0' == x) {
++res;
swap(x, y);
}
if (x != y && res % 2 == 1)
--res;
return res;
}
void solve() {... |
1389 | D | Segment Intersections | You are given two lists of segments $[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$ and $[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$.
Initially, all segments $[al_i, ar_i]$ are equal to $[l_1, r_1]$ and all segments $[bl_i, br_i]$ are equal to $[l_2, r_2]$.
In one step, you can choose one segment (either from ... | At first, note that intersection_length of segments $[l_1, r_1]$ and $[l_2, r_2]$ can be calculated as $\min(r_1, r_2) - \max(l_1, l_2)$. If it's negative then segments don't intersect, otherwise it's exactly length of intersection. Now we have two major cases: do segments $[l_1, r_1]$ and $[l_2, r_2]$ already intersec... | [
"brute force",
"greedy",
"implementation",
"math"
] | 2,100 | import kotlin.math.*
fun main() {
repeat(readLine()!!.toInt()) {
val (n, k) = readLine()!!.split(' ').map { it.toLong() }
val (l1, r1) = readLine()!!.split(' ').map { it.toLong() }
val (l2, r2) = readLine()!!.split(' ').map { it.toLong() }
var ans = 1e18.toLong()
if (max(l1... |
1389 | E | Calendar Ambiguity | Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days.
A pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of m... | Let the month, the days in them and the days of the week be numbered $0$-based. Translate the $x$-th day of the $y$-th month to the index of that day in a year; that would be $yd + x$. Thus, the corresponding day of the week is $(yd + x)~mod~w$. So we can rewrite the condition for a pair as $xd + y \equiv yd + x~(mod~w... | [
"math",
"number theory"
] | 2,200 | fun gcd(a: Long, b: Long): Long {
if (a == 0L) return b
return gcd(b % a, a)
}
fun main() {
repeat(readLine()!!.toInt()) {
val (m, d, w) = readLine()!!.split(' ').map { it.toLong() }
val w2 = w / gcd(d - 1, w)
val mn = minOf(m, d)
var cnt = mn / w2
println((2 * (mn - w2) - w2 * (cnt - 1)) * cnt / 2)
}
} |
1389 | F | Bicolored Segments | You are given $n$ segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$. Each segment has one of two colors: the $i$-th segment's color is $t_i$.
Let's call a pair of segments $i$ and $j$ bad if the following two conditions are met:
- $t_i \ne t_j$;
- the segments $[l_i, r_i]$ and $[l_j, r_j]$ intersect, embed or touc... | There are two approaches to this problem. Most of the participants of the round got AC by implementing dynamic programming with data structures such as segment tree, but I will describe another solution which is much easier to code. Let's consider a graph where each vertex represents a segment, and two vertices are con... | [
"data structures",
"dp",
"graph matchings",
"sortings"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#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)
typedef pair<int, int> pt;
const int INF = 1e9;
const int N = 200 * 1000;
... |
1389 | G | Directing Edges | You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. $k$ vertices of this graph are special.
You have to direct each edge of this graph or leave it undirected. If you leave the $i$-th edge undirected, you pay $w_i$ coins, and if you direct it, you don't have to pay for it.
Let's call ... | Suppose we want to calculate the maximum profit for some vertex in $O(n)$. Let's try to find out how it can be done, and then optimize this process so we don't have to run it $n$ times. First of all, we have to find the bridges and biconnected components in our graph. Why do we need them? Edges in each biconnected comp... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
const int N = 300043;
bool is_bridge[N];
int w[N];
int c[N];
int v[N];
vector<pair<int, int> > g[N];
vector<pair<int, int> > g2[N];
int comp[N];
li sum[N];
li dp[N];
int cnt[N];
int fup[N];
int tin[N];
int T = 0;
li ans[N];
int v1[N], v2[N];
int n... |
1391 | A | Suborrays | A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
For a positive ... | Every permutation is good. Proof: We use the fact that for any set of numbers, it's bitwise OR is at least the maximum value in it. Now, we just need to show that any subarray of length $len$ has at least one element greater than or equal to $len$. If the maximum element is $< len$, then, we have $len$ elements all wit... | [
"constructive algorithms",
"math"
] | 800 | #include<bits/stdc++.h>
using namespace std;
mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());
void solve(){
int n;
cin >> n;
vector<int> all;
for(int i = 1;i <= n;i++)all.push_back(i);
shuffle(all.begin(),all.end(),rng);
for(int i = 0;i < n;i++){
cout <... |
1391 | B | Fix You | Consider a conveyor belt represented using a grid consisting of $n$ rows and $m$ columns. The cell in the $i$-th row from the top and the $j$-th column from the left is labelled $(i,j)$.
Every cell, except $(n,m)$, has a direction R (Right) or D (Down) assigned to it. If the cell $(i,j)$ is assigned direction R, any l... | The answer is $#R in the last column + #D in the last row$. It's obvious that we must change all Rs in the last column and all Ds in the last row. Otherwise, anything placed in those cells will move out of the grid. We claim that doing just this is enough to make the grid functional. Indeed, for any other cell, any lug... | [
"brute force",
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int n,m;
void solve(){
cin >> n >> m;
int ans = 0;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
char o;cin >> o;
if(o == 'C')continue;
if(i == n and o == 'D')ans++;
if(j == m and o == 'R')ans++;
}
}
cout << ans << endl;
}
int main(){
i... |
1391 | C | Cyclic Permutations | A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
Consider a perm... | The answer is $n!-2^{n-1}$. Consider an arbitrary cyclic permutation - for example, [4,2,3,1,5,6]; it contains many cycles of length $3$: $[1,2,3]$, $[1,3,5]$, $[3,4,5]$. Note that all the listed cycles contain nodes obtained from just one choice of $i$. We can generalize this to the following. If for any $i$, we make ... | [
"combinatorics",
"dp",
"graphs",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int MOD = 1e9+7;
int n;
int res,fact;
signed main(){
cin >> n;
res = 1;
fact = 1;
for(int i = 1;i <= n-1;i++){
res *= 2;
fact *= i;
fact %= MOD;
res %= MOD;
}
fact *= n;
fact %= MOD;
fact -= res;
fact %= MOD;
if(fact < 0... |
1391 | D | 505 | A binary matrix is called \textbf{good} if every \textbf{even} length square sub-matrix has an \textbf{odd} number of ones.
Given a binary matrix $a$ consisting of $n$ rows and $m$ columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all.
... | Firstly, if $min(n,m) > 3$, then, no solution exists because this means the grid contains at least one $4\times4$ sub-matrix, which can further be decomposed into four $2\times2$ sub-matrices. Since all four of these $2\times2$ sub-matrices are supposed to have an odd number of ones, the union of them will have an even... | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"greedy",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5+1;
int n,m;
int a[4][N];
int dp3[N][8];
int dp2[N][4];
bool ok3[8][8];
bool ok2[4][4];
void fill3(){
for(int i = 0;i < 8;i++){
for(int j = 0;j < 8;j++){
bool bad = 0;
for(int st = 0;st < 2;st++){
int bits = (bool)(i&(1<<st))+(bool)(i&(1<<(... |
1391 | E | Pairs of Pairs | You have a simple and connected undirected graph consisting of $n$ nodes and $m$ edges.
Consider any way to pair some subset of these $n$ nodes such that no node is present in more than one pair.
This pairing is \textbf{valid} if for every pair of pairs, the induced subgraph containing all $4$ nodes, two from each pa... | Let's build the DFS tree of the given graph, and let $dep(u)$ denote the depth of node $u$ in the tree. If $dep(u) \ge \lceil \frac{n}{2} \rceil$ holds for any node $u$, we have found a path. Otherwise, the maximum depth is at most $\lfloor \frac{n}{2} \rfloor$, and we can find a valid pairing as follows: For every dep... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5+1;
int n,m;
vector<int> adj[N];
bool vis[N];
vector<int> all[N];
int dep[N];
int par[N];
int pairs = 0;
bool outputted = 0;
void dfs(int u){
if(outputted)return;
vis[u] = 1;
pairs -= all[dep[u]].size()/2;
all[dep[u]].push_back(u);
pairs += all[d... |
1392 | A | Omkar and Password | Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array $a$ of $n$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace t... | If your array consists of one number repeated $n$ times, then you obviously can't do any moves to shorten the password. Otherwise, you can show that it is always possible to shorten the password to $1$ number. For an array consisting of $2$ or more distinct elements, considering the maximum value of the array. If its m... | [
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
#define len(v) ((int)((v).size()))
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define chmax(x, v) x = max((x), (v))
#define chmin(x, v) x = min((x), (v))
using namespace std;
using ll = long long;
void solve() {
int n; cin >> n;
vector<int> vec(n);
for (i... |
1392 | B | Omkar and Infinity Clock | Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array $a$ of $n$ integers. You are also given an integer $k$. Lord Omkar wants you to do... | There's only two possible states the array can end up as. Which state it becomes after $k$ turns is determined solely by the parity of $k$. After the first move, the array will consists of all non-negative numbers ($d-a_{i}$ will never be negative because $a_{i}$ never exceeds $d$). After one turn, let's define $x$ as ... | [
"implementation",
"math"
] | 800 | #include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <cassert>
std::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());
int main() {
std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);
int t;
std::cin >> t;
while(t--) {
int n;
long long k;
std... |
1392 | C | Omkar and Waterslide | Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing... | Call the initial array $a$. We claim that the answer is $\sum max(a_i-a_{i+1}, 0)$ over the entire array of supports (call this value $ans$). Now let's show why. First, notice that in a nondecreasing array, $ans = 0$. So, the problem is now to apply operations to the array such that $ans = 0$. Now, let's see how applyi... | [
"greedy",
"implementation"
] | 1,200 | #include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <cassert>
std::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());
int main() {
std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);
int t;
std::cin >> t;
while(t--) {
int n;
std::cin >> n;
l... |
1392 | D | Omkar and Bed Wars | Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $n$ players arranged in a circle, so that for all $j$ such that $2 \leq j \leq n$, player $j - 1$ is to the left of the player $j$, and player $j$ is to the right of player $j - 1$. Additionally, player $n$ is to the left of player $1$... | As described in the statement, the only situation in which a player is not acting logically according to Bed Wars strategy is when they are being attacked by exactly $1$ player, but they are not attacking that player in response. Let the player acting illogically be player $j$. There are two cases in which player $j$ i... | [
"dp",
"greedy"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, ans = 0;
cin >> n;
string s;
cin >> s;
int cnt = 0;
while(s.size() && s[0] == s.back()) {
cnt++;
s.pop_back();
}
if(s.empty()) {
if(cnt <= 2) {
cout << "0\n";
return;
... |
1392 | E | Omkar and Duck | \textbf{This is an interactive problem.}
Omkar has just come across a duck! The duck is walking on a grid with $n$ rows and $n$ columns ($2 \leq n \leq 25$) so that the grid contains a total of $n^2$ cells. Let's denote by $(x, y)$ the cell in the $x$-th row from the top and the $y$-th column from the left. Right now,... | The problem essentially boils down to constructing a grid such that any path from $(1, 1)$ to $(n, n)$ has a different sum and you can easily determine any path from its sum. You can do this using the following construction: for all $(x, y)$, if $x$ is even, then let $a_{x,y} = 2^{x + y}$; otherwise, let $a_{x,y} = 0$.... | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 2,100 | #include <bits/stdc++.h>
#define len(v) ((int)((v).size()))
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define chmax(x, v) x = max((x), (v))
#define chmin(x, v) x = min((x), (v))
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int ... |
1392 | F | Omkar and Landslide | Omkar is standing at the foot of Celeste mountain. The summit is $n$ meters away from him, and he can see all of the mountains up to the summit, so for all $1 \leq j \leq n$ he knows that the height of the mountain at the point $j$ meters away from himself is $h_j$ meters. It turns out that for all $j$ satisfying $1 \l... | Fun fact: This problem was originally proposed as B. TL;DR: We can show that in the resulting array, every pair of adjacent elements differs by exactly $1$ except that there may be at most one pair of adjacent equal elements. It is easy to see that there is only one such array satisfying that condition that also has th... | [
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0);
ll n;
cin >> n;
ll s = 0;
for (ll x, i = 0; i < n; ++i)
cin >> x, s += x;
ll l = (s - n * (n-1) / 2) / n + 1;
s = l * n + n * (n-1) / 2 - s;
for (int i = 0; i < n; ++i)
cout << l + ... |
1392 | G | Omkar and Pies | Omkar has a pie tray with $k$ ($2 \leq k \leq 20$) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.
To assist Omkar, $n$ elves have gathered in a line... | Consider any two binary strings $u$ and $v$ of length $k$. Notice that if you swap the bits at positions $\alpha$ and $\beta$ in $u$ and also swap the bits at positions $\alpha$ and $\beta$ in $v$, then the amount of common bits in $u$ and $v$ remains the same. Furthermore, you can do this multiple times - i. e. applyi... | [
"bitmasks",
"dfs and similar",
"dp",
"math",
"shortest paths"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
int p[20],dp[2][(1<<20)];
int getmask(string s)
{
int ans=0;
for (int i=0;i<s.size();i++)
ans|=((s[i]-'0')<<i);
return ans;
}
int main()
{
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
string a,b;
cin >> a >> b;
for (int i=0;i<k;i++)
p[i]=i;
for (int i=0;i<(1<<k);i++)
{
... |
1392 | H | ZS Shuffles Cards | zscoder has a deck of $n+m$ custom-made cards, which consists of $n$ cards labelled from $1$ to $n$ and $m$ jokers. Since zscoder is lonely, he wants to play a game with himself using those cards.
Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set $S$ which is initially empty... | Firstly, let's find a simple dp. Let $f(x)$ denote the expected time before the game ends with the deck is full (with $n+m$ cards) and $S$ contains $n - x$ elements. Hence, $f(0)=0$. Our goal is to find $f(n)$. Suppose the jokers are also numbered from $1$ to $m$ and $S$ contains $n-x$ elements. Consider the cards draw... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 3,000 | const val MOD = 998244353L
fun main() {
val (n, m) = readLine()!!.split(" ").map { it.toInt() }
val factorial = LongArray(4000002)
factorial[0] = 1L
for (j in 1..4000001) {
factorial[j] = (j.toLong() * factorial[j - 1]) % MOD
}
val factInv = LongArray(4000002)
factInv[4000001] = fac... |
1392 | I | Kevin and Grid | As Kevin is in BigMan's house, suddenly a trap sends him onto a grid with $n$ rows and $m$ columns.
BigMan's trap is configured by two arrays: an array $a_1,a_2,\ldots,a_n$ and an array $b_1,b_2,\ldots,b_m$.
In the $i$-th row there is a heater which heats the row by $a_i$ degrees, and in the $j$-th column there is a ... | An obvious solution would be to do DFS, but it is $O(nmq)$. Firstly we focus on answering a single question. We represent our input with two graphs (one for cells with temperature less than X and other for temperatures greater than X), in which we add an edge between two neigbouring cells. As it is a subgraph of the gr... | [
"fft",
"graphs",
"math"
] | 3,300 | #include<bits/stdc++.h>
using namespace std;
#define MAX 262144
#define MAXN 1000000
long long int a[MAXN],b[MAXN];
using cd = complex<double>;
const double PI = acos(-1);
vector<cd> A(MAX),B(MAX);
vector<cd> Amx(MAX),Bmx(MAX);
vector<cd> Amn(MAX),Bmn(MAX);
vector<cd> E11(MAX),E12(MAX),E21(MAX),E22(MAX);
vector<cd> ... |
1393 | A | Rainbow Dash, Fluttershy and Chess Coloring | One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.
The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with siz... | By modeling the game on different grids it was possible to notice that the answer is equal to $\lfloor \frac{n}{2} \rfloor + 1$. You can prove that this is the answer by using induction method separately for grids with even and odd sides. Initially it was asked to solve the problem for rectangular grids. You can think ... | [
"greedy",
"math"
] | 800 | #include<bits/stdc++.h>
using namespace std;
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, n;
cin >> t;
while (t--) {
cin >> n;
cout << n / 2 + 1 << '\n';
}
return 0;
} |
1393 | B | Applejack and Storages | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).
A... | Let's maintain the array $cnt_i$, in it we are going to store the number of planks for each length. Let's note that to be able to build a square and a rectangle we need to have four planks of the same length and also two pairs of planks of the same length. To check it we can maintain two values: $sum2=\sum_{i=1}^{10^5}... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
int const MAXN = 1e5 + 5;
int cnt[MAXN];
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, q, x, cnt2 = 0, cnt4 = 0;
char type;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> x;
cnt2 -= cnt[x... |
1393 | C | Pinkie Pie Eats Patty-cakes | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t... | Let's note that if you can find the arrangement with the maximum distance $\geq X$, then you can also find the arrangement with the maximum distance $\geq X-1$. It allows you to use the binary search on the answer. To check that the answer is at least $X$, we can use the greedy algorithm. Each time let's use the elemen... | [
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100009;
int cnt[MAXN];
vector<int> a;
int n;
bool check(int x) {
for (int i = 1; i <= n; i ++) cnt[i] = 0;
for (int i = 0; i < n; i ++) cnt[a[i]]++;
set<pair<int, int>, greater<pair<int, int>>> ss; //use greater comparator to sort set in des... |
1393 | D | Rarity and New Dress | Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.
The piec... | Let's note that if there is a rhombus of size $X$ in the cell $(i, j)$, then there are also rhombuses with the smaller sizes. Let's divide the rhombus into the left part and the right part. Let's solve the problem separately for both of them and then the answer for the cell is going to be equal to the minimum of these ... | [
"dfs and similar",
"dp",
"implementation",
"shortest paths"
] | 2,100 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int const maxn = 2005;
char a[maxn][maxn];
int cnt_up[maxn][maxn], cnt_down[maxn][maxn], L[maxn], R[maxn];
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {... |
1393 | E2 | Twilight and Ancient Scroll (harder version) | This is a harder version of the problem E with larger constraints.
Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.
To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. ... | Let's use dynamic programming. $dp[i][j]$: the number of ways to form the non-decreasing subsequence on the strings $1 \ldots i$, s.t. the delete character in string $i$ is $j$. This works in $O(L^3)$, where $L$ is the total length of all strings. Let's optimize this solution. For each string, sort all strings obtained... | [
"dp",
"hashing",
"implementation",
"string suffix structures",
"strings",
"two pointers"
] | 3,200 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int const maxn = 1e5 + 5, maxc = 1e6 + 5;
ll mod[2], P[2], p[2][maxc], rev_P[2];
vector < ll > h[2][maxn];
vector < int > sorted[maxn];
string s[maxn];
int nxt[maxc];
int a[maxc], dp[2][maxc], inf = 1e9 + 7;
int MOD = 1e9 + 7;
ll st(ll x, int y, int ... |
1394 | A | Boboniu Chats with Du | Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for $n$ days. On the $i$-th day:
- If Du can speak, he'll make fun of Boboni... | If $a_i>m$, we consider it as a big item with value $a_i$, else a small item with value $a_i$. We are asked to choose some items and maximize the total value. If an item is not chosen, it means we put it on a muzzled day. Enumerate the number of chosen big item, which is denoted by $x$. Thus they take $(x-1)(d+1)+1$ da... | [
"dp",
"greedy",
"sortings",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
#define rep(i, a, b) for (int i = (a); i <= int(b); i++)
using namespace std;
typedef long long ll;
const int maxn = 1e5;
int n, d, m, k, l;
ll a[maxn + 5], b[maxn + 5];
void solve(ll a[], int n) {
sort(a + 1, a + n + 1);
reverse(a + 1, a + n + 1);
rep(i, 1, n) a[i] += a[i - 1];
}
int mai... |
1394 | B | Boboniu Walks on Graph | Boboniu has a \textbf{directed} graph with $n$ vertices and $m$ edges.
The out-degree of each vertex is at most $k$.
Each edge has an integer weight between $1$ and $m$. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple $(c_1,c_2,\ldots,c_k)... | Let $\deg u$ denote the out degree of $u$. Let $nex_{u,i}$ denote the vertex, which the edge with the $i$-the smallest weight among all edges start from $u$ ends at. For a fixed tuple $(t_1,t_2,\ldots,t_k)$, if $\{ nex_{i,t_{\deg i}} | 1\le i\le n \}=\{1,2,\ldots,n\}$ (i. e. each vertex appears exactly once), then it i... | [
"brute force",
"dfs and similar",
"graphs",
"hashing"
] | 2,300 | //by Sshwy
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define ROF(i,a,b) for(int i=(a);i>=(b);--i)
mt19937 mt_rand(chrono::high_resolution_clock::now().time_since_epoch().count());
const int N=2e5+5,HS=3,K=10;
int n,m,k;
vector< pair<int,int> > g[N];
... |
1394 | C | Boboniu and String | Boboniu defines BN-string as a string $s$ of characters 'B' and 'N'.
You can perform the following operations on the BN-string $s$:
- Remove a character of $s$.
- Remove a substring "BN" or "NB" of $s$.
- Add a character 'B' or 'N' to the end of $s$.
- Add a string "BN" or "NB" to the end of $s$.
Note that a string ... | It's obvious that the operation of BN-string is equivalent to the operation of BN-set, which I'm talking about, for a multi set $s$ contains only B and N: Remove a B or an N (if exists) from $s$. Insert a B or an N into $s$. Remove a B and an N from $s$. Insert a B and an N into $s$. So let's use pair $(x,y)$ to denote... | [
"binary search",
"geometry",
"ternary search"
] | 2,600 | //by Sshwy
#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define ROF(i,a,b) for(int i=(a);i>=(b);--i)
const int INF=1e9;
int n;
int main(){
cin>>n;
int lx=INF,rx=-INF,ly=INF,ry=-INF,lz=INF,rz=-INF;
FOR(i,1,n){
string s;
cin>>s;
int x=0,y=... |
1394 | D | Boboniu and Jianghu | Since Boboniu finished building his Jianghu, he has been doing Kungfu on these mountains every day.
Boboniu designs a map for his $n$ mountains. He uses $n-1$ roads to connect all $n$ mountains. Every pair of mountains is connected via roads.
For the $i$-th mountain, Boboniu estimated the tiredness of doing Kungfu on... | Generally speaking, you're asked to use some simple directed paths (challenges) to cover the original tree and minimize the total cost (tiredness). Those edges with $h_u \neq h_v$ are already oriented, and for the other ones, we need to determine their directions. At first, let's consider the case where each edge has a... | [
"dp",
"greedy",
"sortings",
"trees"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5;
int n, h[maxn + 3], t[maxn + 3], in[maxn + 3], out[maxn + 3];
vector<int> G[maxn + 3];
bool vis[maxn + 3];
ll ans, f[maxn + 3], g[maxn + 3], a[maxn + 3];
void dfs(int u, int fa = 0) {
vis[u] = true;
for (int i = 0, v; i < G[u]... |
1394 | E | Boboniu and Banknote Collection | No matter what trouble you're in, don't be afraid, but face it with a smile.
I've made another billion dollars!
— Boboniu
Boboniu has issued his currencies, named Bobo Yuan. Bobo Yuan (BBY) is a series of currencies. Boboniu gives each of them a positive integer identifier, such as BBY-1, BBY-2, etc.
Boboniu has a ... | At first, I'd like to explanation the fold operation in a intuitive way. Section 1 Fold To be exact, the origin problem isn't ask us to calculate the number of folds, but the number of folding marks. Section 1.1 Example 1 For example, you can fold $[1,1,1,1]$ three times, but you have different method to fold it: Metho... | [
"strings"
] | 3,500 | //by Sshwy
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define ROF(i,a,b) for(int i=(a);i>=(b);--i)
const int N=1e5+5;
int n,a[N],xyx,q[N],c[N],p[N];
vector<int> v[N];
int pos;
void get_v(int pos){
v[pos].clear();
if(pos==1)return;
if(a[p... |
1395 | A | Boboniu Likes to Color Balls | Boboniu gives you
- $r$ red balls,
- $g$ green balls,
- $b$ blue balls,
- $w$ white balls.
He allows you to do the following operation as many times as you want:
- Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the balls into a ... | If there are less than or equal to one odd number in $r$, $b$, $g$, $w$, then you can order them to be a palindrome. Otherwise, do the operation once (if you can) and check the condition above. It is meaningless to do operation more than once because we only care about the parity of $r$, $b$, $g$, $w$. | [
"brute force",
"math"
] | 1,000 | def check(r,g,b,w):
return False if r%2 + g%2 + b%2 + w%2 > 1 else True
if __name__ == '__main__':
T = int(input())
for ttt in range(T):
r,g,b,w = map(int,input().split())
if check(r,g,b,w):
print("Yes")
elif r>0 and g>0 and b>0 and check(r-1,g-1,b-1,w+1):
pr... |
1395 | B | Boboniu Plays Chess | Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a $n\times m$ grid (rows are numbered from $1$ to $n$, and col... | There are many solutions and I will describe one of them. Let say $f(i,j) = ( (i+S_x-2)\bmod n+1, (j+S_y-2)\bmod m+1 )$. Iterate $i$ from $1$ to $n$: if $i$ is odd, print $f(i,1),f(i,2),\ldots,f(i,m)$. Else print $f(i,m),f(i,m-1),\ldots,f(i,1)$. | [
"constructive algorithms"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define ROF(i,a,b) for(int i=(a);i>=(b);--i)
int n,m,sx,sy;
void f(int i,int j){
printf("%d %d\n",(i+sx-2)%n+1,(j+sy-2)%m+1);
}
int main(){
scanf("%d%d%d%d",&n,&m,&sx,&sy);
FOR(i,1,n){
if(i&1)FOR(j,1,m)f(i,j)... |
1395 | C | Boboniu and Bit Operations | Boboniu likes bit operations. He wants to play a game with you.
Boboniu gives you two sequences of non-negative integers $a_1,a_2,\ldots,a_n$ and $b_1,b_2,\ldots,b_m$.
For each $i$ ($1\le i\le n$), you're asked to choose a $j$ ($1\le j\le m$) and let $c_i=a_i\& b_j$, where $\&$ denotes the bitwise AND operation. Note... | Suppose the answer is $A$. Thus for all $i$ ($1\le i\le n$), $c_i | A = A$. Since $a_i, b_i <2^9$, we can enumerate all integers from $0$ to $2^9-1$, and check if there exists $j$ for each $i$ that $(a_i \& b_j) | A = A$. The minimum of them will be the answer. The time complexity is $O(2^9\cdot n^2)$ | [
"bitmasks",
"brute force",
"dp",
"greedy"
] | 1,600 | #include<bits/stdc++.h>
#define ci const int&
using namespace std;
int n,m,p[210],d[210],ans;
bool Check(ci x){
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j)if(((p[i]&d[j])|x)==x)goto Next;
return 0;
Next:;
}
return 1;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)scanf("%d",&p[i]);
for(int i=1;i<=... |
1396 | A | Multiples of Length | You are given an array $a$ of $n$ integers.
You want to make all elements of $a$ equal to zero by doing the following operation \textbf{exactly three} times:
- Select a segment, for each number in this segment we can add a multiple of $len$ to it, where $len$ is the length of this segment (added integers can be diffe... | In this problem, the answer is rather simple. Here is one possible solution to this task. $1 \space \space 1$ $0$ $1 \space \space 1$ $0$ $1 \space \space 1$ $-a_1$ $1 \space \space 1$ $-a_1$ $1 \space \space n$ $0, \space -n \cdot a_2, \space -n \cdot a_3, \space \dots , \space -n \cdot a_n$ $2 \space \space n$ $(n-1)... | [
"constructive algorithms",
"greedy",
"number theory"
] | 1,600 | n = int(input())
a = list(map(int, input().split()))
if n == 1:
print('1 1', -a[0], '1 1', '0', '1 1', '0', sep='\n')
exit(0)
print(1, n)
for i in range(n):
print(-a[i] * n, end = ' ')
a[i] -= a[i] * n
print()
print(1, n - 1)
for i in range(n - 1):
print(-a[i], end = ' ')
a[i] = 0
print()
pr... |
1396 | B | Stoned Game | T is playing a game with his friend, HL.
There are $n$ piles of stones, the $i$-th pile initially has $a_i$ stones.
T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen ... | Let us denote $S$ as the current total number of stones. Consider the following cases: Case A: There is a pile that has more than $\lfloor \frac{S}{2} \rfloor$ stones. The first player (T) can always choose from this pile, thus he (T) is the winner. Case B: Every pile has at most $\lfloor \frac{S}{2} \rfloor$ stones, a... | [
"brute force",
"constructive algorithms",
"games",
"greedy"
] | 1,800 | t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
maxPile = max(a)
numStones = sum(a)
if maxPile * 2 > numStones or (numStones & 1):
print('T')
else:
print('HL') |
1396 | C | Monster Invaders | Ziota found a video game called "Monster Invaders".
Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.
For the sake of simplicity, we only consider two different types of monsters and three different types of guns.
Namely, the two types of monsters are:
- a ... | In this problem, it is useful to note that when the boss only has $1$ hp left, just use the pistol because it has the least reloading time. So there are 3 strategies we will use when playing at stage $i$ $(1 \le i \le n)$: Take $a_i$ pistol shots to kill first $a_i$ monsters and shoot the boss with the AWP. Take $a_i +... | [
"dp",
"greedy",
"implementation"
] | 2,300 | /*input
4 2 4 4 1
4 5 1 2
*/
#include <bits/stdc++.h>
using namespace std;
int read() {
int x = 0, c = getchar();
for(; !(c > 47 && c < 58); c = getchar());
for(; (c > 47 && c < 58); c = getchar()) x = x * 10 + c - 48;
return x;
}
void upd(long long &a, long long b) {
a = (a < b) ? a : b;
}
const int N = 1e6 + ... |
1396 | D | Rainbow Rectangles | Shrimpy Duc is a fat and greedy boy who is always hungry. After a while of searching for food to satisfy his never-ending hunger, Shrimpy Duc finds M&M candies lying unguarded on a $L \times L$ grid. There are $n$ M&M candies on the grid, the $i$-th M&M is currently located at $(x_i + 0.5, y_i + 0.5),$ and has color $c... | Let $xl, xr, yd, yu$ denote a rectangle with opposite corners $(xl, yd)$ and $(xr, yu)$. For convenience, assume $(xl \le xr)$ and $(yd \le yu)$. Let's try solving the problem if coordinates are in range $[1, n]$. We could easily do this by coordinates compression. First, let's look at the problem with $(yd, yu)$ fixed... | [
"data structures",
"sortings",
"two pointers"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MOD = 1000000007;
int L;
ll sum[8040];
int len[8040];
int last[8040];
int lazy[8040];
void init(int v, int l, int r, const vector<int> &xs) {
len[v] = xs[r] - xs[l - 1];
if (l < r) {
int md = (l + r) >> 1;
init(v << 1, l... |
1396 | E | Distance Matching | You are given an integer $k$ and a tree $T$ with $n$ nodes ($n$ is even).
Let $dist(u, v)$ be the number of edges on the shortest path from node $u$ to node $v$ in $T$.
Let us define a undirected weighted complete graph $G = (V, E)$ as following:
- $V = \{x \mid 1 \le x \le n \}$ i.e. the set of integers from $1$ to... | Root the tree at centroid $c$. First, determine if there is any matching that satisfies the requirement. Consider an edge $e$ that splits the tree into $2$ subtrees with sizes $x$ and $N - x$ respectively, let $z$ be the number of paths passing through $e$, then we have $z$ has the same parity as $x$ and $x \% 2 \le z ... | [
"constructive algorithms",
"dfs and similar",
"trees"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
int N; ll K;
cin >> N >> K;
vector<vector<int>> adj(N);
for (int i = 0; i < N - 1; ++i) {
int v, u;
cin >> v >> u;
adj[--v].emplace_back(--u);
ad... |
1397 | A | Juggling Letters | You are given $n$ strings $s_1, s_2, \ldots, s_n$ consisting of lowercase Latin letters.
In one operation you can remove a character from a string $s_i$ and insert it to an arbitrary position in a string $s_j$ ($j$ may be equal to $i$). You may perform this operation any number of times. Is it possible to make all $n$... | If the total number of occurrences of some character $c$ is not a multiple of $n$, then it is impossible to make all $n$ strings equal - because then it is impossible for all $n$ strings to have the same number of $c$. On the other hand, if the total number of occurrences of every character $c$ is a multiple of $n$, th... | [
"greedy",
"strings"
] | 800 | numTests = int(input())
for testNo in range(numTests):
n = int(input())
cnt = [0 for i in range(26)]
for _ in range(n):
s = input()
for i in s:
cnt[ord(i) - 97] += 1
ans = True
for i in range(26):
if cnt[i] % n != 0:
ans = False
break
if ans:
print('YES')
else:
... |
1397 | B | Power Sequence | Let's call a list of positive integers $a_0, a_1, ..., a_{n-1}$ a \textbf{power sequence} if there is a positive integer $c$, so that for every $0 \le i \le n-1$ then $a_i = c^i$.
Given a list of $n$ positive integers $a_0, a_1, ..., a_{n-1}$, you are allowed to:
- Reorder the list (i.e. pick a permutation $p$ of $\{... | First of all, the optimal way to reorder is to sort $a$ in non-decreasing order. Note that the cost the transform $a_i$ to $c^i$ is $\lvert a_i - c^i \rvert$. While there is a pair $(a_i, a_j)$ such that $i < j$ and $a_i > a_j$, swap $a_i$ and $a_j$. Since $\lvert x \rvert + \lvert y \rvert = max \{ \lvert x + y \rvert... | [
"brute force",
"math",
"number theory",
"sortings"
] | 1,500 | n = int(input())
a = [int(x) for x in input().split()]
a.sort()
inf = 10**18
if n <= 2:
print(a[0] - 1)
else:
ans = sum(a) - n
for x in range(1, 10**9):
curPow = 1
curCost = 0
for i in range(n):
curCost += abs(a[i] - curPow)
curPow *= x
if curPow... |
1398 | A | Bad Triangle | You are given an array $a_1, a_2, \dots , a_n$, which is sorted in non-decreasing order ($a_i \le a_{i + 1})$.
Find three indices $i$, $j$, $k$ such that $1 \le i < j < k \le n$ and it is \textbf{impossible} to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $a_i$, $a_j$ and $a... | The triangle with side $a \ge b \ge c$ is degenerate if $a \ge b + c$. So we have to maximize the length of the longest side ($a$) and minimize the total length of other sides ($b + c$). Thus, if $a_n \ge a_1 + a_2$ then we answer if $1, 2, n$, otherwise the answer is -1. | [
"geometry",
"math"
] | 800 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
if a[0] + a[1] > a[-1]:
print(-1)
else:
print(1, 2, n) |
1398 | B | Substring Removal Game | Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of \textbf{consecutive equal characters} in $s$ and delete them.
Fo... | The following greedy strategy works: during each turn, delete the largest possible substring consisting of $1$-characters. So we have to find all blocks of $1$-characters, sort them according to their length and model which blocks are taken by Alice, and which - by Bob. Why does the greedy strategy work? It's never opt... | [
"games",
"greedy",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
void solve() {
string s;
cin >> s;
vector<int> a;
forn(i, sz(s)) if (s[i] == '1') {
int j = i;
while (j + 1 < sz(s) && s[j + 1] == '1')
++j;
a.push_back(j - i + 1);
i = j;
}... |
1398 | C | Good Subarrays | You are given an array $a_1, a_2, \dots , a_n$ consisting of integers from $0$ to $9$. A subarray $a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$ is good if the sum of elements of this subarray is equal to the length of this subarray ($\sum\limits_{i=l}^{r} a_i = r - l + 1$).
For example, if $a = [1, 2, 0]$, then there ... | We use zero indexing in this solution. We also use half-closed interval (so subarray $[l, r]$ is $a_l, a_{l + 1}, \dots, a_{r-1}$). Let's precalculate the array $p$, where $p_i = \sum\limits_{j = 0}^{i - 1} a_j$ (so $p_x$ if sum of first $x$ elements of $a$). Then subarray $[l, r]$ is good if $p_r - p_l = r - l$, so $p... | [
"data structures",
"dp",
"math"
] | 1,600 | for _ in range(int(input())):
n = int(input())
a = input()
d = {0 : 1}
res, s = 0, 0
for i in range(n):
s += int(a[i])
x = s - i - 1
if x not in d:
d[x] = 0
d[x] += 1
res += d[x] - 1
print(res) |
1398 | D | Colored Rectangles | You are given three multisets of pairs of colored sticks:
- $R$ pairs of red sticks, the first pair has length $r_1$, the second pair has length $r_2$, $\dots$, the $R$-th pair has length $r_R$;
- $G$ pairs of green sticks, the first pair has length $g_1$, the second pair has length $g_2$, $\dots$, the $G$-th pair has... | Let's build some rectangles and take a look at the resulting pairings. For example, consider only red/green rectangles. Let the rectangles be $(r_{i1}, g_{i1})$, $(r_{i2}, g_{i2})$, .... Sort them in a non-decreasing order of $r_{ij}$. I claim that in the most optimal set $g_{ij}$ are also sorted in a non-decreasing or... | [
"dp",
"greedy",
"sortings"
] | 1,800 | n = [int(x) for x in input().split()]
a = []
for i in range(3):
a.append([int(x) for x in input().split()])
a[i].sort(reverse=True)
dp = [[[0 for i in range(n[2] + 1)] for j in range(n[1] + 1)] for k in range(n[0] + 1)]
ans = 0
for i in range(n[0] + 1):
for j in range(n[1] + 1):
for k in range(n[2] + 1):
if i ... |
1398 | E | Two Types of Spells | Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and \textbf{doubles} the damage of the next spell Polycarp casts. Eac... | Let's solve this problem for fixed set of spells. For example, we have a fireball spells with powers $f_1, f_2, \dots , f_m$ and lighting spells with powers $l_1, l_2, \dots, l_k$. We reach the maximum total damage if we can double all $k$ spells with maximum damage. It's possibly iff the set of $k$ largest by power sp... | [
"binary search",
"data structures",
"greedy",
"implementation",
"math",
"sortings"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = int(1e5) + 9;
int n;
set <int> sDouble;
long long sum[2];
set <int> s[2];
int cntDouble[2];
// 0: 0 -> 1
// 1: 1 -> 0
void upd(int id) {
assert(s[id].size() > 0);
int x = *s[id].rbegin();
if (id == 1) x = *s[id].begin();
bool d = sDouble.co... |
1398 | F | Controversial Rounds | Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won $x$ rounds in a row. For example, if Bob won five rounds in a row and $x = 2$, then two sets ends.
You know that Alice and... | Let's consider the following function $f(pos, x)$: minimum index $npos$ such that there is a substring of string $s_{pos}, s_{pos+1}, \dots, s_{npos-1}$ of length $x$ consisting of only characters $1$ and $?$ or $0$ and $?$. If this function has asymptotic $O(1)$ then we can solve problem for $O(n log n)$. Now, let's p... | [
"binary search",
"data structures",
"dp",
"greedy",
"two pointers"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int N = int(1e6) + 99;
const int INF = int(1e9) + 99;
int n;
string s;
vector <int> p[2][N];
int nxt[2][N];
int ptr[2];
char buf[N];
int main(){
cin >> n >> s;
for (int i = n - 1; i >= 0; --i) {
if (s[i] != '0') nxt[0][i] = 1 + nxt[0][i + 1];
... |
1398 | G | Running Competition | A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane:
- two horizontal segments: one connecting the points $(0, 0)$ and $(x, 0)$, the other connecting the points $(0, y)$ and $(x, y)$;
- $n + 1$ vertical segments, ... | First of all, let's find all possible lengths of the laps (after doing that, we can just check every divisor of $l_i$ to find the maximum possible length of a lap for a given query). A lap is always a rectangle - you can't construct a lap without using any vertical segments or using an odd number of vertical segments, ... | [
"bitmasks",
"fft",
"math",
"number theory"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < n; i++)
#define sz(a) ((int)(a).size())
const int LOGN = 20;
const int N = (1 << LOGN);
const int K = 200043;
const int M = 1000043;
typedef double ld;
typedef long long li;
const ld PI = acos(-1.0);
struct comp
{
ld x, y;
... |
1399 | A | Remove Smallest | You are given the array $a$ consisting of $n$ positive (greater than zero) integers.
In one move, you can choose two indices $i$ and $j$ ($i \ne j$) such that the absolute difference between $a_i$ and $a_j$ is no more than one ($|a_i - a_j| \le 1$) and remove the smallest of these two elements. If two elements are equ... | Firstly, let's sort the initial array. Then it's obvious that the best way to remove elements is from smallest to biggest. And if there is at least one $i$ such that $2 \le i \le n$ and $a_i - a_{i-1} > 1$ then the answer is "NO", because we have no way to remove $a_{i-1}$. Otherwise, the answer is "YES". | [
"greedy",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) cin >> it;
sort(a.begin(), a.end());
bool ok = true;
for (in... |
1399 | B | Gifts Fixing | You have $n$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $i$-th gift consists of $a_i$ candies and $b_i$ oranges.
During one move, you can choose some gift $1 \le i \le n$ and do one of the following operations:
-... | At first, consider the problems on candies and oranges independently. Then it's pretty obvious that for candies the optimal way is to decrease all $a_i$ to the value $min(a)$ (we need obtain at least this value to equalize all the elements and there is no point to decrease elements further). The same works for the arra... | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n), b(n);
for (auto &it : a) cin >> it;
for (auto &it : b) cin >> it;
int mna = *min_... |
1399 | C | Boats Competition | There are $n$ people who want to participate in a boat competition. The weight of the $i$-th participant is $w_i$. Only teams consisting of \textbf{two} people can participate in this competition. As an organizer, you think that it's fair to allow only teams with \textbf{the same total weight}.
So, if there are $k$ te... | This is just an implementation problem. Firstly, let's fix $s$ (it can be in range $[2; 2n]$), find the maximum number of boats we can obtain with this $s$ and choose the maximum among all found values. To find the number of pairs, let's iterate over the smallest weight in the team in range $[1; \lfloor\frac{s + 1}{2}\... | [
"brute force",
"greedy",
"two pointers"
] | 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 t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> cnt(n + 1);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
++cnt[x];
}
int ans... |
1399 | D | Binary String To Subsequences | You are given a binary string $s$ consisting of $n$ zeros and ones.
Your task is to divide the given string into the \textbf{minimum} number of \textbf{subsequences} in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the... | Let's iterate over all characters of $s$ from left to right, maintaining two arrays $pos_0$ and $pos_1$, where $pos_0$ stores indices of all subsequences which end with '0' and $pos_1$ stores indices of all subsequences which end with '1'. If we met '0', then the best choice is to append it to some existing subsequence... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
string s;
cin >> n >> s;
vector<int> ans(n);
vector<int> pos0, pos1;
for (int i = 0; i < n; ++i) {
int new... |
1399 | E1 | Weights Division (easy version) | \textbf{Easy and hard versions are actually different problems, so we advise you to read both statements carefully}.
You are given a weighted rooted tree, vertex $1$ is the root of this tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is th... | Let's define $cnt_i$ as the number of leaves in the subtree of the $i$-th edge (of course, in terms of vertices, in the subtree of the lower vertex of this edge). Values of $cnt$ can be calculated with pretty standard and simple dfs and dynamic programming. Then we can notice that our edges are independent and we can c... | [
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
vector<int> w, cnt;
vector<vector<pair<int, int>>> g;
long long getdiff(int i) {
return w[i] * 1ll * cnt[i] - (w[i] / 2) * 1ll * cnt[i];
}
void dfs(int v, int p = -1) {
if (g[v].size() == 1) cnt[p] = 1;
for (auto [to, id] : g[v]) {
if (id == p) continue;
dfs(to, ... |
1399 | E2 | Weights Division (hard version) | \textbf{Easy and hard versions are actually different problems, so we advise you to read both statements carefully}.
You are given a weighted rooted tree, vertex $1$ is the root of this tree. \textbf{Also, each edge has its own cost}.
A tree is a connected graph without cycles. A rooted tree has a special vertex call... | Read the easy version editorial first, because almost all solution is the solution to the easy version with little changes. Firstly, let's simulate the greedy process we used to solve the easy version problem, for edges with cost $1$ and edges with cost $2$, independently. But we don't stop when our sum reach something... | [
"binary search",
"dfs and similar",
"greedy",
"sortings",
"trees",
"two pointers"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n;
vector<int> w, c, cnt;
vector<vector<pair<int, int>>> g;
long long getdiff(int i) {
return w[i] * 1ll * cnt[i] - (w[i] / 2) * 1ll * cnt[i];
}
void dfs(int v, int p = -1) {
if (g[v].size() == 1) cnt[p] = 1;
for (auto [to, id] : g[v]) {
i... |
1399 | F | Yet Another Segments Subset | You are given $n$ segments on a coordinate axis $OX$. The $i$-th segment has borders $[l_i; r_i]$. All points $x$, for which $l_i \le x \le r_i$ holds, belong to the $i$-th segment.
Your task is to choose the \textbf{maximum} by size (the number of segments) subset of the given set of segments such that each pair of s... | Firstly, let's compress the given borders of segments (just renumerate them in such a way that the maximum value is the minimum possible and the relative order of integers doesn't change). Pretty standard approach. Now let's do recursive dynamic programming $dp_{l, r}$. This state stores the answer for the segment $[l;... | [
"data structures",
"dp",
"graphs",
"sortings"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> rg;
vector<vector<int>> dp;
int calc(int l, int r) {
if (dp[l][r] != -1) return dp[l][r];
dp[l][r] = 0;
if (l > r) return dp[l][r];
bool add = count(rg[l].begin(), rg[l].end(), r); // can't be greater than 1
dp[l][r] = max(dp[l][r], add + (l + 1 ... |
1400 | A | String Similarity | A binary string is a string where each character is either 0 or 1. Two binary strings $a$ and $b$ of equal length are similar, if they have the same character in some position (there exists an integer $i$ such that $a_i = b_i$). For example:
- 10010 and 01111 are similar (they have the same character in position $4$);... | There are many ways to solve this problem: let the answer be $s_1 s_3 s_5 \dots s_{2n-1}$, so it coincides with $s[1..n]$ in the first character, with $s[2..n+1]$ in the second character, and so on; copy the character $s_n$ $n$ times, since it appears in every substring we are interested in; find the character that occ... | [
"constructive algorithms",
"strings"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
val n = readLine()!!.toInt()
val c = readLine()!!.groupingBy { it }.eachCount().maxBy { it.value }!!.key
println(c.toString().repeat(n))
}
} |
1400 | B | RPG Protagonist | You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $p$ units and your follower — at most $f$ uni... | Let's say (without loss of generality) that $s \le w$ (a sword is lighter than a war axe). If not, then we can swap swords and axes. Now, let's iterate over the number of swords $s_1$ we will take ourselves. We can take at least $0$ and at most $\min(cnt_s, \frac{p}{s})$ swords. If we have taken $s_1$ swords, then we c... | [
"brute force",
"greedy",
"math"
] | 1,700 | fun main() {
repeat(readLine()!!.toInt()) {
val (p, f) = readLine()!!.split(' ').map { it.toInt() }
var (cntS, cntW) = readLine()!!.split(' ').map { it.toInt() }
var (s, w) = readLine()!!.split(' ').map { it.toInt() }
if (s > w) {
s = w.also { w = s }
... |
1400 | C | Binary String Reconstruction | Consider the following process. You have a binary string (a string where each character is either 0 or 1) $w$ of length $n$ and an integer $x$. You build a new binary string $s$ consisting of $n$ characters. The $i$-th character of $s$ is chosen as follows:
- if the character $w_{i-x}$ exists and is equal to 1, then $... | At first, let's replace all elements of string $w$ by 1. Now, let's consider all indices $i$ such that $s_i = 0$. If $s_i = 0$, then $w_{i - x}$ must be equal to 0 (if it exists) and $w_{i + x}$ must be equal to 0 (if it exists), so let's replace all such elements by 0. And after let's perform the process described in ... | [
"2-sat",
"brute force",
"constructive algorithms",
"greedy"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int t;
string s;
int x;
string f(string s) {
string res = s;
for (int i = 0; i < s.size(); ++i) {
if (i - x >= 0 && s[i - x] == '1' || i + x < s.size() && s[i + x] == '1')
res[i] = '1';
else
res[i] = '0';
}
return r... |
1400 | D | Zigzags | You are given an array $a_1, a_2 \dots a_n$. Calculate the number of tuples $(i, j, k, l)$ such that:
- $1 \le i < j < k < l \le n$;
- $a_i = a_k$ and $a_j = a_l$; | Let's iterate indices $j$ and $k$. For simplicity, for each $j$ we'll iterate $k$ in descending order. To calculate the number of tuples for a fixed $(j, k)$ we just need the number of $i < j$ such that $a_i = a_k$ and the number of $l > k$ with $a_l = a_j$. We can maintain both values in two frequency arrays $cntLeft$... | [
"brute force",
"combinatorics",
"data structures",
"math",
"two pointers"
] | 1,900 | fun main() {
repeat(readLine()!!.toInt()) {
val n = readLine()!!.toInt()
val a = readLine()!!.split(' ').map { it.toInt() - 1 }.toIntArray()
val cntLeft = IntArray(n) { 0 }
val cntRight = IntArray(n) { 0 }
var ans = 0L
for (j in a.indices) {
cntRight.fil... |
1400 | E | Clear the Multiset | You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.
You may apply two types of operations:
- choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., o... | Let's solve the problem by dynamic programing. Let $dp_{i, j}$ be the minimum number of operations to delete all elements from $1$ to $i$, if we have $j$ "unclosed" operations of the first type. In each transition, we either advance to the right (and possibly "close" some operations of the second type, so we go from $d... | [
"data structures",
"divide and conquer",
"dp",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = int(5e3) + 9;
int n;
int a[N];
int dp[N][N];
int calc (int pos, int x) {
int &res = dp[pos][x];
if (res != -1) return res;
if (pos == n) return res = 0;
res = 1 + calc(pos + 1, n);
res = min(res, calc(pos + 1, pos) + a[pos]);
i... |
1400 | F | x-prime Substrings | You are given an integer value $x$ and a string $s$ consisting of digits from $1$ to $9$ inclusive.
A substring of a string is a contiguous subsequence of that string.
Let $f(l, r)$ be the sum of digits of a substring $s[l..r]$.
Let's call substring $s[l_1..r_1]$ $x$-prime if
- $f(l_1, r_1) = x$;
- there are no val... | The number of $x$-prime strings is relatively small, so is their total length (you may bruteforce all of them and check that the total length of $x$-prime strings never exceeds $5000$, we will need that bruteforce in the solution). Now we have the following problem: given a set of strings with total length up to $5000$... | [
"brute force",
"dfs and similar",
"dp",
"string suffix structures",
"strings"
] | 2,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int AL = 9;
const int N = 5000;
const int INF = 1e9;
string s;
int x;
struct node{
int nxt[AL];
int p;
char pch;
int link;
int go[AL];
bool term;
node(){
memset(nxt, -1, sizeo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.