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 ⌀ |
|---|---|---|---|---|---|---|---|
2023 | B | Skipping | It is already the year $3024$, ideas for problems have long run out, and the olympiad now takes place in a modified individual format. The olympiad consists of $n$ problems, numbered from $1$ to $n$. The $i$-th problem has its own score $a_i$ and a certain parameter $b_i$ ($1 \le b_i \le n$).
Initially, the testing sy... | Notice that it makes no sense for us to skip problems for which $b_i \leq i$, since we can solve the problem, earn points for it, and the next problem will be chosen from the numbers $j < i$. If we skip it, we do not earn points, and the next problem will be chosen from the same set of problems or even a smaller one. W... | [
"binary search",
"dp",
"graphs",
"shortest paths"
] | 1,700 | null |
2023 | C | C+K+S | You are given two strongly connected$^{\dagger}$ directed graphs, each with exactly $n$ vertices, but possibly different numbers of edges. Upon closer inspection, you noticed an important feature — the length of any cycle in these graphs is divisible by $k$.
Each of the $2n$ vertices belongs to exactly one of two type... | Consider a strongly connected graph in which the lengths of all cycles are multiples of $k$. It can be observed that it is always possible to color this graph with $k$ colors in such a way that any edge connects a vertex of color $color$ to a vertex of color $(color + 1) \mod k$. It turns out that we can add edges to t... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"hashing",
"implementation",
"strings"
] | 2,400 | null |
2023 | D | Many Games | Recently, you received a rare ticket to the only casino in the world where you can actually earn something, and you want to take full advantage of this opportunity.
The conditions in this casino are as follows:
- There are a total of $n$ games in the casino.
- You can play each game \textbf{at most once}.
- Each game... | Claim 1: Suppose we took at least one item with $p_i < 100$. Then it is claimed that the sum $w_i$ over all taken elements is $\le 200\,000 \cdot \frac{100}{99} = C$. To prove this, let's assume the opposite and try to remove any element with $p_i < 100$ from the taken set, denoting $q_i = \frac{p_i}{100}$. The answer ... | [
"brute force",
"dp",
"greedy",
"math",
"probabilities"
] | 2,900 | null |
2023 | E | Tree of Life | In the heart of an ancient kingdom grows the legendary Tree of Life — the only one of its kind and the source of magical power for the entire world. The tree consists of $n$ nodes. Each node of this tree is a magical source, connected to other such sources through magical channels (edges). In total, there are $n-1$ cha... | This problem has several solutions that are similar to varying degrees. We will describe one of them. We will apply the following greedy approach. We will construct the answer by combining the answers for the subtrees. To do this, we will perform a depth-first traversal, and when exiting a vertex, we return a triplet $... | [
"dp",
"greedy",
"trees"
] | 3,300 | null |
2023 | F | Hills and Pits | In a desert city with a hilly landscape, the city hall decided to level the road surface by purchasing a dump truck. The road is divided into $n$ sections, numbered from $1$ to $n$ from left to right. The height of the surface in the $i$-th section is equal to $a_i$. If the height of the $i$-th section is greater than ... | To begin, let's solve the problem for a single query, where $l = 1$ and $r = n$. We will introduce an additional constraint - the dump truck must start on the first segment and finish on the last one. We will calculate the prefix sums of the array $a_1, a_2, \ldots, a_n$, denoted as $p_1, p_2, \ldots, p_n$. If $p_n < 0... | [
"data structures",
"greedy",
"math",
"matrices"
] | 3,500 | null |
2024 | A | Profitable Interest Rate | Alice has $a$ coins. She can open a bank deposit called "Profitable", but the minimum amount required to open this deposit is $b$ coins.
There is also a deposit called "Unprofitable", which can be opened with \textbf{any} amount of coins. Alice noticed that if she opens the "Unprofitable" deposit with $x$ coins, the m... | Let's say we have deposited $x$ coins into the "Unprofitable" deposit, then we can open a "Profitable" deposit if $a - x \geq b - 2x$ is satisfied. Which is equivalent to the inequality: $x \geq b - a$. Thus, we need to open an "Unprofitable" deposit for $\text{max}(0, b - a)$ coins, and open a "Profitable" deposit for... | [
"greedy",
"math"
] | 800 | null |
2024 | B | Buying Lemonade | There is a vending machine that sells lemonade. The machine has a total of $n$ slots. You know that initially, the $i$-th slot contains $a_i$ cans of lemonade. There are also $n$ buttons on the machine, each button corresponds to a slot, with exactly one button corresponding to each slot. Unfortunately, the labels on t... | Let's make a few simple observations about the optimal strategy of actions. First, if after pressing a certain button, no cans have been obtained, there is no point in pressing that button again. Second, among the buttons that have not yet resulted in a failure, it is always advantageous to press the button that has be... | [
"binary search",
"constructive algorithms",
"sortings"
] | 1,100 | null |
2025 | A | Two Screens | There are two screens which can display sequences of uppercase Latin letters. Initially, both screens display nothing.
In one second, you can do one of the following two actions:
- choose a screen and an uppercase Latin letter, and append that letter to \textbf{the end} of the sequence displayed on that screen;
- cho... | Whenever we perform the second action (copy from one screen to the other screen), we overwrite what was written on the other screen. It means that we can consider the string on the other screen to be empty before the copying, and that we only need to copy at most once. So, the optimal sequence of operations should look... | [
"binary search",
"greedy",
"strings",
"two pointers"
] | 800 | for _ in range(int(input())):
s = input()
t = input()
lcp = 0
n = len(s)
m = len(t)
for i in range(1, min(n, m) + 1):
if s[:i] == t[:i]:
lcp = i
print(n + m - max(lcp, 1) + 1) |
2025 | B | Binomial Coefficients, Kind Of | Recently, akshiM met a task that needed binomial coefficients to solve. He wrote a code he usually does that looked like this:
\begin{verbatim}
for (int n = 0; n < N; n++) { // loop over n from 0 to N-1 (inclusive)
C[n][0] = 1;
C[n][n] = 1;
for (int k = 1; k < n; k++) // loop over k from 1 to n-1 (inclusive)
C[n][k] =... | In order to solve the task, just try to generate values and find a pattern. The pattern is easy: $C[n][k] = 2^k$ for all $k \in [0, n)$. The last step is to calculate $C[n][k]$ fast enough. For example, we can precalculate all powers of two in some array $p$ as $p[k] = 2 \cdot p[k - 1] \bmod (10^9 + 7)$ for all $k < 10... | [
"combinatorics",
"dp",
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
const int MOD = int(1e9) + 7;
int main() {
int t; cin >> t;
vector<int> ks(t);
for (int _ = 0; _ < 2; _++)
for (int i = 0; i < t; i++)
cin >> ks[i];
vector<int> ans(1 + *max_element(ks.begin(), ks.end()), 1);
for (int i = 1; i < (int)ans.size(); i++)
ans[i] ... |
2025 | C | New Game | There's a new game Monocarp wants to play. The game uses a deck of $n$ cards, where the $i$-th card has exactly one integer $a_i$ written on it.
At the beginning of the game, on the first turn, Monocarp can take any card from the deck. During each subsequent turn, Monocarp can take exactly one card that has either the... | Let's fix the value of the first selected card $x$. Then it is optimal to take the cards as follows: take all cards with the number $x$, then all cards with the number $x + 1$, ..., all cards with the number $x + k - 1$. If any of the intermediate numbers are not present in the deck, we stop immediately. Let's sort the... | [
"binary search",
"brute force",
"greedy",
"implementation",
"sortings",
"two pointers"
] | 1,300 | for _ in range(int(input())):
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
ans = 0
j = 0
for i in range(n):
j = max(i, j)
while j + 1 < n and a[j + 1] - a[j] <= 1 and a[j + 1] - a[i] < k:
j += 1
ans = max(ans, j - i + 1)
print(ans) |
2025 | D | Attribute Checks | Imagine a game where you play as a character that has two attributes: "Strength" and "Intelligence", that are at zero level initially.
During the game, you'll acquire $m$ attribute points that allow you to increase your attribute levels — one point will increase one of the attributes by one level. But sometimes, you'l... | For the start, let's introduce a slow but correct solution. Let $d[i][I]$ be the answer to the task if we processed first $i$ records and the current Intelligence level is $I$. If we know Intelligence level $I$, then we also know the current Strength level $S = P - I$, where $P$ is just a total number of points in firs... | [
"brute force",
"data structures",
"dp",
"implementation",
"math",
"two pointers"
] | 1,800 | n, m = map(int, input().split())
rs = map(int, input().split())
d = [-int(1e9)] * (m + 1)
d[0] = 0
add = [0] * (m + 2)
def addSegment(l, r):
if l <= r:
add[l] += 1
add[r + 1] -= 1
def pushAll():
sum = 0
for i in range(m + 1):
sum += add[i]
d[i] += sum
for i in range(m +... |
2025 | E | Card Game | In the most popular card game in Berland, a deck of $n \times m$ cards is used. Each card has two parameters: suit and rank. Suits in the game are numbered from $1$ to $n$, and ranks are numbered from $1$ to $m$. There is exactly one card in the deck for each combination of suit and rank.
A card with suit $a$ and rank... | Suppose we're solving the problem for one suit. Consider a distribution of cards between two players; how to check if at least one matching between cards of the first player and cards of the second player exists? Let's order the cards from the highest rank to the lowest rank and go through them in that order. If we get... | [
"combinatorics",
"dp",
"fft",
"greedy",
"math"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y) {
x += y;
if (x >= MOD) x -= MOD;
return x;
}
int mul(int x, int y) {
return x * 1LL * y % MOD;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> ways(m + 1, vector<int>(m + 1));
ways[0][0]... |
2025 | F | Choose Your Queries | You are given an array $a$, consisting of $n$ integers (numbered from $1$ to $n$). Initially, they are all zeroes.
You have to process $q$ queries. The $i$-th query consists of two different integers $x_i$ and $y_i$. During the $i$-th query, you have to choose an integer $p$ (which is either $x_i$ or $y_i$) and an int... | We will use the classical method for solving maximization/minimization problems: we will come up with an estimate for the answer and try to achieve it constructively. The first idea. Since we have $n$ objects connected by binary relations, we can model the problem as a graph. Let the $n$ elements of the array be the ve... | [
"constructive algorithms",
"dfs and similar",
"dp",
"graphs",
"greedy",
"trees"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 300043;
string choice = "xy";
string sign = "+-";
int qs[N][2];
string ans[N];
int n, q;
vector<int> g[N];
int color[N];
void pair_queries(int q1, int q2)
{
if(q1 > q2) swap(q1, q2);
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
if(... |
2025 | G | Variable Damage | Monocarp is gathering an army to fight a dragon in a videogame.
The army consists of two parts: the heroes and the defensive artifacts. Each hero has one parameter — his health. Each defensive artifact also has one parameter — its durability.
Before the battle begins, Monocarp distributes artifacts to the heroes so t... | Let's start unraveling the solution from the end. Suppose we currently have $n$ heroes with health $a_1, a_2, \dots, a_n$ and $m$ artifacts with durability $b_1, b_2, \dots, b_m$. Let's assume we have already distributed the artifacts to the heroes, forming pairs $(a_i, b_i)$. If $m > n$, we will discard the excess art... | [
"data structures",
"flows"
] | 3,000 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct query{
int t, v;
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int m;
cin >> m;
vector<query> q(m);
forn(i, m) cin >> q[i].t >> q[i].v;
vector<pair<int, int>> xs;
forn(i, m) xs.push_bac... |
2026 | A | Perpendicular Segments | You are given a coordinate plane and three integers $X$, $Y$, and $K$. Find two line segments $AB$ and $CD$ such that
- the coordinates of points $A$, $B$, $C$, and $D$ are integers;
- $0 \le A_x, B_x, C_x, D_x \le X$ and $0 \le A_y, B_y, C_y, D_y \le Y$;
- the length of segment $AB$ is at least $K$;
- the length of s... | Let's look at all segments with a fixed angle between them and the X-axis. Let's take the shortest one with integer coordinates and length at least $K$ as $AB$. Let's say that a bounding box of $AB$ has width $w$ and height $h$. It's easy to see that a bounding box of segment $CD$ will have width at least $h$ and heigh... | [
"constructive algorithms",
"geometry",
"greedy",
"math"
] | 900 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while (t--) {
int X, Y, K;
cin >> X >> Y >> K;
int M = min(X, Y);
cout << "0 0 " << M << " " << M << endl;
cout << "0 " << M << " " << M << " 0" << endl;
}
} |
2026 | B | Black Cells | You are given a strip divided into cells, numbered from left to right from $0$ to $10^{18}$. Initially, all cells are white.
You can perform the following operation: choose two \textbf{white} cells $i$ and $j$, such that $i \ne j$ and $|i - j| \le k$, and paint them black.
A list $a$ is given. All cells from this lis... | First, let's consider the case when $n$ is even. It is not difficult to notice that to minimize the value of $k$, the cells have to be painted in the following pairs: $(a_1, a_2)$, $(a_3, a_4)$, ..., $(a_{n-1}, a_n)$. Then the answer is equal to the maximum of the distances between the cells in the pairs. For odd $n$, ... | [
"binary search",
"brute force",
"constructive algorithms",
"greedy"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<long long> a(n);
for (auto& x : a) cin >> x;
long long ans = 1e18;
auto upd = [&](vector<long long> a) {
sort(a.begin(), a.end());
for (int i = 1; i <... |
2026 | C | Action Figures | There is a shop that sells action figures near Monocarp's house. A new set of action figures will be released shortly; this set contains $n$ figures, the $i$-th figure costs $i$ coins and is available for purchase from day $i$ to day $n$.
For each of the $n$ days, Monocarp knows whether he can visit the shop.
Every t... | Consider the following solution: we iterate on the number of figures we get for free (let this number be $k$), and for each value of $k$, we try to check if it is possible to get $k$ figures for free, and if it is, find the best figures which we get for free. For a fixed value of $k$, it is optimal to visit the shop ex... | [
"binary search",
"brute force",
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
const int N = 400043;
char buf[N];
bool can(const string& s, int k)
{
int n = s.size();
vector<int> used(n);
for(int i = n - 1; i >= 0; i--)
if(k > 0 && s[i] == '1')
{
used[i] = 1;
k--;
}
int cur = 0;
... |
2026 | D | Sums of Segments | You are given a sequence of integers $[a_1, a_2, \dots, a_n]$. Let $s(l,r)$ be the sum of elements from $a_l$ to $a_r$ (i. e. $s(l,r) = \sum\limits_{i=l}^{r} a_i$).
Let's construct another sequence $b$ of size $\frac{n(n+1)}{2}$ as follows: $b = [s(1,1), s(1,2), \dots, s(1,n), s(2,2), s(2,3), \dots, s(2,n), s(3,3), \d... | In the editorial, we will treat all elements as $0$-indexed. The array $b$ consists of $n$ "blocks", the first block has the elements $[s(0,0), s(0,1), \dots, s(0,n-1)]$, the second block contains $[s(1,1), s(1,2), \dots, s(1,n-1)]$, and so on. Each position of element in $b$ can be converted into a pair of the form "i... | [
"binary search",
"data structures",
"dp",
"implementation",
"math"
] | 1,900 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int n;
vector<long long> a;
vector<long long> pa;
vector<long long> ppa;
vector<long long> start;
vector<long long> block;
vector<long long> pblock;
vector<long long> prefix_sums(vector<long long> v)
{
int k = v.size();
vector<long lo... |
2026 | E | Best Subsequence | Given an integer array $a$ of size $n$.
Let's define the value of the array as its size minus the number of set bits in the bitwise OR of all elements of the array.
For example, for the array $[1, 0, 1, 2]$, the bitwise OR is $3$ (which contains $2$ set bits), and the value of the array is $4-2=2$.
Your task is to c... | Let the number of chosen elements be $k$, and their bitwise OR be $x$. The answer is equal to $k - popcount(x)$, where $popcount(x)$ is the number of bits equal to $1$ in $x$. However, we can rewrite $popcount(x)$ as $60 - zeroes(x)$, where $zeroes(x)$ is equal to the number of bits equal to $0$ among the first $60$ bi... | [
"bitmasks",
"dfs and similar",
"flows",
"graph matchings",
"graphs"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
template<typename T = int>
struct Dinic {
struct edge {
int u, rev;
T cap, flow;
};
int n, s, t;
T flow;
vector<int> lst;
vector<int> d;
vector<vector<edge>> g;
Dinic() {}
Dinic(int n, int s, int t) : n(... |
2026 | F | Bermart Ice Cream | In the Bermart chain of stores, a variety of ice cream is sold. Each type of ice cream has two parameters: price and tastiness.
Initially, there is one store numbered $1$, which sells nothing. You have to process $q$ queries of the following types:
- $1~x$ — a new store opens, that sells the same types of ice cream a... | Let's try to solve the problem without queries of type $1$. This leads to a data structure where elements are added to the end and removed from the beginning. In other words, a queue. The query is a dynamic programming problem of the "knapsack" type. To implement a knapsack on a queue, we can use the technique of imple... | [
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"implementation",
"trees"
] | 2,700 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int P = 2000 + 5;
struct item{
int p, t;
};
struct minstack {
stack<item> st;
stack<array<int, P>> dp;
int get(int p) {return dp.empty() ? 0 : dp.top()[p];}
bool empty() {return st.empty();}
int size(... |
2027 | A | Rectangle Arrangement | You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.
You will use \textbf{each} stamp exactly \textbf{once} to color a rectangle of the same size as the stamp on the grid in black. You cannot r... | We must minimize the perimeter, and an obvious way to attempt this is to maximize the overlap. To achieve this, we can place each stamp such that the lower left corner of each stamp is at the same position, like shown in the sample explanation. Now, we can observe that the perimeter of this shape is determined solely b... | [
"geometry",
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int maxw = 0, maxh = 0;
for (int i=0; i<n; i++) {
int w, h;
cin >> w >> h;
maxw = max(maxw, w);... |
2027 | B | Stalin Sort | Stalin Sort is a humorous sorting algorithm designed to eliminate elements which are out of place instead of bothering to sort them properly, lending itself to an $\mathcal{O}(n)$ time complexity.
It goes as follows: starting from the second element in the array, if it is strictly smaller than the previous element (ig... | An array is vulnerable if and only if the first element is the largest. To prove the forward direction, we can trivially perform a single operation on the entire range, which will clearly make it non-increasing. Now, let's prove the reverse direction. Consider any array in which the maximum is not the first element. No... | [
"brute force",
"greedy"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> A(n);
for (int i=0; i<n; i++) cin >> A[i];
int best = 0;
for (int i=0; i<n; i++) {
int curr... |
2027 | C | Add Zeros | You're given an array $a$ initially containing $n$ integers. In one operation, you must do the following:
- Choose a position $i$ such that $1 < i \le |a|$ and $a_i = |a| + 1 - i$, where $|a|$ is the \textbf{current} size of the array.
- Append $i - 1$ zeros onto the end of $a$.
After performing this operation as man... | Let's rearrange the equation given in the statement to find a 'required' $|a|$ value in order to use an operation at that index. We have $a_i = |a| + 1 - i$, so $|a| = a_i + i - 1$. Note that if $a_i = 0$, then the condition is never true, since $i - 1 < |a|$ always. So actually, we just need to consider the first $n$ ... | [
"brute force",
"data structures",
"dfs and similar",
"dp",
"graphs",
"greedy"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<ll> A(n);
for (int i=0; i<n; i++) cin >> A[i];
map<ll,vector<ll>> adj;
for (int i=1; i<n; i++)... |
2027 | D1 | The Endspeaker (Easy Version) | \textbf{This is the easy version of this problem. The only difference is that you only need to output the minimum total cost of operations in this version. You must solve both versions to be able to hack.}
You're given an array $a$ of length $n$, and an array $b$ of length $m$ ($b_i > b_{i+1}$ for all $1 \le i < m$). ... | Let's use dynamic programming. We will have $\operatorname{dp}_{i,j}$ be the minimum cost to remove the prefix of length $i$, where the current value of $k$ is $j$. By a type $1$ operation, we can transition from $\operatorname{dp}_{i,j}$ to $\operatorname{dp}_{i,j+1}$ at no cost. Otherwise, by a type $2$ operation, we... | [
"binary search",
"dp",
"graphs",
"greedy",
"implementation",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int inf = 1 << 30;
void chmin(int &a, int b) {
a = min(a, b);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<int> A(n+1);
for (int i=0; i<n; i++) cin >> ... |
2027 | D2 | The Endspeaker (Hard Version) | \textbf{This is the hard version of this problem. The only difference is that you need to also output the number of optimal sequences in this version. You must solve both versions to be able to hack.}
You're given an array $a$ of length $n$, and an array $b$ of length $m$ ($b_i > b_{i+1}$ for all $1 \le i < m$). Initi... | Following on from the editorial for D1. Let's have the $\operatorname{dp}$ table store a pair of the minimum cost and the number of ways. Since we're now counting the ways, it's not enough just to consider the transition to $\operatorname{dp}_{r,j}$; we also need to transition to all $\operatorname{dp}_{x,j}$. Doing th... | [
"binary search",
"data structures",
"dp",
"greedy",
"implementation",
"two pointers"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define int long long
int modN = 1e9 + 7;
int mod(int n) {
return (n + modN) % modN;
}
struct SegmentTree {
struct Node {
int val = 1e18;
int cnt = 1;
};
vector<Node> st;
int n;
SegmentTree(int n): n(n) {
st.resize(4 * ... |
2027 | E1 | Bit Game (Easy Version) | \textbf{This is the easy version of this problem. The only difference is that you need to output the winner of the game in this version, and the number of stones in each pile are fixed. You must solve both versions to be able to hack.}
Alice and Bob are playing a familiar game where they take turns removing stones fro... | Each pile is an independent game, so let's try to find the nimber of a pile with value $a$ and size $x$ - let's denote this by $f(x, a)$. Suppose $x = 2^k - 1$ for some integer $k$; in this case, the nimber is entirely dependent on $a$. If $x$ is not in that form, consider the binary representation of $a$. If any bit i... | [
"bitmasks",
"brute force",
"games",
"math"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
int nimber(int x, int a) {
int aprime = 0;
bool goodbit = false;
for (int bit=30; bit>=0; bit--) {
if (x & (1 << bit)) {
aprime *= 2;
if (goodbit || (a & (1 << bit))) {
aprime += 1;
}
} else if (a & (1 << bit)) {
goodbit = t... |
2027 | E2 | Bit Game (Hard Version) | \textbf{This is the hard version of this problem. The only difference is that you need to output the number of choices of games where Bob wins in this version, where the number of stones in each pile are not fixed. You must solve both versions to be able to hack.}
Alice and Bob are playing a familiar game where they t... | Let's continue on from the editorial for E1. We figured out that the nimbers lie in one of these four cases: $g(2^k - 2) = 0$, for all $k \ge 1$. $g(2^k - 1) = k$, for all $k \ge 0$. $g(2^k) = k + (-1)^k$, for all $k \ge 0$. $g(2^k+1) = g(2^k+2) = \ldots = g(2^{k+1} - 3) = k + 1$, for all $k \ge 2$. From these, it's cl... | [
"bitmasks",
"dp",
"math"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
int dp[32][32][6][2][2];
const int mod = 1000000007;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> A(n);
for (int i=0; i<n; i++) cin >> A[i];
vector<int> B(n);
for (int... |
2028 | A | Alice's Adventures in ''Chess'' | Alice is trying to meet up with the Red Queen in the countryside! Right now, Alice is at position $(0, 0)$, and the Red Queen is at position $(a, b)$. Alice can only move in the four cardinal directions (north, east, south, west).
More formally, if Alice is at the point $(x, y)$, she will do one of the following:
- g... | We can run the whole pattern $100\gg \max(a, b, n)$ times, which gives a total runtime of $O(100tn)$ (be careful in that running the pattern only 10 times is not enough!) To prove that $100$ repeats suffices, suppose that Alice's steps on the first run of the pattern are $(0, 0), (x_1, y_1), (x_2, y_2), \ldots, (x_n, y... | [
"brute force",
"implementation",
"math"
] | 900 | def solve():
[n, a, b] = list(map(int, input().split()))
s = str(input())
x, y = 0, 0
for __ in range(100):
for c in s:
if c == 'N':
y += 1
elif c == 'E':
x += 1
elif c == 'S':
y -= 1
else:
... |
2028 | B | Alice's Adventures in Permuting | Alice mixed up the words transmutation and permutation! She has an array $a$ specified via three integers $n$, $b$, $c$: the array $a$ has length $n$ and is given via $a_i = b\cdot (i - 1) + c$ for $1\le i\le n$. For example, if $n=3$, $b=2$, and $c=1$, then $a=[2 \cdot 0 + 1, 2 \cdot 1 + 1, 2 \cdot 2 + 1] = [1, 3, 5]$... | Suppose that $b = 0$. Then, if $c \ge n$, the answer is $n$; if $c = n - 1$ or $c = n - 2$, the answer is $n - 1$; and otherwise, it is $-1$ (for example, consider $c = n - 3$, in which case we will end up with $a = [0, 1, \ldots, n - 4, n - 3, n - 3, n - 3] \rightarrow [0, 1, \ldots, n - 4, n - 3, n - 3, n - 2] \right... | [
"binary search",
"implementation",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define smx(a, b) a = max(a, b)
#define smn(a, b) a = mi... |
2028 | C | Alice's Adventures in Cutting Cake | Alice is at the Mad Hatter's tea party! There is a long sheet cake made up of $n$ sections with tastiness values $a_1, a_2, \ldots, a_n$. There are $m$ creatures at the tea party, excluding Alice.
Alice will cut the cake into $m + 1$ pieces. Formally, she will partition the cake into $m + 1$ subarrays, where each suba... | Alice's piece of cake will be some subsegment $a[i:j]$. For a fixed $i$, how large can $j$ be? To determine this, let $pfx[i]$ be the maximum number of creatures that can be fed on $a[:i]$ and $sfx[j]$ the maximum number of creatures on $a[j:]$. Then, for a given $i$, the maximum possible $j$ is exactly the largest $j$... | [
"binary search",
"dp",
"greedy",
"two pointers"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define smx(a, b) a = max(a, b)
#define smn(a, b) a = mi... |
2028 | D | Alice's Adventures in Cards | Alice is playing cards with the Queen of Hearts, King of Hearts, and Jack of Hearts. There are $n$ different types of cards in their card game. Alice currently has a card of type $1$ and needs a card of type $n$ to escape Wonderland. The other players have one of each kind of card.
In this card game, Alice can trade c... | We will use DP to answer the following question for each $a$ from $n$ down to $1$: is it possible to trade up from card $a$ to card $n$? To answer this question efficiently, we need to determine for each of the three players whether there exists some $b > a$ such that $p(b) < p(a)$ and it is possible to trade up from c... | [
"constructive algorithms",
"data structures",
"dp",
"graphs",
"greedy",
"implementation",
"ternary search"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define smx(a, b) a = max(a, b)
#define smn(a, b) a = mi... |
2028 | E | Alice's Adventures in the Rabbit Hole | Alice is at the bottom of the rabbit hole! The rabbit hole can be modeled as a tree$^{\text{∗}}$ which has an exit at vertex $1$, and Alice starts at some vertex $v$. She wants to get out of the hole, but unfortunately, the Queen of Hearts has ordered her execution.
Each minute, a fair coin is flipped. If it lands hea... | Note that Alice should always aim to move to the root, as this maximizes her probability of escaping (i.e., for any path from leaf to root, Alice's probability of escaping increases moving up the path). Furthermore, the Queen should always move downward for the same reason as above. Furthermore, the Queen should always... | [
"combinatorics",
"dfs and similar",
"dp",
"games",
"greedy",
"math",
"probabilities",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define smx(a, b) a = max(a, b)
#define smn(a, b) a = mi... |
2028 | F | Alice's Adventures in Addition | \textbf{Note that the memory limit is unusual.}
The Cheshire Cat has a riddle for Alice: given $n$ integers $a_1, a_2, \ldots, a_n$ and a target $m$, is there a way to insert $+$ and $\times$ into the circles of the expression $$a_1 \circ a_2 \circ \cdots \circ a_n = m$$ to make it true? We follow the usual order of o... | Let $dp[i][j]$ be whether $a_1\circ a_2\circ \ldots \circ a_i = j$ can be satisfied. Then, let's case on $a_i$. If $a_i = 0$, then $dp[i][j] = dp[i - 1][j] \lor dp[i - 2][j]\lor \cdots \lor dp[0][j]$ (where we will take $dp[0][j]= \boldsymbol{1}[j = 0]$, the indicator that $j = 0$). This is because we can multiply toge... | [
"bitmasks",
"brute force",
"dp",
"implementation"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define smx(a, b) a = max(a, b)
#define smn(a, b) a = min... |
2029 | A | Set | You are given a positive integer $k$ and a set $S$ of all integers from $l$ to $r$ (inclusive).
You can perform the following two-step operation any number of times (possibly zero):
- First, choose a number $x$ from the set $S$, such that there are at least $k$ multiples of $x$ in $S$ (including $x$ itself);
- Then, ... | Greedy from small to large. We can delete the numbers from small to large. Thus, previously removed numbers will not affect future choices (if $x<y$, then $x$ cannot be a multiple of $y$). So an integer $x$ ($l\le x\le r$) can be removed if and only if $k\cdot x\le r$, that is, $x\le \left\lfloor\frac{r}{k}\right\rfloo... | [
"greedy",
"math"
] | 800 | for _ in range(int(input())):
l, r, k = map(int, input().split())
print(max(r // k - l + 1, 0)) |
2029 | B | Replacement | You have a binary string$^{\text{∗}}$ $s$ of length $n$, and Iris gives you another binary string $r$ of length $n-1$.
Iris is going to play a game with you. During the game, you will perform $n-1$ operations on $s$. In the $i$-th operation ($1 \le i \le n-1$):
- First, you choose an index $k$ such that $1\le k\le |s... | ($\texttt{01}$ or $\texttt{10}$ exists) $\Longleftrightarrow$ (both $\texttt{0}$ and $\texttt{1}$ exist). Each time we do an operation, if $s$ consists only of $\texttt{0}$ or $\texttt{1}$, we surely cannot find any valid indices. Otherwise, we can always perform the operation successfully. In the $i$-th operation, if ... | [
"constructive algorithms",
"games",
"strings"
] | 1,100 | for _ in range(int(input())):
n = int(input())
s = input()
one = s.count("1")
zero = s.count("0")
ans = "YES"
for ti in input():
if one == 0 or zero == 0:
ans = "NO"
break
one -= 1
zero -= 1
if ti == "1":
one += 1
else:
... |
2029 | C | New Rating | \begin{quote}
{{Hello, \sout{Codeforces} Forcescode!}}
\end{quote}
Kevin used to be a participant of Codeforces. Recently, the KDOI Team has developed a new Online Judge called Forcescode.
Kevin has participated in $n$ contests on Forcescode. In the $i$-th contest, his performance rating is $a_i$.
Now he has hacked ... | Binary search. Do something backward. First, do binary search on the answer. Suppose we're checking whether the answer can be $\ge k$ now. Let $f_i$ be the current rating after participating in the $1$-st to the $i$-th contest (without skipping). Let $g_i$ be the minimum rating before the $i$-th contest to make sure th... | [
"binary search",
"data structures",
"dp",
"greedy"
] | 1,700 | for _ in range(int(input())):
n = int(input())
def f(a, x):
return a + (a < x) - (a > x)
dp = [0, -n, -n]
for x in map(int, input().split()):
dp[2] = max(f(dp[1], x), f(dp[2], x))
dp[1] = max(dp[1], dp[0])
dp[0] = f(dp[0], x)
print(max(dp[1], dp[2])) |
2029 | D | Cool Graph | You are given an undirected graph with $n$ vertices and $m$ edges.
You can perform the following operation at most $2\cdot \max(n,m)$ times:
- Choose three distinct vertices $a$, $b$, and $c$, then for each of the edges $(a,b)$, $(b,c)$, and $(c,a)$, do the following:
- If the edge does not exist, add it. On the con... | There are many different approaches to this problem. Only the easiest one (at least I think so) is shared here. Try to make the graph into a forest first. ($deg_i\le 1$ for every $i$) $\Longrightarrow$ (The graph is a forest). Let $d_i$ be the degree of vertex $i$. First, we keep doing the following until it is impossi... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"trees"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include "debug.hpp"
#else
#define debug(...) (void)0
#endif
using i64 = int64_t;
constexpr bool test = false;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
for (int ti = 0; ti < t; ti += 1) {
int n, m;
cin >> n >> m;... |
2029 | E | Common Generator | For two integers $x$ and $y$ ($x,y\ge 2$), we will say that $x$ is a generator of $y$ if and only if $x$ can be transformed to $y$ by performing the following operation some number of times (possibly zero):
- Choose a divisor $d$ ($d\ge 2$) of $x$, then increase $x$ by $d$.
For example,
- $3$ is a generator of $8$ s... | $2$ is powerful. Consider primes. How did you prove that $2$ can generate every integer except odd primes? Can you generalize it? In this problem, we do not take the integer $1$ into consideration. Claim 1. $2$ can generate every integer except odd primes. Proof. For a certain non-prime $x$, let $\operatorname{mind}(x)... | [
"brute force",
"constructive algorithms",
"math",
"number theory"
] | 2,100 | #include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 4e5 + 5;
int vis[_N], pr[_N], cnt = 0;
void init(int n) {
vis[1] = 1;
for (int i = 2; i <= n; i++) {
if (!vis[i]) {
pr[++cnt] = i;
}
for (int j = 1; j <= cnt... |
2029 | F | Palindrome Everywhere | You are given a cycle with $n$ vertices numbered from $0$ to $n-1$. For each $0\le i\le n-1$, there is an undirected edge between vertex $i$ and vertex $((i+1)\bmod n)$ with the color $c_i$ ($c_i=R$ or $B$).
Determine whether the following condition holds for every pair of vertices $(i,j)$ ($0\le i<j\le n-1$):
- Ther... | If there are both consecutive $\texttt{R}$-s and $\texttt{B}$-s, does the condition hold for all $(i,j)$? Why? Suppose that there are only consecutive $\texttt{R}$-s, check the parity of the number of $\texttt{R}$-s in each consecutive segment of $\texttt{R}$-s. If for each consecutive segment of $\texttt{R}$-s, the pa... | [
"constructive algorithms",
"graphs",
"greedy"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n; cin>>n;
string s; cin>>s;
int visr=0,visb=0,ok=0;
for(int i=0;i<n;i++){
if(s[i]==s[(i+1)%n]){
if(s[i]=='R') visr=1;
else visb=1;
ok++;
}
}
if(visr&visb){
cout<<"NO\n";
return ;
}
if(ok==n){
cout<<"YES\n";
return ;
}
if(vi... |
2029 | G | Balanced Problem | There is an array $a$ consisting of $n$ integers. Initially, all elements of $a$ are equal to $0$.
Kevin can perform several operations on the array. Each operation is one of the following two types:
- Prefix addition — Kevin first selects an index $x$ ($1\le x\le n$), and then for each $1\le j\le x$, increases $a_j$... | This problem has two approaches. The first one is the authors' solution, and the second one was found during testing. The array $a$ is constructed with the operations. How can we use this property? If we want to make all $a_i=x$, what is the minimum value of $x$? Use the property mentioned in Hint 1. (For the subproble... | [
"data structures",
"dp"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define pii pair<int, int>
#define all(a) a.begin(), a.end()
const int mod = 1e9 + 7, N = 5005;
void solve() {
int n, m, V;
cin >> n >> m >> V;
vector <int> c(n);
for (int i = 0; i < n; ++i) {
cin >> c[i];
... |
2029 | H | Message Spread | Given is an undirected graph with $n$ vertices and $m$ edges. Each edge connects two vertices $(u, v)$ and has a probability of $\frac{p}{q}$ of appearing each day.
Initially, vertex $1$ has a message. At the end of the day, a vertex has a message if and only if itself or at least one of the vertices adjacent to it ha... | It's hard to calculate the expected number. Try to change it to the probability. Consider a $\mathcal{O}(3^n)$ dp first. Use inclusion and exclusion. Write out the transformation. Try to optimize it. Let $dp_S$ be the probability such that exactly the points in $S$ have the message. The answer is $\sum dp_S\cdot tr_S$,... | [
"bitmasks",
"brute force",
"combinatorics",
"dp"
] | 3,500 | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=(1<<21),mod=998244353;
const int Lim=8e18;
inline void add(signed &i,int j){
i+=j;
if(i>=mod) i-=mod;
}
int qp(int a,int b){
int ans=1;
while(b){
if(b&1) (ans*=a)%=mod;
(a*=a)%=mod;
b>>=1;
}
return ans;
}
int dp[N],f[N],g[N],h[... |
2029 | I | Variance Challenge | Kevin has recently learned the definition of variance. For an array $a$ of length $n$, the variance of $a$ is defined as follows:
- Let $x=\dfrac{1}{n}\displaystyle\sum_{i=1}^n a_i$, i.e., $x$ is the mean of the array $a$;
- Then, the variance of $a$ is $$ V(a)=\frac{1}{n}\sum_{i=1}^n(a_i-x)^2. $$
Now, Kevin gives yo... | The intended solution has nothing to do with dynamic programming. This is the key observation of the problem. Suppose we have an array $b$ and a function $f(x)=\sum (b_i-x)^2$, then the minimum value of $f(x)$ is the variance of $b$. Using the observation mentioned in Hint 2, we can reduce the problem to minimizing $\s... | [
"flows",
"graphs",
"greedy"
] | 3,400 | #include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
ll n, m, k; cin >> n >> m >> k;
vector<ll> a(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
vector<ll> kans(m + 1, LLONG_MAX);
ve... |
2030 | A | A Gift From Orangutan | While exploring the jungle, you have bumped into a rare orangutan with a bow tie! You shake hands with the orangutan and offer him some food and water. In return...
The orangutan has gifted you an array $a$ of length $n$. Using $a$, you will construct two arrays $b$ and $c$, both containing $n$ elements, in the follow... | First, what is the maximum possible value of $c_i-b_j$ for any $i,j$? Since $c_i$ is the maximum element of some subset of $a$ and $b_i$ is the minimum element of some subset of $a$, the maximum possible value of $c_i-b_j$ is $max(a)-min(a)$. Also note that $c_1=b_1$ for any reordering of $a$. By reordering such that t... | [
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 800 | for i in range(int(input())):
n = int(input())
mx = 0
mn= 1000000
lst = input().split()
for j in range(n):
x = int(lst[j])
mx = max(mx, x)
mn = min(mn, x)
print((mx-mn)*(n-1)) |
2030 | B | Minimise Oneness | For an arbitrary binary string $t$$^{\text{∗}}$, let $f(t)$ be the number of non-empty subsequences$^{\text{†}}$ of $t$ that contain only $\mathtt{0}$, and let $g(t)$ be the number of non-empty subsequences of $t$ that contain at least one $\mathtt{1}$.
Note that for $f(t)$ and for $g(t)$, each subsequence is counted ... | Observation: $f(t)-g(t)$ is odd. Proof: $f(t)+g(t)$ is the set of all non-empty subsets of $t$, which is $2^{|t|}-1$, which is odd. The sum and difference of two integers has the same parity, so $f(t)-g(t)$ is always odd. By including exactly one $1$ in the string $s$, we can make $f(s)=2^{n-1}-1$ and $g(s)=2^{n-1}$, o... | [
"combinatorics",
"constructive algorithms",
"games",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
cout << '1';
for(int i = 1; i < n; i++) cout << '0';
cout << endl;
}
} |
2030 | C | A TRUE Battle | Alice and Bob are playing a game. There is a list of $n$ booleans, each of which is either true or false, given as a binary string $^{\text{∗}}$ of length $n$ (where $1$ represents true, and $0$ represents false). Initially, there are no operators between the booleans.
Alice and Bob will take alternate turns placing a... | Let's understand what Alice wants to do. She wants to separate a statement that evaluates to true between two or's. This guarantees her victory since or is evaluated after all and's. First, if the first or last boolean is true, then Alice instantly wins by placing or between the first and second, or second to last and ... | [
"brute force",
"games",
"greedy"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
string s;
cin >> s;
vector<int> v(n);
for(int i = 0; i < n; i++) {
if(s[i]=='1') v[i]=1;
}
bool win = false;
if(v[0]|... |
2030 | D | QED's Favorite Permutation | QED is given a permutation$^{\text{∗}}$ $p$ of length $n$. He also has a string $s$ of length $n$ containing only characters $L$ and $R$. QED only likes permutations that are sorted in non-decreasing order. To sort $p$, he can select any of the following operations and perform them any number of times:
- Choose an ind... | Observation: Through a series of swaps, we can swap an element from position $i$ to position $j$ (WLOG, assume $i < j$) if there is no such $k$ such that $i \leq k < j$ such that $s_k = \texttt{L}$ and $s_{k+1} = \texttt{R}$. Let's mark all indices $i$ such that $s_i = \texttt{L}$ and $s_{i+1} = \texttt{R}$ as bad. If ... | [
"data structures",
"implementation",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n,q;
cin >> n >> q;
vector<int> perm(n);
for(int i = 0; i < n; i++) cin >> perm[i];
for(int i = 0; i < n; i++) perm[i]--;
vector<int> invperm(n);
for(int i =... |
2030 | E | MEXimize the Score | Suppose we partition the elements of an array $b$ into any number $k$ of non-empty multisets $S_1, S_2, \ldots, S_k$, where $k$ is an arbitrary positive integer. Define the score of $b$ as the maximum value of $\operatorname{MEX}(S_1)$$^{\text{∗}}$$ + \operatorname{MEX}(S_2) + \ldots + \operatorname{MEX}(S_k)$ over all... | Observation: The score of $b$ is equivalent to $f_0$ + $\min(f_0, f_1)$ + $\ldots$ + $\min(f_0, \ldots, f_{n-1})$ where $f_i$ stores the frequency of integer $i$ in $b$. Intuition: We can greedily construct the $k$ arrays by repeating this step: Select the minimum $j$ such that $f_j = 0$ and $\min(f_0, \ldots f_{j-1}) ... | [
"combinatorics",
"data structures",
"dp",
"greedy",
"implementation",
"math"
] | 2,200 | #include <bits/stdc++.h>
#define int long long
#define ll long long
#define pii pair<int,int>
#define piii pair<pii,pii>
#define fi first
#define se second
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
using namespace std;
const int MX = 2e5;
ll fact[MX+1];
ll ifact[MX+1];
... |
2030 | F | Orangutan Approved Subarrays | Suppose you have an array $b$. Initially, you also have a set $S$ that contains all distinct elements of $b$. The array $b$ is called orangutan-approved if it can be \textbf{emptied} by repeatedly performing the following operation:
- In one operation, select indices $l$ and $r$ ($1 \leq l \leq r \leq |b|$) such that ... | First, let's try to find whether a single array is orangutan-approved or not. Claim: The array $b$ of size $n$ is not orangutan-approved if and only if there exists indices $1\leq w < x < y < z \leq n$ such that $b_w=b_y$, $b_x=b_z$, and $b_w\neq b_x$. Proof: Let's prove this with strong induction. For $n=0$, the claim... | [
"binary search",
"data structures",
"dp",
"greedy",
"implementation",
"two pointers"
] | 2,400 | #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define nline "\n"
#define f first
#define s second
#define sz(x) x.size()
#define all(x) x.begin(),x.end()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const ll INF_ADD=1e18;
const ll MOD=1e9+7;
... |
2030 | G2 | The Destruction of the Universe (Hard Version) | \textbf{This is the hard version of the problem. In this version, $n \leq 10^6$. You can only make hacks if both versions of the problem are solved.}
Orangutans are powerful beings—so powerful that they only need $1$ unit of time to destroy every vulnerable planet in the universe!
There are $n$ planets in the univers... | To find the score of a set of intervals $([l_1, r_1], [l_2, r_2], \ldots, [l_v, r_v])$, we follow these steps: Initially, the score is set to $0$. We perform the following process repeatedly: Let $x$ be the interval with the smallest $r_i$ among all active intervals. Let $y$ be the interval with the largest $l_i$ among... | [
"combinatorics",
"math"
] | 3,100 |
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll long long
#define ld long double
#define nline "\n"
#define f first
#define s second
#define sz(x) (ll)x.size()
#defin... |
2031 | A | Penchick and Modern Monument | Amidst skyscrapers in the bustling metropolis of Metro Manila, the newest Noiph mall in the Philippines has just been completed! The construction manager, Penchick, ordered a state-of-the-art monument to be built with $n$ pillars.
The heights of the monument's pillars can be represented as an array $h$ of $n$ positive... | Consider the maximum number of pillars that can be left untouched instead. Under what conditions can $k>1$ pillars be untouched? Note that if pillars $i$ and $j$ with different heights are both untouched, then the first pillar must be taller than the second, which contradicts the fact that the heights must be non-decre... | [
"constructive algorithms",
"dp",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
vector<int> arr(n);
for(auto &x : arr) cin >> x;
int ans = 0, cnt = 1;
for(int i = 1; i < n; i++){
if(arr[i] == arr[i - 1]) cnt++;
else{
ans = max(ans, cnt);
cnt = 1... |
2031 | B | Penchick and Satay Sticks | Penchick and his friend Kohane are touring Indonesia, and their next stop is in Surabaya!
In the bustling food stalls of Surabaya, Kohane bought $n$ satay sticks and arranged them in a line, with the $i$-th satay stick having length $p_i$. It is given that $p$ is a permutation$^{\text{∗}}$ of length $n$.
Penchick wan... | Consider which permutations you can get by reversing the operations and starting from the identity permutation After $p_i$ and $p_{i+1}$ have been swapped, i.e. $p_i=i+1$ and $p_{i+1}=i$, neither of them can then be involved in another different swap. Suppose we begin with the identity permutation. Consider what happen... | [
"brute force",
"greedy",
"sortings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
vector<int> arr(n);
for(auto &x : arr) cin >> x;
for(int i = 0; i < n - 1; i++){
if(arr[i] != i + 1){
if(arr[i + 1] == i + 1 && arr[i] == i + 2) swap(arr[i], arr[i + 1]);
else{
... |
2031 | C | Penchick and BBQ Buns | Penchick loves two things: square numbers and Hong Kong-style BBQ buns! For his birthday, Kohane wants to combine them with a gift: $n$ BBQ buns arranged from left to right. There are $10^6$ available fillings of BBQ buns, numbered from $1$ to $10^6$. To ensure that Penchick would love this gift, Kohane has a few goals... | Solve the problem for $n=2$ and for even $n$ in general. For odd $n$, there exists a color that appears at least thrice. What does this mean? Note that $1$ is a square number; thus, for even $n$, the construction $1~1~2~2~3~3\ldots\frac{n}{2}~\frac{n}{2}$ works. For odd $n$, note that there exists a color that appears ... | [
"constructive algorithms",
"math",
"number theory"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;cin>>t;
while (t--) {
int n;cin>>n;
if (n%2) {
if (n<27) cout<<-1<<endl;
else {
cout<<"1 3 3 4 4 5 5 6 6 1 2 7 7 8 8 9 9 10 10 11 11 12 12 13 13 1 2 ";
for (int i=14;i<=n/2;i+... |
2031 | D | Penchick and Desert Rabbit | Dedicated to pushing himself to his limits, Penchick challenged himself to survive the midday sun in the Arabian Desert!
While trekking along a linear oasis, Penchick spots a desert rabbit preparing to jump along a line of palm trees. There are $n$ trees, each with a height denoted by $a_i$.
The rabbit can jump from ... | Suppose that you have found the maximum height reachable from tree $i+1$. How do you find the maximum height reachable from tree $i$? Let $p$ be the highest height among trees indexed from $1$ to $i$, and $s$ be the lowest height among trees indexed from $i+1$ to $n$. When can tree $i$ be reachable from tree $i+1$? Fir... | [
"binary search",
"data structures",
"dfs and similar",
"dp",
"dsu",
"greedy",
"implementation",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t; cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> ar(n), pref(n), suff(n), ans(n);
for (int i = 0; i < n; i++) cin >> ar[i];
// prefix maximum
pref[0]... |
2031 | E | Penchick and Chloe's Trees | With just a few hours left until Penchick and Chloe leave for Singapore, they could hardly wait to see the towering trees at the Singapore Botanic Gardens! Attempting to contain their excitement, Penchick crafted a rooted tree to keep Chloe and himself busy.
Penchick has a rooted tree$^{\text{∗}}$ consisting of $n$ ve... | Consider the tree where root $1$ has $k$ children which are all leaves. What is its minimum depth? Consider undoing the operations from the given tree back to the perfect binary tree. Where can each child of the tree go? As in Hint 2, suppose that there exists a finite sequence of operations that convert a perfect bina... | [
"data structures",
"dfs and similar",
"dp",
"greedy",
"implementation",
"math",
"sortings",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1'000'000;
void dfs(int u, int p, vector<vector<int>>& adj, vector<int>& depth) {
priority_queue<int,vector<int>,greater<int>> pq;
for (int v : adj[u]) {
if (v != p) {
dfs(v, u, adj, depth);
pq.push(depth[v]);
... |
2031 | F | Penchick and Even Medians | This is an interactive problem.
Returning from a restful vacation on Australia's Gold Coast, Penchick forgot to bring home gifts for his pet duck Duong Canh! But perhaps a beautiful problem crafted through deep thought on the scenic beaches could be the perfect souvenir.
There is a hidden permutation$^{\text{∗}}$ $p$... | Querying $n - 2$ elements is very powerful. Try to find two indices $x$ and $y$ such that one of $p_x, p_y$ is strictly smaller than $\frac{n}{2}$ and the other is strictly greater than $\frac{n}{2} + 1$. What can you do after finding these two elements? This solution is non-deterministic and uses $\frac{n}{2} + O(1)$ ... | [
"binary search",
"constructive algorithms",
"interactive",
"probabilities"
] | 2,800 | #include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <utility>
#include <cstring>
using namespace std;
#define ll long long
#define MOD // Insert modulo here
#define mul(a, b) (((ll)(a) * (ll)(b)) % MOD)
#ifndef ONLINE_JUDGE
#define ... |
2032 | A | Circuit | Alice has just crafted a circuit with $n$ lights and $2n$ switches. Each component (a light or a switch) has two states: on or off. The lights and switches are arranged in a way that:
- Each light is connected to \textbf{exactly two} switches.
- Each switch is connected to \textbf{exactly one} light. It's \textbf{unkn... | Observe that an even number of switch toggles on the same light will not change that light's status. In other words, a light is on if and only if exactly one of the two switches connecting to it is on. Let's denote $\text{cnt}_0$ and $\text{cnt}_1$ as the number of off switches and on switches in the circuit. We see th... | [
"greedy",
"implementation",
"math",
"number theory"
] | 800 | class Solution:
hasMultipleTests = True
n: int = None
a: list = None
@classmethod
def preprocess(cls):
pass
@classmethod
def input(cls, testcase):
cls.n = int(input())
cls.a = list(map(int, input().split()))
@classmethod
def solve(cls, testcase):
c... |
2032 | B | Medians | You are given an array $a = [1, 2, \ldots, n]$, where $n$ is \textbf{odd}, and an integer $k$.
Your task is to choose an \textbf{odd} positive integer $m$ and to split $a$ into $m$ subarrays$^{\dagger}$ $b_1, b_2, \ldots, b_m$ such that:
- Each element of the array $a$ belongs to exactly one subarray.
- For all $1 \l... | For $n = 1$ (and $k = 1$ as well), the obvious answer would be not partitioning anything, i.e., partition with 1 subarray being itself. For $n > 1$, we see that $k = 1$ and $k = n$ cannot yield a satisfactory construction. Proof is as follows: $m = 1$ will yield $ans = \lfloor \frac{n+1}{2} \rfloor$, which will never b... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,100 | class Solution:
hasMultipleTests = True
n: int = None
k: int = None
@classmethod
def preprocess(cls):
pass
@classmethod
def input(cls, testcase):
cls.n, cls.k = map(int, input().split())
@classmethod
def solve(cls, testcase):
if cls.n == 1: return(print('1... |
2032 | C | Trinity | You are given an array $a$ of $n$ elements $a_1, a_2, \ldots, a_n$.
You can perform the following operation any number (possibly $0$) of times:
- Choose two integers $i$ and $j$, where $1 \le i, j \le n$, and assign $a_i := a_j$.
Find the minimum number of operations required to make the array $a$ satisfy the condit... | Without loss of generality, we assume that every array mentioned below is sorted in non-descending order. An array $b$ of $k$ elements ($k \ge 3$) will satisfy the problem's criteria iff $b_1 + b_2 > b_k$. The proof is that $b_1 + b_2$ is the minimum sum possible of any pair of distinct elements of array $b$, and if it... | [
"binary search",
"math",
"sortings",
"two pointers"
] | 1,400 | class Solution:
hasMultipleTests = True
n: int = None
a: list = None
@classmethod
def preprocess(cls):
pass
@classmethod
def input(cls, testcase):
cls.n = int(input())
cls.a = list(map(int, input().split()))
@classmethod
def solve(cls, testcase):
c... |
2032 | D | Genokraken | This is an interactive problem.
Upon clearing the Waterside Area, Gretel has found a monster named Genokraken, and she's keeping it contained for her scientific studies.
The monster's nerve system can be structured as a tree$^{\dagger}$ of $n$ nodes (really, everything should stop resembling trees all the time$\ldots... | For simplicity, we'll use the term "tentacle" to call each path tree in the forest made by cutting off node $0$. We also notice that in each tentacle, two nodes will never have the same distance from root node $0$. The condition of $p_x \le p_y$ iff $x \le y$ leads to a crucial observation of the system: it is indexed ... | [
"constructive algorithms",
"data structures",
"graphs",
"greedy",
"implementation",
"interactive",
"trees",
"two pointers"
] | 1,800 | class DeleteOnly_DLL:
def __init__(self, size: int):
self.values = [None for _ in range(size)]
self.prev = [(i + size - 1) % size for i in range(size)]
self.next = [(i + 1) % size for i in range(size)]
self.pointer = 0
def current(self):
return self.values[sel... |
2032 | E | Balanced | You are given a \textbf{cyclic} array $a$ with $n$ elements, where $n$ is \textbf{odd}. In each operation, you can do the following:
- Choose an index $1 \le i \le n$ and increase $a_{i - 1}$ by $1$, $a_i$ by $2$, and $a_{i + 1}$ by $1$. The element before the first element is the last element because this is a cyclic... | To simplify this problem a little bit before starting, we will temporarily allow "negative" operation: choose an index $1 \le i \le n$ and increase $a_{i - 1}$ by $-1$, $a_i$ by $-2$, and $a_{i + 1}$ by $-1$. This is counted as $-1$ operation on index $i$. Should we get negative elements in array $v$ in the end, we can... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"math"
] | 2,400 | class Solution:
hasMultipleTests = True
n: int = None
a: list = None
@classmethod
def apply_prefixes(cls, prefixes, v):
for i in range(2, cls.n*2):
prefixes[i] += prefixes[i - 2]
for i in range(cls.n*2):
v[i % cls.n] += prefixes[i]
@classmethod... |
2032 | F | Peanuts | Having the magical beanstalk, Jack has been gathering a lot of peanuts lately. Eventually, he has obtained $n$ pockets of peanuts, conveniently numbered $1$ to $n$ from left to right. The $i$-th pocket has $a_i$ peanuts.
Jack and his childhood friend Alice decide to play a game around the peanuts. First, Alice divides... | Let's get the trivial case out of the way: If the peanut pockets always contain $1$ nut each, then partitioning the pockets doesn't affect the game's outcome at all: Alice will always win if $n$ is odd, and there are $2^{n-1}$ ways to partition $n$ pockets. Jack will always win if $n$ is even. Proof for the trivial cas... | [
"combinatorics",
"dp",
"games",
"math"
] | 2,700 | class Solution:
hasMultipleTests = True
n: int = None
a: list = None
MAXN: int = 1000000
MOD: int = 998244353
pow2: list = None
@classmethod
def preprocess(cls):
cls.pow2 = [None for _ in range(cls.MAXN)]
for i in range(cls.MAXN):
cls.pow2[i] = 1 if i =... |
2033 | A | Sakurako and Kosuke | Sakurako and Kosuke decided to play some games with a dot on a coordinate line. The dot is currently located in position $x=0$. They will be taking turns, and \textbf{Sakurako will be the one to start}.
On the $i$-th move, the current player will move the dot in some direction by $2\cdot i-1$ units. Sakurako will alwa... | For this task we could just brute-force the answer by repeatedly adding or substracting the odd numbers from the initial position $0$. This would result in $O(n)$ time complexity. This is sufficient enough. | [
"constructive algorithms",
"implementation",
"math"
] | 800 | def solve():
n = int(input())
x = 0
c = 1
while -n <= x <= n:
if c % 2 == 1:
x -= 2 * c - 1
else:
x += 2 * c - 1
c += 1
if c % 2 == 0:
print("Sakurako")
else:
print("Kosuke")
for tc in range(int(input())):
solve() |
2033 | B | Sakurako and Water | During her journey with Kosuke, Sakurako and Kosuke found a valley that can be represented as a matrix of size $n \times n$, where at the intersection of the $i$-th row and the $j$-th column is a mountain with a height of $a_{i,j}$. If $a_{i,j} < 0$, then there is a lake there.
Kosuke is very afraid of water, so Sakur... | In this task we were supposed to find the minimal possible amount of moves that Sakurako needs to make in order to make all elements in the matrix non-negative. The key observation is to notice that Sakurako can only add simultaneously to elements that lay on one diagonal. For cell $(i,j)$, let the "index" of diagonal ... | [
"brute force",
"constructive algorithms",
"greedy"
] | 900 | def solve():
n = int(input())
mn = dict()
for i in range(n):
a = [int(x) for x in input().split()]
for j in range(n):
mn[i - j] = min(a[j], mn.get(i - j, 0))
ans = 0
for value in mn.values():
ans -= value
print(ans)
t = int(input())
for _ in range(t):
so... |
2033 | C | Sakurako's Field Trip | Even in university, students need to relax. That is why Sakurakos teacher decided to go on a field trip. It is known that all of the students will be walking in one line. The student with index $i$ has some topic of interest which is described as $a_i$. As a teacher, you want to minimise the disturbance of the line of ... | Note that the answer is influenced by neighboring elements. This allows us to optimally place elements $i$ and $n - i + 1$ with respect to elements $i - 1$ and $n - i + 2$. Thus, we need to be able to choose the best order for an array of $4$ elements. Let's consider several types of arrays: $[1, x, y, 1]$ or $[x, 1, 1... | [
"dp",
"greedy",
"two pointers"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int a[n+1];
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=n/2-1;i>=1;i--){
if(a[i]==a[i+1] || a[n-i+1]==a[n-i]){
swap(a[... |
2033 | D | Kousuke's Assignment | After a trip with Sakurako, Kousuke was very scared because he forgot about his programming assignment. In this assignment, the teacher gave him an array $a$ of $n$ integers and asked him to calculate the number of \textbf{non-overlapping} segments of the array $a$, such that each segment is considered beautiful.
A se... | For this task we were supposed to find the biggest amount of non-intersecting segments all of which have their sum equal to zero. First of all, the problem "find the maximal number of non-intersecting segments" is an exaxmple of a classic dynamic programming problem. First of all, we will sort all our segments by their... | [
"data structures",
"dp",
"dsu",
"greedy",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int a[n+1];
map<int,int>mp;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int p_su[n+1];
p_su[0]=0;
int lst[n+1];
mp[0]=0;
... |
2033 | E | Sakurako, Kosuke, and the Permutation | Sakurako's exams are over, and she did excellently. As a reward, she received a permutation $p$. Kosuke was not entirely satisfied because he failed one exam and did not receive a gift. He decided to sneak into her room (thanks to the code for her lock) and spoil the permutation so that it becomes simple.
A permutatio... | Lets make this the shortest editorial out of all. Observation $1$: All permutations can be split into cycles. All cycles of permutation can be traversed in $O(n)$ time. Observation $2$: When we are swapping $2$ elements that belong to one cycle, we are splitting our cycle into $2$ parts. If we rephrase our definition o... | [
"brute force",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"math"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
ios_base::sync_with_stdio(false);cout.tie(nullptr);cin.tie(nullptr);
cin>>t;
while(t--){
int n;
cin>>n;
int p[n+1];
for(int i=1;i<=n;i++){
cin>>p[i];
}
bool us[n+1];
memset... |
2033 | F | Kosuke's Sloth | Kosuke is too lazy. He will not give you any legend, just the task:
Fibonacci numbers are defined as follows:
- $f(1)=f(2)=1$.
- $f(n)=f(n-1)+f(n-2)$ $(3\le n)$
We denote $G(n,k)$ as an index of the $n$-th Fibonacci number that is divisible by $k$. For given $n$ and $k$, compute $G(n,k)$.As this number can be too bi... | This was one of my favourite tasks untill I realised that the amount of numbers in Fibonacci cycle is either $1$, $2$ or $4$... First of all, the length of cycle after which our sequence would be repeating for modulo $k$ is at most $6k$ (We will just take this as a fact for now, it is too long to explain but you can re... | [
"brute force",
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
#define ssize(x) (int)(x.size())
#define ALL(x) (x).begin(), (x).end()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rd(int l, int r) {
return uniform_int_distribution<int>(l, r)(rng);
}
const LL MOD = 1e9 + 7;
int ... |
2033 | G | Sakurako and Chefir | Given a tree with $n$ vertices rooted at vertex $1$. While walking through it with her cat Chefir, Sakurako got distracted, and Chefir ran away.
To help Sakurako, Kosuke recorded his $q$ guesses. In the $i$-th guess, he assumes that Chefir got lost at vertex $v_i$ and had $k_i$ stamina.
Also, for each guess, Kosuke a... | In each query, Chefir can ascend from vertex $v$ by no more than $k$. To maximize the distance, we need to first ascend $x$ times ($0 \le x \le k$), and then descend to the deepest vertex. For each vertex $u$, we will find $maxd[v].x$ - the distance to the farthest descendant of vertex $u$. We will also need $maxd[v].y... | [
"data structures",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 2,200 | #include <bits/stdc++.h>
//#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(time(nullptr));
const int inf = 1... |
2034 | A | King Keykhosrow's Mystery | There is a tale about the wise King Keykhosrow who owned a grand treasury filled with treasures from across the Persian Empire. However, to prevent theft and ensure the safety of his wealth, King Keykhosrow's vault was sealed with a magical lock that could only be opened by solving a riddle.
The riddle involves two sa... | Step 1: Prove that for the minimum value of $m$, we must have $m \% a = m \% b = 0$. Step 2: To prove this, show that if $m \% a = m \% b = x > 0$, then $m-1$ will also satisfy the problem's requirements. Step 3: Since $m \ge \min(a , b)$, if $x > 0$, then $m > \min(a , b)$ must hold. Therefore, $m - 1 \ge \min(a , b)$... | [
"brute force",
"chinese remainder theorem",
"math",
"number theory"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int tt;
cin >> tt;
while(tt--){
int a, b;
cin >> a >> b;
cout << lcm(a , b) << endl;
}
} |
2034 | B | Rakhsh's Revival | Rostam's loyal horse, Rakhsh, has seen better days. Once powerful and fast, Rakhsh has grown weaker over time, struggling to even move. Rostam worries that if too many parts of Rakhsh's body lose strength at once, Rakhsh might stop entirely. To keep his companion going, Rostam decides to strengthen Rakhsh, bit by bit, ... | We will solve the problem using the following approach: Start from the leftmost spot and move rightwards. Whenever a consecutive segment of $m$ weak spots (i.e., $0$'s) is found, apply Timar to a segment of length $k$, starting from the last index of the weak segment. Repeat this process until no segment of $m$ consecu... | [
"data structures",
"greedy",
"implementation",
"two pointers"
] | 1,000 | # include <bits/stdc++.h>
using namespace std;
const int xn = 2e5 + 10;
int q, n, m, k, ps[xn];
string s;
int main() {
cin >> q;
while (q --) {
cin >> n >> m >> k >> s;
fill(ps, ps + n, 0);
int ans = 0, cnt = 0, sum = 0;
for (int i = 0; i < n; ++ i) {
sum += ps[i]... |
2034 | C | Trapped in the Witch's Labyrinth | In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $n$ rows and $m$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that wheneve... | If a cell has a fixed direction (i.e., it points to another cell), and following that direction leads outside the maze, it must eventually exit the maze. Such cells cannot be part of any loop. We can analyze the remaining cells once we identify cells that lead out of the maze. Any undirected cell or $?$ cell might eith... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
string c[n+1];
for(int i = 1 ; i <= n ; i++) cin >> c[i] , c[i] = "-" + c[i];
vector<pair<int,int>> jda[n+2][m+2];
for(int i = 1 ; i <= n ;... |
2034 | D | Darius' Wisdom | Darius the Great is constructing $n$ stone columns, each consisting of a base and between $0$, $1$, or $2$ inscription pieces stacked on top.
In each move, Darius can choose two columns $u$ and $v$ such that the difference in the number of inscriptions between these columns is exactly $1$, and transfer one inscription... | Step 1: Using two moves, we can move an element to any arbitrary position in the array. Thus, we can place all $0$'s in their correct positions with at most $2 \min(count(0), count(1) + count(2))$ moves. Step 2: After placing all $0$'s, the rest of the array will contain only $1$'s and $2$'s. To sort this part of the a... | [
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 1,600 | // In the name of god
#include <bits/stdc++.h>
using namespace std;
const int N = 200000;
int n, cnt[3], a[N];
vector<int> vip[3][3]; // Value In Position
vector<pair<int, int>> swaps;
inline int Pos(int index) {
if(index < cnt[0])
return 0;
else if(index < cnt[0]+cnt[1])
return 1;
else
... |
2034 | E | Permutations Harmony | Rayan wants to present a gift to Reyhaneh to win her heart. However, Reyhaneh is particular and will only accept a k-harmonic set of permutations.
We define a k-harmonic set of permutations as a set of $k$ \textbf{pairwise distinct} permutations $p_1, p_2, \ldots, p_k$ of size $n$ such that for every pair of indices $... | Step 1: There are $n$ positions that must be equal, and their sum is $\frac{n \cdot (n+1) \cdot k}{2}$. Hence, each position must be $\frac{(n+1) \cdot k}{2}$. Additionally, there must be $k$ distinct permutations, so $k \leq n!$. Step 2: For even $k$, we can group $n!$ permutations into $\frac{n!}{2}$ double handles, ... | [
"combinatorics",
"constructive algorithms",
"greedy",
"hashing",
"math"
] | 2,200 | // In the name of God
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
int t;
cin >> t;
int f[8] = {1,1,2,6,24,120,720,5040};
while(t--) {
int n, k;
cin >> n >> k;
if(min(n, k) == 1) {
if(n*k == 1) {
... |
2034 | F1 | Khayyam's Royal Decree (Easy Version) | \textbf{This is the easy version of the problem. The only differences between the two versions are the constraints on $k$ and the sum of $k$.}
In ancient Persia, Khayyam, a clever merchant and mathematician, is playing a game with his prized treasure chest containing $n$ red rubies worth $2$ dinars each and $m$ blue s... | Step 1: For simplicity, redefine the special conditions for the number of rubies and sapphires in your satchel (not chest). Add two dummy states, $(0,0)$ and $(n,m)$ for convenience (the first one indexed as $0$ and the second one indexed as $k+1$). Note that these dummy states won't involve doubling the value. Step 2:... | [
"combinatorics",
"dp",
"math",
"sortings"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define nl "\n"
#define nf endl
#define ll long long
#define pb push_back
#define _ << ' ' <<
#define INF (ll)1e18
#define mod 998244353
#define maxn 400010
ll fc[maxn], nv[maxn];
ll fxp(ll b, ll e) {
ll r = 1, k = b;
while (e != 0) {
if (e % 2) r = ... |
2034 | F2 | Khayyam's Royal Decree (Hard Version) | \textbf{This is the hard version of the problem. The only differences between the two versions are the constraints on $k$ and the sum of $k$.}
In ancient Persia, Khayyam, a clever merchant and mathematician, is playing a game with his prized treasure chest containing $n$ red rubies worth $2$ dinars each and $m$ blue s... | Step 1: For simplicity, redefine the special conditions for the number of rubies and sapphires in your satchel (not chest). Step 2: Order the redefined conditions $(x, y)$ in increasing order based on the value of $x + y$. Step 3: Define $total_{i,j}$ as the total number of ways to move from state $i$ to state $j$ (ign... | [
"combinatorics",
"dp",
"math",
"sortings"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
#define nl "\n"
#define nf endl
#define ll long long
#define pb push_back
#define _ << ' ' <<
#define INF (ll)1e18
#define mod 998244353
#define maxn 400010
ll fc[maxn], nv[maxn];
ll fxp(ll b, ll e) {
ll r = 1, k = b;
while (e != 0) {
if (e % 2) r = ... |
2034 | G1 | Simurgh's Watch (Easy Version) | \textbf{The only difference between the two versions of the problem is whether overlaps are considered at all points or only at integer points.}
The legendary Simurgh, a mythical bird, is responsible for keeping watch over vast lands, and for this purpose, she has enlisted $n$ vigilant warriors. Each warrior is alert ... | It is easy to check if the solution can be achieved with only one color. For any time point $x$, there must be at most one interval containing $x$, since if multiple intervals contain $x$, they must be colored differently. A simple strategy is to solve the problem using three colors. First, we color some intervals with... | [
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 3,500 | /* In the name of Allah */
// Welcome to the Soldier Side!
// Where there's no one here, but me...
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int t, n, l[N], r[N], col[N];
vector<int> st[N << 1], en[N << 1];
void compress_points() {
vector<int> help;
for (int i = 0; i < n; i++) {
... |
2034 | G2 | Simurgh's Watch (Hard Version) | \textbf{The only difference between the two versions of the problem is whether overlaps are considered at all points or only at integer points.}
The legendary Simurgh, a mythical bird, is responsible for keeping watch over vast lands, and for this purpose, she has enlisted $n$ vigilant warriors. Each warrior is alert ... | Step 1: It is easy to check if the solution can be achieved with only one color. For any time point $x$, there must be at most one interval containing $x$, since if multiple intervals contain $x$, they must be colored differently. Step 2: A simple strategy is to solve the problem using three colors; First, we color som... | [
"greedy",
"implementation"
] | 3,500 | /* In the name of Allah */
// Welcome to the Soldier Side!
// Where there's no one here, but me...
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
vector<int> st[N << 2], en[N << 2];
int t, n, k, l[N], r[N], dp[N], col[N], prv[N];
void compress_numbers() {
vector<int> help;
for (int i = 0;... |
2034 | H | Rayan vs. Rayaneh | Rayan makes his final efforts to win Reyhaneh's heart by claiming he is stronger than Rayaneh (i.e., computer in Persian). To test this, Reyhaneh asks Khwarizmi for help. Khwarizmi explains that a set is integer linearly independent if no element in the set can be written as an integer linear combination of the others.... | Step 1: According to Bézout's Identity, we can compute $\gcd(x_1, \ldots, x_t)$ and all its multipliers as an integer linear combination of $x_1, x_2, \ldots, x_t$. Step 2: A set {$a_1, \ldots, a_k$} is good (integer linearly independent) if for every $i$, $\gcd(${$a_j \mid j \neq i$}$) \nmid a_i$. Step 3: A set {$a_1,... | [
"brute force",
"dfs and similar",
"dp",
"number theory"
] | 3,300 | /// In the name of God the most beneficent the most merciful
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr int T = 100;
constexpr int M = 100001;
constexpr int SQM = 320;
constexpr int LGM = 20;
vector<pair<int,... |
2035 | A | Sliding | \begin{quote}
Red was ejected. They were not the imposter.
\end{quote}
There are $n$ rows of $m$ people. Let the position in the $r$-th row and the $c$-th column be denoted by $(r, c)$. Number each person starting from $1$ in row-major order, i.e., the person numbered $(r-1)\cdot m+c$ is initially at $(r,c)$.
The per... | The people with a smaller row major number won't move at all so we can ignore them. Now we can break everyone else into $2$ groups of people. The first group will be changing rows while the second group will stay in the same row. For the people changing rows their manhattan distance will change by a total of $m$ and th... | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using int64 = long long;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t; while (t--) {
int64 n, m, r, c; cin >> n >> m >> r >> c;
cout << (n - r) * (m - 1) + n * m - (r - 1) * m - c << endl;
}
}
|
2035 | B | Everyone Loves Tres | \begin{quote}
There are 3 heroes and 3 villains, so 6 people in total.
\end{quote}
Given a positive integer $n$. Find the \textbf{smallest} integer whose decimal representation has length $n$ and consists only of $3$s and $6$s such that it is divisible by both $33$ and $66$. If no such integer exists, print $-1$. | If we had the lexicographically smallest number for some $n$, we could extend it to the lexicographically smallest number for $n+2$ by prepending $33$ to it. This is due to the lexicographic condition that values minimize some digits over all the digits behind them. In other words, $3666xx$ is always better than $6333x... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 900 | #include <iostream>
using namespace std;
int main(){
int T;
cin >> T;
while(T--){
int n;
cin >> n;
if(n == 1 || n == 3){
cout << "-1\n";
}else if(n%2 == 0){
for(int i = 0; i<n-2; i++){
cout << "3";
}
cout << "66\n";
}else{
for(int i = 0; i<n-5; i++){
cout << "3";
}
cout << ... |
2035 | C | Alya and Permutation | Alya has been given a hard problem. Unfortunately, she is too busy running for student council. Please solve this problem for her.
Given an integer $n$, construct a permutation $p$ of integers $1, 2, \ldots, n$ that maximizes the value of $k$ (which is initially $0$) after the following process.
Perform $n$ operation... | We can make $k$ what it needs to be using at most the last $5$ numbers of the permutation. Every other element can be assigned randomly. We can split this up into several cases. Case 1: $n$ is odd. The last operation will be bitwise and. The bitwise and of $k$ with the last element which is less than or equal to $n$ is... | [
"bitmasks",
"constructive algorithms",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t; while (t--) {
int n; cin >> n;
set<int> s; FOR(i, 1, n) s.insert(i);
vi a(n + 1);
int po2 = 1; while (po2 * ... |
2035 | D | Yet Another Real Number Problem | \begin{quote}
Three r there are's in strawberry.
\end{quote}
You are given an array $b$ of length $m$. You can perform the following operation any number of times (possibly zero):
- Choose two distinct indices $i$ and $j$ \textbf{where} $\bf{1\le i < j\le m}$ and $b_i$ is even, divide $b_i$ by $2$ and multiply $b_j$ ... | Consider how to solve the problem for an entire array. We iterate backwards on the array, and for each $a_i$ we consider, we give all of its $2$ divisors to the largest $a_j > a_i$ with $j > i$. If $a_i$ is the largest, we do nothing. To do this for every prefix $x$, notice that if we after we have iterated backwards f... | [
"binary search",
"data structures",
"divide and conquer",
"greedy",
"implementation",
"math"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include "debug.hpp"
#else
#define debug(...) (void)0
#endif
using i64 = int64_t;
using u64 = uint64_t;
constexpr bool test = false;
constexpr i64 mod = 1000000007;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
for (int ti = ... |
2035 | E | Monster | \begin{quote}
Man, this Genshin boss is so hard. Good thing they have a top-up of $6$ coins for only $ \$4.99$. I should be careful and spend no more than I need to, lest my mom catches me...
\end{quote}
You are fighting a monster with $z$ health using a weapon with $d$ damage. Initially, $d=0$. You can perform the fo... | Let $\text{damage}(a, b)$ represent the maximum number of damage by performing the first operation $a$ times and the second operation $b$ times. Since we should always increase damage if possible, the optimal strategy will be the following: increase damage by $k$, deal damage, increase damage by $k$, deal damage, and s... | [
"binary search",
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"math",
"ternary search"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
i64 solve(int x, int y, int z, int k) {
auto cost = [&](int a, int b) {
return (i64) a * x + (i64) b * y;
};
auto damage = [&](int a, int b) {
int c = min(b, a / k);
return (i64) k * c * (c + 1) / 2 + (i64) (b -... |
2035 | F | Tree Operations | \begin{quote}
This really says a lot about our society.
\end{quote}
One day, a turtle gives you a tree with $n$ nodes rooted at node $x$. Each node has an initial nonnegative value; the $i$-th node has starting value $a_i$.
You want to make the values of all nodes equal to $0$. To do so, you will perform a series of ... | The key observation to make is that if we can make all nodes equal to $0$ using $t$ operations, we can make all nodes equal to $0$ in $t + 2n$ operations by increasing all nodes by $1$ before decreasing all nodes by $1$. As such, this motivates a binary search solution. For each $i$ from $0$ to $2n - 1$, binary search ... | [
"binary search",
"brute force",
"dfs and similar",
"dp",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include "debug.hpp"
#else
#define debug(...) (void)0
#endif
using i64 = int64_t;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
for (int ti = 0; ti < t; ti += 1) {
int n, x;
cin >> n >> x;
vector<int> a(n + 1);
... |
2035 | G1 | Go Learn! (Easy Version) | \textbf{The differences between the easy and hard versions are the constraints on $n$ and the sum of $n$. In this version, $n \leq 3000$ and the sum of $n$ does not exceed $10^4$. You can only make hacks if both versions are solved.}
Well, well, well, let's see how Bessie is managing her finances. She seems to be in t... | Let's sort the tests by $x_i$. I claim a subsequence of tests $t_1 \dots t_r$ remaining is correct iff $k_{t_i} < k_{t_{i+1}}$ for all $1 \leq i < r$. $x_{t_1} = 1$ or $k_{t_1} \neq 1$. In other words, the set of tests is increasing, and if some test has $k_i = 1$, that test's $x_i$ must $= 1$. This is because a binary... | [
"dp",
"trees"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int, int>
#define f first
#define s second
const int mx = 3005, md = 998244353;
int n, m, t, A[mx]; pii ans; vector<int> touch[mx]; vector<pii> tests; pii dp[mx];
pii comb(pii a, pii b){
return a.f == b.f ? make_pair(a.f, (... |
2035 | G2 | Go Learn! (Hard Version) | \textbf{The differences between the easy and hard versions are the constraints on $n$ and the sum of $n$. In this version, $n \leq 3\cdot 10^5$ and the sum of $n$ does not exceed $10^6$. You can only make hacks if both versions are solved.}
Well, well, well, let's see how Bessie is managing her finances. She seems to ... | Read the editorial for G1; we will build off of that. The most important observation is that $b$ is defined above as at most $1$. If you consider binary searching for $j$ and $i$, at the index $m$ which is present both in $\text{touch}(j)$ and $\text{touch}(i)$ and between $j$ and $i$, the search must go left for $j$ a... | [
"divide and conquer",
"dp"
] | 3,500 | //maomao and hanekawa will carry me to red
//#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <iostream>
#include <iomanip>
#include <cmath>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <array>
#include <cstring>
#include <functional>
#include <numeric>
#include <se... |
2035 | H | Peak Productivity Forces | \begin{quote}
I'm peakly productive and this is deep.
\end{quote}
You are given two permutations$^{\text{∗}}$ $a$ and $b$, both of length $n$.
You can perform the following three-step operation on permutation $a$:
- Choose an index $i$ ($1 \le i \le n$).
- Cyclic shift $a_1, a_2, \ldots, a_{i-1}$ by $1$ to the right... | We can rephrase the problem as sorting $b^{-1}(a)$. First, it is impossible to sort the permutation $[2, 1]$ because no operations you make affect the permutation. Instead of completely sorting it we can get it to a semi sorted state in $n + 1$ moves. This semi sorted state will be: some pairs of non-intersecting adjac... | [
"constructive algorithms"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
// #include "../lib/hori.h"
struct ds {
vector<int> occ, pos;
int counter, n;
ds() {}
ds(vector<int> perm) {
counter = 0;
n = ssize(perm);
occ = vector<int>(n, 0);
pos = vector<int>(2 * n, 0); // store n + i - update
for (int i = 0; i < n; i++... |
2036 | A | Quintomania | Boris Notkin composes melodies. He represents them as a sequence of notes, where each note is encoded as an integer from $0$ to $127$ inclusive. The interval between two notes $a$ and $b$ is equal to $|a - b|$ semitones.
Boris considers a melody perfect if the interval between each two adjacent notes is either $5$ sem... | If for all $i$ $(1 \leq i \leq n - 1)$ is true $|a_i - a_{i+1}| = 5$ or $|a_i - a_{i+1}| = 7$, the answer to the problem is "YES", otherwise it is "NO". Complexity: $O(n)$ | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
bool solve(){
int n;
cin >> n;
vector<int>a(n);
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 1; i < n; i++) {
if(abs(a[i] - a[i - 1]) != 5 && abs(a[i] - a[i - 1]) != 7) return false;
}
return true;
}
int main() {
int t;
c... |
2036 | B | Startup | Arseniy came up with another business plan — to sell soda from a vending machine! For this, he purchased a machine with $n$ shelves, as well as $k$ bottles, where the $i$-th bottle is characterized by the brand index $b_i$ and the cost $c_i$.
You can place any number of bottles on each shelf, but all bottles on the sa... | Let's create an array brand_cost of length $k$ and fill it so that brand_cost[i] stores the cost of all bottles of brand $i+1$. Then sort the array by non-growing and calculate the sum of its first min(n, k) elements, which will be the answer to the problem. Complexity: $O(k \cdot \log k)$ | [
"greedy",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> brand_cost(k, 0);
for (int i = 0; i < k; i++) {
int b, c;
cin >> b >> c;
brand_cost[b - 1] += c;
}
sort(brand_cost.rbegin(), brand_cost.rend());
long long ans = 0;
for (int i = 0; i < min(n, k... |
2036 | C | Anya and 1100 | While rummaging through things in a distant drawer, Anya found a beautiful string $s$ consisting only of zeros and ones.
Now she wants to make it even more beautiful by performing $q$ operations on it.
Each operation is described by two integers $i$ ($1 \le i \le |s|$) and $v$ ($v \in \{0, 1\}$) and means that the $i... | With each query, to track the change in the presence of "1100" in a row, you don't have to go through the entire row - you can check just a few neighboring cells. First, in a naive way, let's count $count$ - the number of times "1100" occurs in $s$. Then for each of $q$ queries we will update $count$: consider the subs... | [
"brute force",
"implementation"
] | 1,100 | #include <cstdio>
#include <cstring>
using namespace std;
typedef long long l;
char buf[1000000];
l n;
bool check_1100(l i) {
if (i < 0) return false;
if (i >= n - 3) return false;
if (buf[i] == '1' && buf[i + 1] == '1' && buf[i + 2] == '0' && buf[i + 3] == '0') return true;
return false;
}
void solve() {
scan... |
2036 | D | I Love 1543 | One morning, Polycarp woke up and realized that $1543$ is the most favorite number in his life.
The first thing that Polycarp saw that day as soon as he opened his eyes was a large wall carpet of size $n$ by $m$ cells; $n$ and $m$ are even integers. Each cell contains one of the digits from $0$ to $9$.
Polycarp becam... | We will go through all layers of the carpet, adding to the answer the number of $1543$ records encountered on each layer. To do this, we can iterate over, for example, the top-left cells of each layer having the form $(i, i)$ for all $i$ in the range $[1, \frac{min(n, m)}{2}]$, and then traverse the layer with a naive ... | [
"brute force",
"implementation",
"matrices"
] | 1,300 | #include <cstdio>
char a[1005][1005];
char layer[4005];
void solve() {
int n, m; scanf("%d %d", &n, &m);
for (int i = 0; i < n; ++i) scanf("%s", a[i]);
int count = 0;
for (int i = 0; (i + 1) * 2 <= n && (i + 1) * 2 <= m; ++i) {
int pos = 0;
for (int j = i; j < m - i; ++j) layer[po... |
2036 | E | Reverse the Rivers | A conspiracy of ancient sages, who decided to redirect rivers for their own convenience, has put the world on the brink. But before implementing their grand plan, they decided to carefully think through their strategy — that's what sages do.
There are $n$ countries, each with exactly $k$ regions. For the $j$-th region... | For any non-negative integers, $a \leq a | b$, where $|$ is the bitwise "or" operation. After computing the values of $b_{i,j}$ for all countries and regions, we can notice that for a fixed region $j$, the values of $b_{i,j}$ increase as the index $i$ increases. This is because the bitwise "or" operation cannot decreas... | [
"binary search",
"constructive algorithms",
"data structures",
"greedy"
] | 1,600 | #include <cstdio>
typedef long long l;
l ** arr;
int main() {
l n, k, q; scanf("%lld %lld %lld", &n, &k, &q);
arr = new l*[n];
for (l i = 0; i < n; i++) arr[i] = new l[k];
for (l i = 0; i < n; i++) for (l j = 0; j < k; j++) scanf("%lld", &arr[i][j]);
for (l i = 1; i < n; i++) for (l j = 0; j < k; j++) arr[i]... |
2036 | F | XORificator 3000 | Alice has been giving gifts to Bob for many years, and she knows that what he enjoys the most is performing bitwise XOR of interesting integers. Bob considers a positive integer $x$ to be interesting if it satisfies $x \not\equiv k (\bmod 2^i)$. Therefore, this year for his birthday, she gifted him a super-powerful "XO... | Note the base of the module Can we quickly compute XOR on the segment $[l, r]$? We also recommend the beautiful tutorial by ne_justlm! Let us introduce the notation $\DeclareMathOperator{\XOR}{XOR}\XOR(l, r) = l \oplus (l+1) \oplus \dots \oplus r$ . The first thing that comes to mind when reading the condition is that ... | [
"bitmasks",
"dp",
"number theory",
"two pointers"
] | 1,900 | #include <iostream>
using namespace std;
#define int uint64_t
#define SPEEDY std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);
int xor_0_n(int n) {
int rem = n % 4;
if (rem == 0) {
return n;
}
if (rem == 1) {
return 1;
}
if (rem == 2) {
return n + 1;... |
2036 | G | Library of Magic | This is an interactive problem.
The Department of Supernatural Phenomena at the Oxenfurt Academy has opened the Library of Magic, which contains the works of the greatest sorcerers of Redania — $n$ ($3 \leq n \leq 10^{18}$) types of books, numbered from $1$ to $n$. Each book's type number is indicated on its spine. Mo... | Have you considered the cases where $a \oplus b \oplus c = 0$? Suppose you are certain that at least one lost number is located on some segment $[le, ri]$. Can you choose a value $mid$ such that the queries xor {le} {mid} and xor {mid + 1} {ri} you can unambiguously understand on which of the segments ($[le, mid]$ or $... | [
"binary search",
"constructive algorithms",
"divide and conquer",
"interactive",
"math",
"number theory"
] | 2,200 | #include <cstdio>
typedef long long l;
l n, num1, num2;
l req(l le, l ri, l num) {
if (le > n) return 0;
if (ri > n) ri = n;
printf("xor %lld %lld\n", le, ri); fflush(stdout);
l res; scanf("%lld", &res);
if (num > 1 && le <= num1 && num1 <= ri) res ^= num1;
if (num > 2 && le <= num2 ... |
2037 | A | Twice | Kinich wakes up to the start of a new day. He turns on his phone, checks his mailbox, and finds a mysterious present. He decides to unbox the present.
Kinich unboxes an array $a$ with $n$ integers. Initially, Kinich's score is $0$. He will perform the following operation any number of times:
- Select two indices $i$ ... | We want to count how many times we can choose $i$ and $j$ such that $a_i = a_j$. Suppose $f_x$ stores the frequency of $x$ in $a$. Once we choose $a_i = a_j = x$, $f_x$ is subtracted by $2$. Thus, the answer is the sum of $\lfloor \frac{f_x}{2} \rfloor$ over all $x$. | [
"implementation"
] | 800 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
print(sum([a.count(x) // 2 for x in range(n + 1)])) |
2037 | B | Intercepted Inputs | To help you prepare for your upcoming Codeforces contest, Citlali set a grid problem and is trying to give you a $n$ by $m$ grid through your input stream. Specifically, your input stream should contain the following:
- The first line contains two integers $n$ and $m$ — the dimensions of the grid.
- The following $n$ ... | It is worth noting that test $4$ is especially made to blow up python dictionaries, sets, and Collections.counter. If you are time limit exceeding, consider using a frequency array of length $n$. You must check if you can find two integers $n$ and $m$, such that $n \cdot m+2=k$. You can either use a counter, or use two... | [
"brute force",
"implementation"
] | 800 | testcases = int(input())
for _ in range(testcases):
k = int(input())
list = input().split()
freq = []
for i in range(k+1):
freq.append(0)
for x in list:
freq[int(x)] = freq[int(x)]+1
solution = (-1,-1)
for i in range(1,k+1):
if i*i==k-2:
if freq[i]>1:
... |
2037 | C | Superultra's Favorite Permutation | Superultra, a little red panda, desperately wants primogems. In his dreams, a voice tells him that he must solve the following task to obtain a lifetime supply of primogems. Help Superultra!
Construct a permutation$^{\text{∗}}$ $p$ of length $n$ such that $p_i + p_{i+1}$ is composite$^{\text{†}}$ over all $1 \leq i \l... | Remember that all even numbers greater than $2$ are composite. As $1+3 > 2$, any two numbers with same parity sum up to a composite number. Now you only have to find one odd number and one even number that sum up to a composite number. One can manually verify that there is no such pair in $n \leq 4$, but in $n=5$ there... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,000 | for _ in range(int(input())):
n = int(input())
if n < 5:
print(-1)
continue
for i in range(2,n+1,2):
if i != 4:
print(i,end=" ")
print("4 5",end=" ")
for i in range(1,n+1,2):
if i != 5:
print(i, end = " ")
print() |
2037 | D | Sharky Surfing | Mualani loves surfing on her sharky surfboard!
Mualani's surf path can be modeled by a number line. She starts at position $1$, and the path ends at position $L$. When she is at position $x$ with a jump power of $k$, she can jump to any \textbf{integer} position in the interval $[x, x+k]$. Initially, her jump power is... | Process from earliest to latest. Maintain a priority queue of power-ups left so far. If Mualani meets a power-up, add it to the priority queue. Otherwise (Mualani meets a hurdle), take power-ups in the priority queue from strongest to weakest until you can jump over the hurdle. This guarantees that each time Mualani ju... | [
"data structures",
"greedy",
"two pointers"
] | 1,300 | import sys
import heapq
input = sys.stdin.readline
for _ in range(int(input())):
n,m,L = map(int,input().split())
EV = []
for _ in range(n):
EV.append((*list(map(int,input().split())),1))
for _ in range(m):
EV.append((*list(map(int,input().split())),0))
EV.sort()
k = 1
pwr = ... |
2037 | E | Kachina's Favorite Binary String | This is an interactive problem.
Kachina challenges you to guess her favorite binary string$^{\text{∗}}$ $s$ of length $n$. She defines $f(l, r)$ as the number of subsequences$^{\text{†}}$ of $01$ in $s_l s_{l+1} \ldots s_r$. \textbf{Two subsequences are considered different if they are formed by deleting characters fr... | Notice that for if for some $r$ we have $f(1, r) < f(1, r + 1)$ then we can conclude that $s_{r + 1} = 1$ (if it is $0$ then $f(1, r) = f(1, r + 1)$ will be true) and if $f(1, r)$ is non-zero and $f(1, r) = f(1, r + 1)$ then $s_{r + 1}$ is $0$. Unfortunately this is only useful if there is a $0$ in $s_1,s_2,...,s_r$, s... | [
"dp",
"greedy",
"interactive",
"two pointers"
] | 1,600 | def qu(a,b):
if (a,b) not in d:
print("?", a+1,b+1)
d[(a,b)] = int(input())
return d[(a,b)]
for _ in range(int(input())):
d = dict()
n = int(input())
SOL = ["0"] * n
last = qu(0,n-1)
if last:
z = 1
for i in range(n-2,0,-1):
nw= qu(0,i)
... |
2037 | F | Ardent Flames | You have obtained the new limited event character Xilonen. You decide to use her in combat.
There are $n$ enemies in a line. The $i$'th enemy from the left has health $h_i$ and is currently at position $x_i$. Xilonen has an attack damage of $m$, and you are ready to defeat the enemies with her.
Xilonen has a powerful... | Let's perform binary search on the minimum number of hits to kill at least $k$ enemies. How do we check if a specific answer is possible? Let's consider a single enemy for now. If its health is $h_i$ and we need to kill it in at most $q$ attacks, then we need to be doing at least $\lceil\frac{h_i}{q}\rceil$ damage per ... | [
"binary search",
"data structures",
"math",
"sortings",
"two pointers"
] | 2,100 | import sys
input = sys.stdin.readline
from collections import defaultdict
for _ in range(1):
n,m,k = map(int,input().split())
h = list(map(int,input().split()))
x = list(map(int,input().split()))
lo = 0
hi = int(1e10)
while hi - lo > 1:
mid = (lo + hi) // 2
ev = defaultdict(int)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.