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 ⌀ |
|---|---|---|---|---|---|---|---|
1987 | E | Wonderful Tree! | \begin{quote}
God's Blessing on This ArrayForces!
\hfill A Random Pebble
\end{quote}
You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.
Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ wh... | Let $b_v := \sum_{u \in L}{a_u} - a_v$ if $L$ is not empty and $b_v := +\infty$ otherwise. Then, in one operation we decrease $b_v$ by $1$ and increase $b_{p_v}$ by $1$ ($p_v$ is the parent of $v$), and our objective is to make $b_v \ge 0$ for all vertices $v$ in as few operations as possible. We can actually chain our... | [
"brute force",
"data structures",
"dfs and similar",
"dsu",
"greedy",
"trees"
] | 2,000 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const ll inf = 1e15;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (auto &x: a) cin >> x;
... |
1987 | F2 | Interesting Problem (Hard Version) | \textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if both versions of the problem are solved.}
You are given an array of integers $a$ of length $n$.
In one operation, you will perform the following two-step process:
- Choos... | Balanced bracket sequence analogy Suppose there is a way to remove the entire array. Let's look at the process in reverse. Then, we are effectively inserting pairs of adjacent elements into an array until we get the original one. Let's look at a mirror process, where instead we keep inserting pairs of brackets $()$ to ... | [
"dp"
] | 2,600 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int inf = 1e9;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) ci... |
1987 | G1 | Spinning Round (Easy Version) | \textbf{This is the easy version of the problem. The only difference between the two versions are the allowed characters in $s$. In the easy version, $s$ only contains the character ?. You can make hacks only if both versions of the problem are solved.}
You are given a permutation $p$ of length $n$. You are also given... | Meow? (Waiting for something to happen?) Consider that the edges are directed from $i \to l_i$ or $i \to r_i$ respectively. So that edges point from vertices with smaller values to vertices with larger values. That is $a \to b$ implies that $p_a < p_b$. Notice that by definition, every vertex must have only $1$ edge th... | [
"divide and conquer",
"dp",
"trees"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
#define ii pair<int,int>
#define fi first
#define se second
#define pub push_back
#define pob pop_back
#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define sz(x) (int)(x).size()
int n;
int arr[400005];
stri... |
1987 | G2 | Spinning Round (Hard Version) | \textbf{This is the hard version of the problem. The only difference between the two versions are the allowed characters in $s$. You can make hacks only if both versions of the problem are solved.}
You are given a permutation $p$ of length $n$. You are also given a string $s$ of length $n$, where each character is eit... | For simplicity, let $p_0 = p_{n+1} = +\infty$, and let's recalculate the values of $l_i$ and $r_i$. Then, the answer is not $-1$ if for all $1 \le i \le n$ and $p_i < n$: $s_i =~$L $\implies l_i \ge 1$. $s_i =~$R $\implies r_i \le n$. $s_i =~$? $\implies l_i \ge 1$ or $r_i \le n$. Let $dp[tl][tr]$ store some set of pai... | [
"divide and conquer",
"dp",
"trees"
] | 3,500 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
array<vector<int>, 2> get_l_and_r(vector<int> &p) {
int n = p.size();
vector<int> l(n), r(n);
stack<i... |
1987 | H | Fumo Temple | \begin{quote}
This temple only magnifies the mountain's power.
\hfill Badeline
\end{quote}
This is an interactive problem.
You are given two positive integers $n$ and $m$ ($\bf{n \le m}$).
The jury has hidden from you a rectangular matrix $a$ with $n$ rows and $m$ columns, where $a_{i,j} \in \{ -1, 0, 1 \}$ for all ... | In this solution, we will assume that there is no matrix $a$ and the interactor just returns some number $x$ between $di + dj \le x \le di + dj + (di + 1)(dj + 1)$, where $di = |i - i_0|$ and $dj = |j - j_0|$. Let's first solve for $n = 1$. Let the hidden cell be $(1, j_0)$. Let $l = 1$ and $r = m$. On each iteration, ... | [
"interactive"
] | 3,500 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int ans_x = 0, ans_y = 0, cnt_q = 0;
// Coordinates are flipped
int query(int x, int y) {
cnt_q++;
int res = 0;
... |
1988 | A | Split the Multiset | A multiset is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. For example, $\{2,2,4\}$ is a multiset.
You have a multiset $S$. Initially, the multiset contains only one positive integer $n$. That is, $S=\{n\}$. Additionally, there is a given positive integer $k$.
I... | The optimal sequence of operations is very simple. The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\lceil \frac{n-1}{k-1}\rceil$. I failed to find a Div2-A level proof. If you have a simpler proof please share it i... | [
"brute force",
"greedy",
"implementation",
"math"
] | 900 | t = (int)(input())
for _ in range(t):
n, k = map(int, input().split())
print((n - 1 + k - 2) // (k - 1)) |
1988 | B | Make Majority | You are given a sequence $[a_1,\ldots,a_n]$ where each element $a_i$ is either $0$ or $1$. You can apply several (possibly zero) operations to the sequence. In each operation, you select two integers $1\le l\le r\le |a|$ (where $|a|$ is the current length of $a$) and replace $[a_l,\ldots,a_r]$ with a single element $x$... | "Most sequences" can be transformed into $[1]$. Conditions for a sequence to be un-transformable is stringent. Find several simple substrings that make the string transformable. We list some simple conditions for a string to be transformable: If 111 exists somewhere (as a substring) in the string, the string is always ... | [
"greedy",
"implementation"
] | 900 | t = (int)(input())
for _ in range(t):
n = (int)(input())
a = input()
ok = 0
if a.count("111") >= 1:
ok = 1
if a.count("11") >= 2:
ok = 1
if a.count("11") >= 1 and (a[0] == "1" or a[-1] == "1"):
ok = 1
if a[0] == "1" and a[-1] == "1":
ok = 1
if ok:
... |
1988 | C | Increasing Sequence with Fixed OR | You are given a positive integer $n$. Find the \textbf{longest} sequence of positive integers $a=[a_1,a_2,\ldots,a_k]$ that satisfies the following conditions, and print the sequence:
- $a_i\le n$ for all $1\le i\le k$.
- $a$ is strictly increasing. That is, $a_i>a_{i-1}$ for all $2\le i\le k$.
- $a_i\,|\,a_{i-1}=n$ f... | The answer is a simple construction. The maximum length for $2^k-1\ (k>1)$ is $k+1$. It's obvious that the answer only depends on the popcount of $n$. Below, we assume $n=2^k-1$. If $k=1$, it is shown in the samples that the length is $1$. Otherwise, the maximum sequence length for $2^k-1$ is $k+1$. This can be achived... | [
"bitmasks",
"constructive algorithms",
"greedy"
] | 1,300 | t = (int)(input())
for _ in range(t):
n = (int)(input())
a = []
for i in range(62, -1, -1):
x = 1 << i
if ((x & n) == x) and (x != n):
a.append(n - x)
a.append(n)
print(len(a))
for i in a:
print(i, end=" ")
print("") |
1988 | D | The Omnipotent Monster Killer | You, the monster killer, want to kill a group of monsters. The monsters are on a tree with $n$ vertices. On vertex with number $i$ ($1\le i\le n$), there is a monster with $a_i$ attack points. You want to battle with monsters for $10^{100}$ rounds.
In each round, the following happens in order:
- All living monsters ... | Formulate the problem. Some variables can't be large. Suppose monster $i$ is killed in round $b_i$. Then, the total health decrement is the sum of $a_i\times b_i$. The "independent set" constraint means that for adjacent vertices, their $b$-s must be different. Observation: $b_i$ does not exceed $\lfloor \log_2 n\rfloo... | [
"brute force",
"dfs and similar",
"dp",
"trees"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll a[300005], f[300005][24], smn[30];
vector<int> g[300005];
void dfs(int x, int fa) {
for (int i = 1; i <= 22; i++) f[x][i] = i * a[x];
for (int y : g[x]) {
if (y == fa) continue;
dfs(y, x);
ll tt = 8e18;
smn[23] = 8e18;
for (int i ... |
1988 | E | Range Minimum Sum | For an array $[a_1,a_2,\ldots,a_n]$ of length $n$, define $f(a)$ as the sum of the minimum element over all subsegments. That is, $$f(a)=\sum_{l=1}^n\sum_{r=l}^n \min_{l\le i\le r}a_i.$$
A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. You are given a permutati... | Formulate the problem on a cartesian tree. Find a clever bruteforce. Calculate the time complexity carefully. Build the cartesian tree of $a$. Let $lc_x,rc_x$ respectively be $x$'s left and right children. Consider a vertex $x$. If we delete it, what would happen to the tree? Vertices that are on the outside of $x$'s s... | [
"binary search",
"brute force",
"data structures",
"divide and conquer",
"implementation"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pr;
int n, a[500005], st[500005], c[500005][2], top, sz[500005];
ll ans[500005], atv[500005], sum;
void dfs1(int x) {
sz[x] = 1;
for (int i = 0; i < 2; i++)
if (c[x][i]) dfs1(c[x][i]), sz[x] += sz[c[x][i]];
sum += (atv[x] = ... |
1988 | F | Heartbeat | For an array $u_1, u_2, \ldots, u_n$, define
- a prefix maximum as an index $i$ such that $u_i>u_j$ for all $j<i$;
- a suffix maximum as an index $i$ such that $u_i>u_j$ for all $j>i$;
- an ascent as an index $i$ ($i>1$) such that $u_i>u_{i-1}$.
You are given three cost arrays: $[a_1, a_2, \ldots, a_n]$, $[b_1, b_2, ... | We can use dp to calculate the number of permutations of $1\sim n$ with $i$ prefix maximums and $j$ ascents, $f(n,i,j)$: consider where 1 is inserted, we will have a $O(n^3)$ dp that finds $f(n,i,j)$ for all suitable $(n,i,j)$-s. For suffix maximums, (the number of permutations of $1\sim n$ with $i$ prefix maximums and... | [
"combinatorics",
"dp",
"fft",
"math"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353, N = 705;
int n, a[N + 5], b[N + 5], c[N + 5], f[N + 5][N + 5], u[N + 5][N + 5], v[N + 5][N + 5],
C[N + 5][N + 5];
int g[N + 5], h[N + 5], t[N + 5][N + 5], p[N + 5][N + 5], ny[N + 5], o[N + 5];
void upd(int &x, int y) { x += y, (x >= mod && (x ... |
1989 | A | Catch the Coin | Monocarp visited a retro arcade club with arcade cabinets. There got curious about the "Catch the Coin" cabinet.
The game is pretty simple. The screen represents a coordinate grid such that:
- the X-axis is directed from left to right;
- the Y-axis is directed from bottom to top;
- the center of the screen has coordi... | At first glance, it's not very convenient that the move consists of two parts: first the character moves, then the coin. Let's try to combine these steps. Since the coin moves down by $1$ each time, we can add this change in the $y$ coordinate to the change in the character's $y$ coordinate. That is, the character can ... | [
"implementation"
] | 800 | for _ in range(int(input())):
x, y = map(int, input().split())
print("YES" if y >= -1 else "NO") |
1989 | B | Substring and Subsequence | You are given two strings $a$ and $b$, both consisting of lowercase Latin letters.
A subsequence of a string is a string which can be obtained by removing several (possibly zero) characters from the original string. A substring of a string is a contiguous subsequence of that string.
For example, consider the string a... | Since the string $a$ is a substring of the answer, the answer can be represented as follows - $x + a + y$, where + denotes string concatenation, and $x$ and $y$ are some, possibly empty, strings. Now, we have to ensure that the string $x+a+y$ contains the string $b$ as a subsequence. Notice that to minimize the length ... | [
"brute force",
"greedy",
"strings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string a, b;
cin >> a >> b;
int n = a.size(), m = b.size();
int ans = n + m;
for (int i = 0; i < m; ++i) {
int j = i;
for (auto c : a) {
if (j < m && c == b[j]) ++j;
}
a... |
1989 | C | Two Movies | A movie company has released $2$ movies. These $2$ movies were watched by $n$ people. For each person, we know their attitude towards the first movie (liked it, neutral, or disliked it) and towards the second movie.
If a person is asked to leave a review for the movie, then:
- if that person liked the movie, they wil... | Let's notice an important fact: if $a_i \ne b_i$, it is always optimal to choose a review for the movie with the better rating: taking the worse option doesn't increase the rating of any movie. Using this fact, let's calculate several values: $x$ - the rating of the first movie among people who liked the first movie mo... | [
"greedy",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n), b(n);
for (auto& x : a) cin >> x;
for (auto& x : b) cin >> x;
int x = 0, y = 0, neg = 0, pos = 0;
for (int i = 0; i < n; ++i) {
if (a[i] > b[i]) {
... |
1989 | D | Smithing Skill | You are playing a famous computer game (that just works) where you have various skills you can level up. Today, you focused on the "Smithing" skill. Your tactic is obvious: forging weapons from ingots and then melting them back to return the materials partially. For simplicity, every time you create an item, you get $1... | It's quite obvious that we should melt every weapon we forge, and we can do it as soon as we forge it. So, let's do these actions in pairs: forge a weapon, then instantly melt it. Since you can't use two types of metal while forging one weapon, we can solve our task independently for each metal type. Suppose you have $... | [
"brute force",
"data structures",
"dp",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,900 | fun main() {
val (n, m) = readln().split(" ").map { it.toInt() }
val a = readln().split(" ").map { it.toInt() }
val b = readln().split(" ").map { it.toInt() }
val c = readln().split(" ").map { it.toInt() }
val mx = a.maxOrNull()!! + 1
val best = IntArray(mx) { 1e9.toInt() }
val calc = IntA... |
1989 | E | Distance to Different | Consider an array $a$ of $n$ integers, where every element is from $1$ to $k$, and every integer from $1$ to $k$ appears \textbf{at least once}.
Let the array $b$ be constructed as follows: for the $i$-th element of $a$, $b_i$ is the distance to the closest element in $a$ which is not equal to $a_i$. In other words, $... | Consider a block of equal elements in $a$. If we split $a$ into such blocks, we can consider each block separately - for each element, we need only the distance to the closest border of the block (except for the first and the last block, where we consider only one border). It's quite easy to see that if the length of t... | [
"combinatorics",
"dp",
"math"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int main()
{
int n;
cin >> n;
int k;
cin >> k;
vector<vector<int>> dp(n + 1, vect... |
1989 | F | Simultaneous Coloring | You are given a matrix, consisting of $n$ rows and $m$ columns.
You can perform two types of actions on it:
- paint the entire column in blue;
- paint the entire row in red.
\textbf{Note that you cannot choose which color to paint the row or column.}
In one second, you can perform either one action or multiple acti... | The main idea is as follows. Consider any constraint on a cell. If the cell must be red, then the last action on this cell must be coloring the row; otherwise, it should be the column. That is, if the operation is applied to both the row and the column of this cell, then there is a certain order of performing these ope... | [
"dfs and similar",
"divide and conquer",
"graphs"
] | 3,000 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct edge{
int v, u;
};
vector<vector<int>> g, tg;
vector<int> ord;
vector<char> used;
vector<int> clr;
void ts(int v){
used[v] = true;
for (int u : g[v]) if (!used[u])
ts(u);
ord.push_back(v);
}
void dfs(int... |
1990 | A | Submission Bait | Alice and Bob are playing a game in an array $a$ of size $n$.
They take turns to do operations, with Alice starting first. The player who can not operate will lose. At first, a variable $mx$ is set to $0$.
In one operation, a player can do:
- Choose an index $i$ ($1 \le i \le n$) such that $a_{i} \geq mx$ and set $m... | For Alice, what if choosing the maximum value doesn't work? Consider parity. Case $1$: When all values appear an even number of times, Alice will lose. This is because no matter which number Alice chooses, Bob can mimic Alice's move. Case $2$: When at least one value appears an odd number of times, Alice will win. Alic... | [
"brute force",
"games",
"greedy",
"sortings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 55;
int n;
int q[N];
v... |
1990 | B | Array Craft | For an array $b$ of size $m$, we define:
- the \textbf{maximum prefix position} of $b$ is the \textbf{smallest} index $i$ that satisfies $b_1+\ldots+b_i=\max_{j=1}^{m}(b_1+\ldots+b_j)$;
- the \textbf{maximum suffix position} of $b$ is the \textbf{largest} index $i$ that satisfies $b_i+\ldots+b_m=\max_{j=1}^{m}(b_j+\ld... | Starting from a trival construction. Utilize the condition $x > y$. First, we consider making $presum_x > presum_j$ for all $x < i \le n$, and similarly for $y$. We can think of a trivial construction: $a[r, \ldots ,l]=[1, \ldots ,1], a[1, \ldots...,r-1]=[-1, \ldots, -1]$ and $a[l+1,\ldots,n]=[-1, \ldots, -1]$. The con... | [
"constructive algorithms",
"greedy"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while(t>0){
t--;
int n,x,y;
cin >> n >> x >> y;
x--; y--;
vector<int> a(n,1);
int e;
e=-1;
for(int i=x+1;i<n;i++){
a[i]=e;
e*=-1;
}
e=-... |
1990 | C | Mad MAD Sum | We define the $\operatorname{MAD}$ (Maximum Appearing Duplicate) in an array as the largest number that appears at least twice in the array. Specifically, if there is no number that appears at least twice, the $\operatorname{MAD}$ value is $0$.
For example, $\operatorname{MAD}([1, 2, 1]) = 1$, $\operatorname{MAD}([2, ... | After one operation, the array becomes non-decreasing. Consider $a_1=a_2=\ldots=a_n$, the operation seems to have shifted the array right. When does the "right shift" parttern happen? Read hints first. Let's consider only non-decreasing arrays. Observe a continuous segments $a[l...r]=x(l<r,x>0)$, after one operation, w... | [
"brute force",
"greedy",
"math"
] | 1,500 |
#include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 200005;
int n;
int a[N... |
1990 | D | Grid Puzzle | You are given an array $a$ of size $n$.
There is an $n \times n$ grid. In the $i$-th row, the first $a_i$ cells are black and the other cells are white. In other words, note $(i,j)$ as the cell in the $i$-th row and $j$-th column, cells $(i,1), (i,2), \ldots, (i,a_i)$ are black, and cells $(i,a_i+1), \ldots, (i,n)$ ar... | Obviously, when $a_i$ is large enough, we will definitely use operation $2$ on the $i$-th row. What is its specific value? It is $5$(try to prove it). Now we can only consider $a_i \le 4$ cases. From left to right, consider a greedy solution or a DP solution. Read hints first. For $a_i \ge 5$, we will definitely use op... | [
"bitmasks",
"brute force",
"dp",
"greedy",
"implementation"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 200005;
int n;
int a[N]... |
1990 | E2 | Catch the Mole(Hard Version) | \textbf{This is the hard version of the problem. The only difference is the limit on the number of queries.}
\textbf{This is an interactive problem.}
You are given a tree of $n$ nodes with node $1$ as its root node.
There is a hidden mole in one of the nodes. To find its position, you can pick an integer $x$ ($1 \le... | Consider querying a subtree. If the jury returns $0$, we can delete the entire subtree. We can query any leaf node. If the jury returns $1$, we are done; otherwise, the mole will move up. Consider querying a subtree. If the jury returns $1$, we can "drive" it out of this subtree using the method in hint2. Combime the i... | [
"binary search",
"data structures",
"dfs and similar",
"divide and conquer",
"interactive",
"trees"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
#define all(a) a.begin(),a.end()
#define pb push_back
#define sz(a) ((int)a.size())
using ll=long long;
using u32=unsigned int;
using u64=unsigned long long;
using i128=__int128;
using u128=unsigned __int128;
using f128=__float128;
using pii=pair<int,int>;
using pll=pair<... |
1990 | F | Polygonal Segments | You are given an array $a$ of size $n$.
A segment $[l, r](1 \le l < r \le n)$ is called a \textbf{polygonal} segment only if the following conditions hold:
- $(r-l+1) \geq 3$;
- Considering $a_l, a_{l+1}, \ldots, a_r$ as side lengths, these sides can form a polygon with $(r-l+1)$ sides.
Process $q$ queries of two ty... | Consider using a segment tree to solve this problem. We need to merge the information of two intervals. First, we take the maximum value of the answers in the two intervals, and then calculate the polygon segment spanning the two intervals. We notice that a local maximal polygon segment $[l, r]$ must satisfy $min(a_{l-... | [
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy",
"two pointers"
] | 2,800 | // #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include "bits/stdc++.h"
using namespace std;
using ll = long long int;
mt19937_64 RNG(chrono::high_resolution_clock::now().time_since_epoch().count());
/**
* Point-update Segment Tree
* Source: kactl
* Description: Itera... |
1991 | A | Maximize the Last Element | You are given an array $a$ of $n$ integers, where $n$ is \textbf{odd}.
In one operation, you will remove two \textbf{adjacent} elements from the array $a$, and then concatenate the remaining parts of the array. For example, given the array $[4,7,4,2,9]$, we can obtain the arrays $[4,2,9]$ and $[4,7,9]$ by the operatio... | Consider the parity of the position. The answer is the maximum value of the elements at odd indices. Proof Any element at an odd index can be preserved until the end. Since each element at an odd index has an even number of elements on both sides, pairs of adjacent elements can be removed from left to right until only ... | [
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 105;
int t, n, a[MAX_N];
int main() {
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
int max_value = 0;
for (int i = 1; i <= n; i += 2)
max_value = max(max_value, ... |
1991 | B | AND Reconstruction | You are given an array $b$ of $n - 1$ integers.
An array $a$ of $n$ integers is called good if $b_i = a_i \, \& \, a_{i + 1}$ for $1 \le i \le n-1$, where $\&$ denotes the bitwise AND operator.
Construct a good array, or report that no good arrays exist. | Consider $b_{i - 1} | b_i$. Let's construct an array $a$ using the formula $a_i = b_{i - 1} | b_i$ (assuming $b_0$ and $b_n$ are $0$). We then verify the condition $b_i = a_i \& a_{i + 1}$ for $1 \le i < n$. If any condition fails, then such an array $a$ does not exist. Explanation Using the above construction method, ... | [
"bitmasks",
"constructive algorithms",
"greedy"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
int n, b[MAX_N], a[MAX_N];
void solve() {
cin >> n;
for (int i = 1; i < n; i++)
cin >> b[i];
b[0] = b[n] = 0;
for (int i = 1; i <= n; i++)
a[i] = b[i - 1] | b[i];
bool valid = true;
for (int i = 1; i < n; i+... |
1991 | C | Absolute Zero | You are given an array $a$ of $n$ integers.
In one operation, you will perform the following two-step move:
- Choose an integer $x$ ($0 \le x \le 10^{9}$).
- Replace each $a_i$ with $|a_i - x|$, where $|v|$ denotes the absolute value of $v$.
For example, by choosing $x = 8$, the array $[5, 7, 10]$ will be changed in... | If the array contains both odd and even elements, it is impossible to zero the array. Is there a method to narrow the range of elements after every operation? If the array contains both odd and even numbers, it is impossible to zero the array. This is because any operation will maintain the presence of both odd and eve... | [
"constructive algorithms",
"greedy",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 5;
int n, a[MAX_N];
void solve() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
bool has_odd = false, has_even = false;
for (int i = 1; i <= n; i++)
if (a[i] % 2 == 1)
has_odd = true;
else
... |
1991 | D | Prime XOR Coloring | You are given an undirected graph with $n$ vertices, numbered from $1$ to $n$. There is an edge between vertices $u$ and $v$ if and only if $u \oplus v$ is a prime number, where $\oplus$ denotes the bitwise XOR operator.
Color all vertices of the graph using the minimum number of colors, such that no two vertices dire... | We can use only $4$ colors for all $n$. For $n \ge 6$, the minimum number of colors is always $4$. Proof First, we can show that the number of colors cannot be less than $4$. This is because vertices $1$, $3$, $4$, and $6$ form a clique, meaning they are all connected, so they must have different colors. Next, we can p... | [
"bitmasks",
"constructive algorithms",
"graphs",
"greedy",
"math",
"number theory"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
if (n < 6) {
if (n == 1)
cout << 1 << '\n' << "1" << '\n';
else if (n == 2)
cout << 2 << '\n' << "1 2" << '\n';
else if (n == 3)
cout << 2 << '\n' << "1 2 2" << '\n';
... |
1991 | E | Coloring Game | This is an interactive problem.
Consider an undirected connected graph consisting of $n$ vertices and $m$ edges. Each vertex can be colored with one of three colors: $1$, $2$, or $3$. Initially, all vertices are uncolored.
Alice and Bob are playing a game consisting of $n$ rounds. In each round, the following two-ste... | Determine if the graph is bipartite. If the graph is not bipartite, Alice will win. If the graph is bipartite, Bob will win. If the graph is not bipartite, Alice can always choose colors $1$ and $2$. According to the definition of a non-bipartite graph, Bob cannot color the graph with two colors without having two adja... | [
"constructive algorithms",
"dfs and similar",
"games",
"graphs",
"greedy",
"interactive"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e4 + 5;
int n, m, color[MAX_N], isBipartite;
vector<int> graph[MAX_N];
void dfs(int vertex) {
for (auto neighbor: graph[vertex])
if (!color[neighbor]) {
color[neighbor] = 3 — color[vertex];
dfs(neighbor);
} else... |
1991 | F | Triangle Formation | You are given $n$ sticks, numbered from $1$ to $n$. The length of the $i$-th stick is $a_i$.
You need to answer $q$ queries. In each query, you are given two integers $l$ and $r$ ($1 \le l < r \le n$, $r - l + 1 \ge 6$). Determine whether it is possible to choose $6$ \textbf{distinct} sticks from the sticks numbered $... | Under the constraints of the problem, there exists a (small) integer $C$ such that for intervals longer than $C$, it is guaranteed to form two triangles. If there are at least $45$ sticks, it is guaranteed to form a triangle. Proof: For any sequence of stick lengths that cannot form a triangle, we can replace it with t... | [
"brute force",
"greedy",
"implementation",
"math",
"sortings"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
int n, q, a[MAX_N], p[MAX_N];
bool canFormTwoTriangles(int l, int r) {
int t = 0;
for (int i = l; i <= r; i++)
p[++t] = a[i];
sort(p + 1, p + t + 1);
for (int i = 1; i <= t - 5; i++)
for (int j = i + 1; j <= i + 5; ... |
1991 | G | Grid Reset | You are given a grid consisting of $n$ rows and $m$ columns, where each cell is initially white. Additionally, you are given an integer $k$, where $1 \le k \le \min(n, m)$.
You will process $q$ operations of two types:
- $\mathtt{H}$ (horizontal operation) — You choose a $1 \times k$ rectangle completely within the g... | Perform horizontal operations only on the leftmost $k$ columns and vertical operations only on the topmost $k$ rows. Prioritize operations that will lead to a reset. Here is a strategy to ensure you can perform operations infinitely: Perform horizontal operations only on the leftmost $k$ columns and vertical operations... | [
"constructive algorithms",
"greedy",
"implementation"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
const int MAX_SIZE = 105;
char operationType;
int n, m, k, q, grid[MAX_SIZE][MAX_SIZE];
string s;
int calculateSum(int x1, int y1, int x2, int y2) {
int sum = 0;
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
sum += grid[i][j];
... |
1991 | H | Prime Split Game | Alice and Bob are playing a game with $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Players take turns making moves, with Alice going first.
On each move, the player does the following three-step process:
- Choose an integer $k$ ($1 \leq k \leq \frac n 2$). Note that the value of $k$ can be different f... | Consider which pairs of numbers an odd number can be split into. What about an even number? Consider a simplified version of the game with only two piles of stones, where the first pile contains $x$ stones, and the second pile contains one stone. Determine all winning positions for this game configuration. For the simp... | [
"bitmasks",
"dp",
"fft",
"games",
"math",
"number theory"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 5;
bitset<MAX_N + 1> isComposite, isWinning, isPrimeLosing, isPrimeWinning, isGoodPosition;
void initialize() {
isComposite[1] = true;
for (int i = 2; i <= MAX_N; i++)
for (int j = 2 * i; j <= MAX_N; j += i)
isComposite[j]... |
1991 | I | Grid Game | This is an interactive problem.
You are given a grid with $n$ rows and $m$ columns. You need to fill each cell with a unique integer from $1$ to $n \cdot m$.
After filling the grid, you will play a game on this grid against the interactor. Players take turns selecting one of the previously unselected cells from the g... | Notice that if the problem requires our selected numbers' sum to be greater than the interactor's sum, instead of smaller, the essence of the problem changes. Depending on whether $n \cdot m$ is odd or even, we can use different methods to fill the grid and adapt our game strategy. When $n \cdot m$ is odd, we can adopt... | [
"constructive algorithms",
"games",
"graph matchings",
"greedy",
"interactive"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 15, dx[] = {-1, 0, 0, 1}, dy[] = {0, -1, 1, 0};
int n, m, x, y, grid[MAX_N][MAX_N], color[MAX_N][MAX_N], visited[MAX_N][MAX_N], currentValue, currentColor, flipCoords;
bool isAdjacent(int x, int y) {
int nx, ny;
for (int i = 0; i < 4; i++) {
... |
1992 | A | Only Pluses | Kmes has written three integers $a$, $b$ and $c$ in order to remember that he has to give Noobish_Monk $a \times b \times c$ bananas.
Noobish_Monk has found these integers and decided to do the following \textbf{at most $5$ times}:
- pick one of these integers;
- increase it by $1$.
For example, if $a = 2$, $b = 3$ ... | Let's prove why it's always better to add to the smallest number, let $a \le b \le c$, then compare the three expressions: $(a+1)\times b \times c$, $a \times (b+1) \times c$, and $a \times b \times (c+1)$. Remove the common part $a \times b \times c$, and we get: $b \times c$, $a \times c$, $a \times b$. $b \times c \... | [
"brute force",
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 800 | for _ in range(int(input())):
arr = sorted(list(map(int,input().split())))
for i in range(5):
arr[0]+=1
arr.sort()
print(arr[0] * arr[1] * arr[2]) |
1992 | B | Angry Monk | To celebrate his recovery, k1o0n has baked an enormous $n$ metres long potato casserole.
Turns out, Noobish_Monk just can't stand potatoes, so he decided to ruin k1o0n's meal. He has cut it into $k$ pieces, of lengths $a_1, a_2, \dots, a_k$ meters.
k1o0n wasn't keen on that. Luckily, everything can be fixed. In order... | Let's say we want to connect two casseroles with lengths $x$ and $y$. We can disassemble one of them into pieces of length $1$ and then attach them to the casserole of size $y$. In total, we will perform $2x - 1$ operations. Since we want to connect $k$ pieces, at least $k - 1$ of them will have to be disassembled and ... | [
"greedy",
"math",
"sortings"
] | 800 | for _ in range(int(input())):
n,k = map(int,input().split())
mx = max(map(int, input().split()))
print((n - mx) * 2 - (k - 1)) |
1992 | C | Gorilla and Permutation | Gorilla and Noobish_Monk found three numbers $n$, $m$, and $k$ ($m < k$). They decided to construct a permutation$^{\dagger}$ of length $n$.
For the permutation, Noobish_Monk came up with the following function: $g(i)$ is the sum of all the numbers in the permutation on a prefix of length $i$ that are not greater than... | Let $p$ be some permutation. Let's look at the contribution of the number $p_i$ to the sum $\sum_{i=1}^n {f(i)}$. If it is less than $k$, the contribution is $0$, otherwise the contribution is $p_i \cdot (n - i + 1)$. Similarly, let's look at the contribution of $p_i$ to the sum $\sum_{i=1}^n {g(i)}$. If it is greater ... | [
"constructive algorithms",
"math"
] | 900 | for _ in range(int(input()):
n,m,k = map(int,input().split())
print(*range(n,m,-1), *range(1,m)) |
1992 | D | Test of Love | ErnKor is ready to do anything for Julen, even to swim through crocodile-infested swamps. We decided to test this love. ErnKor will have to swim across a river with a width of $1$ meter and a length of $n$ meters.
The river is very cold. Therefore, \textbf{in total} (that is, throughout the entire swim from $0$ to $n+... | In this problem, there are two main solutions: dynamic programming and greedy algorithm. Dynamic programming solution: $dp_i$ $-$ the minimum number of meters that need to be swum to reach the $i$-th cell. The base case of the dynamic programming is $dp_0 = 0$. Then, the update rule is: $\begin{equation*} dp_i = \text{... | [
"dp",
"greedy",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m, k;
cin >> n >> m >> k;
string s;
cin >> s;
vector<int> dp(n + 2, -1);
dp[0] = k;
for (int i = 1; i <= n + 1; i++) {
if (i != n + 1 && s[i -... |
1992 | E | Novice's Mistake | One of the first programming problems by K1o0n looked like this: "Noobish_Monk has $n$ $(1 \le n \le 100)$ friends. Each of them gave him $a$ $(1 \le a \le 10000)$ apples for his birthday. Delighted with such a gift, Noobish_Monk returned $b$ $(1 \le b \le \min(10000, a \cdot n))$ apples to his friends. How many apples... | Notice that $n * a - b$ is strictly less than $10^6$, i.e., it has no more than $6$ digits. The number of characters in the strange calculation $n * a - b$ is equal to $|n| * a - b$, where $|n|$ is the number of digits in n. Let's iterate over the value of $a$, and then determine the boundaries $minB$ and $maxB$ for it... | [
"brute force",
"constructive algorithms",
"implementation",
"math",
"strings"
] | 1,700 | for _ in range(int(input())):
n = int(input())
sn = str(n)
lenN = len(str(n))
ans = []
for a in range(1, 10001):
minB = max(1, lenN * a - 5)
maxB = lenN * a
for b in range(minB, maxB):
x = n * a - b
y = 0
for i in range(lenN * a - b):
... |
1992 | F | Valuable Cards | In his favorite cafe Kmes once again wanted to try the herring under a fur coat. Previously, it would not have been difficult for him to do this, but the cafe recently introduced a new purchasing policy.
Now, in order to make a purchase, Kmes needs to solve the following problem: $n$ cards with prices for different po... | Let's consider the greedy algorithm ``take as long as you can''. Let's prove that it works. In any optimal division, if we take the first segment of non-maximum length, we will not violate the criteria if we transfer one element from the second segment to the first. Therefore, the given greedy algorithm is correct. Now... | [
"brute force",
"dp",
"greedy",
"number theory",
"two pointers"
] | 1,900 | #include <iostream>
#include <vector>
using namespace std;
const int A = 1e6 + 1;
bool used[A];
bool divs[A];
void solve() {
int n, x;
cin >> n >> x;
vector<int> a(n);
vector<int> vecDivs;
for (int d = 1; d * d <= x; d++) {
if (x % d == 0) {
divs[d] = true;
vecDivs.push_back(d);
if (d * d < x) {
... |
1992 | G | Ultra-Meow | K1o0n gave you an array $a$ of length $n$, consisting of numbers $1, 2, \ldots, n$. Accept it? Of course! But what to do with it? Of course, calculate $\text{MEOW}(a)$.
Let $\text{MEX}(S, k)$ be the $k$-th \textbf{positive} (strictly greater than zero) integer in ascending order that is not present in the set $S$. Den... | We will iterate over the size of the set $k$ and its $\text{MEOW}$, $m$. If $2k \geqslant n$, then the set $x$ will fill all the remaining numbers up to $n$, and there may still be some larger than $n$ in it, so the $MEOW$ of all such sets will be $2k+1$, and there will be a total of $C(n, k)$ such sets for each $k$. I... | [
"combinatorics",
"dp",
"math"
] | 2,000 | #include <iostream>
using namespace std;
const int mod = 1e9 + 7;
int add(int a, int b) {
if (a + b >= mod)
return a + b - mod;
return a + b;
}
int sub(int a, int b) {
if (a < b)
return a + mod - b;
return a - b;
}
int mul(int a, int b) {
return (int)((1ll * a * b) % mod);
}
in... |
1993 | A | Question Marks | Tim is doing a test consisting of $4n$ questions; each question has $4$ options: 'A', 'B', 'C', and 'D'. For each option, there are exactly $n$ correct answers corresponding to that option — meaning there are $n$ questions with the answer 'A', $n$ questions with the answer 'B', $n$ questions with the answer 'C', and $n... | What is the pattern of Tim's answer sheet that can give him maximum score? Let's say there are $n$ problems take $A$ as the answer, therefore he can only get $n$ points with the answer $A$. The same is correct for $B$, $C$ and $D$. Therefore, the maximum score can be achieved is $min(n, A) + min(n, B) + min(n, C) + min... | [
"greedy",
"implementation"
] | 800 | t = int(input())
for _ in range(t):
n = int(input())
s = input()
print(sum(min(n, s.count(c)) for c in "ABCD")) |
1993 | B | Parity and Sum | Given an array $a$ of $n$ positive integers.
In one operation, you can pick any pair of indexes $(i, j)$ such that $a_i$ and $a_j$ have \textbf{distinct} parity, then replace the smaller one with the sum of them. More formally:
- If $a_i < a_j$, replace $a_i$ with $a_i + a_j$;
- Otherwise, replace $a_j$ with $a_i + a... | Find a way to make all the elements even. Then odd. In the worst case, the number of operations required is the number of even elements + 1. Why? First, if all elements already have the same parity, we don't need to do perform any operation. Next, if the array contains both $even$ and $odd$ numbers. In this case, it is... | [
"constructive algorithms",
"greedy"
] | 1,100 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
s = -1
v = []
for x in a:
if x%2 == 0:
v.append(x)
elif x > s:
s = x
v.sort()
if s == -1 or v == []:
print(0)
continue
ans = len(v)
... |
1993 | C | Light Switches | There is an apartment consisting of $n$ rooms, each with its light \textbf{initially turned off}.
To control the lights in these rooms, the owner of the apartment decided to install chips in the rooms so that each room has exactly one chip, and the chips are installed at different times. Specifically, these times are ... | Try to find the segments of moments when a light is on. Select this segment from each light. The answer should be the intersection of all of them. As soon as a chip is installed, it changes the light's status every $k$ minutes. Let's first list the segments of the moments when a light is on if we install a chip at mome... | [
"implementation",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, k, d[2*N];
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
cin >> n >> k;
int mx = -1;
fill(d, d + 2*k, 0);
for (int i = 0; i < n; i++) {
... |
1993 | D | Med-imize | Given two positive integers $n$ and $k$, and another array $a$ of $n$ integers.
In one operation, you can select any subarray of size $k$ of $a$, then remove it from the array without changing the order of other elements. More formally, let $(l, r)$ be an operation on subarray $a_l, a_{l+1}, \ldots, a_r$ such that $r-... | Is there any method to calculate median without sorting? Is there any relationship between the original array with the final array? Note: in order to explain this solution easier, we'll suppose all arrays are 0-indexed. If $n \le k$, we don't have to remove any segment since the statement only tell us to do it while th... | [
"binary search",
"dp",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n, k, a[N];
int dp[N], b[N];
bool check(int med) {
for (int i = 0; i < n; i++) {
if (a[i] >= med) {
b[i] = 1;
} else {
b[i] = -1;
}
}
dp[0] = b[0];
for (int i = 1; i < n; i++) {
... |
1993 | E | Xor-Grid Problem | Given a matrix $a$ of size $n \times m$, each cell of which contains a non-negative integer. The integer lying at the intersection of the $i$-th row and the $j$-th column of the matrix is called $a_{i,j}$.
Let's define $f(i)$ and $g(j)$ as the XOR of all integers in the $i$-th row and the $j$-th column, respectively. ... | Try applying an operation on the same row twice. Does it change the matrix significantly? Now apply operations on two different rows. Does the second row (that the operation is applied) look familiar? First, let's extend the original matrix by one unit in rows and columns (which means there's an additional $(n+1)$-th r... | [
"bitmasks",
"constructive algorithms",
"dp",
"implementation"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
const int N = 16;
int n, m;
int a[N][N];
int fr[N][N], fc[N][N];
int w[N][N], dp[N][1<<N];
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 0; i <= n; i++) a[i][m] = 0;
... |
1993 | F1 | Dyn-scripted Robot (Easy Version) | \textbf{This is the easy version of the problem. The only difference is that in this version $k \le n$. You can make hacks only if both versions of the problem are solved.}
Given a $w \times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle.
You al... | Let the robot moves freely (no modification on the script). The new path of the robot is the "mirrored" version of how the robot must go. Imagine we have two robots, let's call them Alex and Bob. Alex is the one who follows the instruction well, but Bob doesn't (if he tries to move outside the box, he keeps going witho... | [
"brute force",
"chinese remainder theorem",
"constructive algorithms",
"math",
"number theory"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e6 + 5;
string s;
ll n, k, w, h;
ll tx[2*N], ty[2*N];
map<pair<ll, ll>, ll> cnt;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
cin >> n >> k >> w >> h >> s;
cnt... |
1993 | F2 | Dyn-scripted Robot (Hard Version) | \textbf{This is the hard version of the problem. The only difference is that in this version $k \le 10^{12}$. You can make hacks only if both versions of the problem are solved.}
Given a $w \times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle.
... | The idea of this version is almost the same as F1: counting the number of pairs $(i, j)$ that satisfies: $ix_n + x_j\equiv 0\pmod{2W}$, and $iy_n + y_j\equiv 0\pmod{2H}$ However, as $k$ is increased to $10^{12}$ we cannot brute-force the same way as the previous version. Luckily, there is a more efficient way. We need ... | [
"chinese remainder theorem",
"math",
"number theory"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
namespace CRT {
// v * inv(v, M) = 1 (mod M)
ll inv(ll v, ll M) {
ll a = 1, b = 0;
for (ll x = v, y = M; x != 0; ) {
swap(a, b -= y/x * a);
swap(x, y -= y/x * x);
}
return b + (b<0)... |
1994 | A | Diverse Game | Petr, watching Sergey's stream, came up with a matrix $a$, consisting of $n$ rows and $m$ columns (the number in the $i$-th row and $j$-th column is denoted as $a_{i, j}$), which contains all integers from $1$ to $n \cdot m$. But he didn't like the arrangement of the numbers, and now he wants to come up with a new matr... | If $n = m = 1$, then there is only one possible matrix, so the answer is $-1$. Otherwise, at least one of the numbers $n, m$ is greater than $1$, then one of the solutions is, for example, a matrix $a$ with cyclically shifted rows (if $m > 1$) or columns (if $n > 1$). | [
"constructive algorithms",
"greedy",
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int tests;
cin >> tests;
while (tests--) {
int n, m;
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m));
for (auto &i: a) {
for (auto &j: i) cin >> j;
... |
1994 | B | Fun Game | Vova really loves the XOR operation (denoted as $\oplus$). Recently, when he was going to sleep, he came up with a fun game.
At the beginning of the game, Vova chooses two binary sequences $s$ and $t$ of length $n$ and gives them to Vanya. A binary sequence is a sequence consisting only of the numbers $0$ and $1$. Van... | If the string $s$ consists entirely of $0$, then obviously no other string can be obtained from it, so the answer is "Yes" only if $s = t$. Otherwise, let $i$ - the index of the first $1$ in $s$. Note that if there is at least one $1$ in $t$ at positions $[1; i)$, then the answer is "No", since $s$ has $0$ at these pos... | [
"bitmasks",
"constructive algorithms",
"greedy",
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
string s, t;
cin >> s >> t;
for (int i = 0; i < s.size() && s[i] == '0'; ++i) {
if (t[i] != '0') {
cout << "NO\n";
return;
}
}
cout << "YES\n";
}
int main() {
int t;
... |
1994 | C | Hungry Games | Yaroslav is playing a computer game, and at one of the levels, he encountered $n$ mushrooms arranged in a row. Each mushroom has its own level of toxicity; the $i$-th mushroom from the beginning has a toxicity level of $a_i$. Yaroslav can choose two integers $1 \le l \le r \le n$, and then his character will take turns... | We'll solve the problem by dynamic programming. Let $dp[i]$ - the number of good subsegments with left boundary at $i$. We will count $dp$ from the end, for each $i$ we will find such a minimum $j$ that the sum on the subsegment $[i; j]$ is greater than $x$. If there is no such $j$, then all right bounds are good, othe... | [
"binary search",
"dp",
"two pointers"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int tests;
cin >> tests;
while (tests--) {
int n;
ll x;
cin >> n >> x;
vector<ll> a(n + 1);
for (int i = 1; i <= n; ++i) cin >> a[i];
... |
1994 | D | Funny Game | Vanya has a graph with $n$ vertices (numbered from $1$ to $n$) and an array $a$ of $n$ integers; initially, there are no edges in the graph. Vanya got bored, and to have fun, he decided to perform $n - 1$ operations.
Operation number $x$ (operations are numbered in order starting from $1$) is as follows:
- Choose $2$... | Note that we have only $n - 1$ edges, so after each operation, the number of connectivity components must decrease by $1$. Since the order of operations is not important, we will perform the operations in reverse order. Then after the operation with number $x$, there will be $x + 1$ connectivity components in the graph... | [
"constructive algorithms",
"dsu",
"graphs",
"greedy",
"math",
"number theory",
"trees"
] | 1,900 | #include<bits/stdc++.h>
using namespace std;
int main() {
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
vector<int> a(n);
for (auto& i : a) cin >> i;
vector<int> pos(n);
iota(pos.begin(), pos.end(), 0);
vector<pair<int, int>> ans;
... |
1994 | E | Wooden Game | You are given a forest of $k$ rooted trees$^{\text{∗}}$. Lumberjack Timofey wants to cut down the entire forest by applying the following operation:
- Select a subtree$^{\text{†}}$ of any vertex of one of the trees and remove it from the tree.
Timofey loves bitwise operations, so he wants the bitwise OR of the sizes ... | We know that the maximal result from one tree is the size of this tree (see hints), but we can make every number from $1$ to the size of the tree. To do that, we can delete leaves until we have the needed value. So the remaining problem is to find the maximal OR if we can choose numbers from $1$ to $a_i$. For every bit... | [
"bitmasks",
"greedy",
"math",
"trees"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
void solve() {
int k;
cin >> k;
vector<int> a(k);
for (int i = 0; i < k; ++i) {
cin >> a[i];
for (int j = 0; j < a[i] - 1; ++j) {
int trash;
cin >> trash;
}
}
sort(a.begin(), a.end(), greater<>());
... |
1994 | F | Stardew Valley | Pelican Town represents $n$ houses connected by $m$ bidirectional roads. Some roads have NPCs standing on them. Farmer Buba needs to walk on each road with an NPC and talk to them.
Help the farmer find a route satisfying the following properties:
- The route starts at some house, follows the roads, and ends at the sa... | The edges with $0$ on them will be called black, the other edges will be called white. To find such a route, we need the graph to be Eulerian (degree of each vertex is even). To achieve this, we can remove some black edges. Let's calculate the degree of each vertex (further we will keep this degree in mind) and leave o... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"trees"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int tests;
cin >> tests;
while (tests--) {
int n, m;
cin >> n >> m;
vector<vector<int>> black(n);
vector<int> edg(m);
vector<vector<int>> g(n);
for (int i... |
1994 | G | Minecraft | After winning another Bed Wars game, Masha and Olya wanted to relax and decided to play a new game. Masha gives Olya an array $a$ of length $n$ and a number $s$. Now Olya's task is to find a non-negative number $x$ such that $\displaystyle\sum_{i=1}^{n} a_i \oplus x = s$. But she is very tired after a tight round, so p... | We will do recursion. Let's go from the lower bits to the significant bits. $rec(i, sum)$ means that the first $i$ bits are selected, the sum of them divided by $2^i$ equals $sum$, and the first $i$ bits match the ones we need. Let $cnt_i$ - the number of ones in the numbers in the $i$-th bit. Then we can go from state... | [
"bitmasks",
"brute force",
"dp",
"graphs",
"math"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
int n, k;
vector<vector<bool>> memo;
string res;
vector<int> cnt;
string s;
bool rec(int i, int cur) {
if (i == k) {
if (cur == 0) {
return true;
}
return false;
}
if (memo[i][cur]) return false;
memo[i][cur] = true;
... |
1994 | H | Fortnite | \textbf{This is an interactive problem!}
Timofey is writing a competition called Capture the Flag (or CTF for short). He has one task left, which involves hacking a security system. The entire system is based on polynomial hashes$^{\text{∗}}$.
Timofey can input a string consisting of lowercase Latin letters into the ... | The first query is $aa$, it can be used to find out $p$. The second query is $zzzzzzzzzz$, let's calculate its hash without modulus, denote h_1, hash with modulus denote a1. Suppose we get a string with hash without modulus from $h_1 - a_1 - m$ to $h_1 - a_1 - 1$, then if we query it, we can easily find out the modulus... | [
"combinatorics",
"constructive algorithms",
"games",
"greedy",
"hashing",
"interactive",
"math",
"number theory",
"strings"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
cout << "? aa" << endl;
int p, v[10];
cin >> p; p--;
cout << "? zzzzzzzzzz" << endl;
int hsh, hsho;
ll nom = 0, cnt = 1;
cin >> hsh;
hsho = hsh;
hsh++;
for (int i = 0; i < 10; i++) {
nom ... |
1995 | A | Diagonals | Vitaly503 is given a checkered board with a side of $n$ and $k$ chips. He realized that all these $k$ chips need to be placed on the cells of the board (no more than one chip can be placed on a single cell).
Let's denote the cell in the $i$-th row and $j$-th column as $(i ,j)$. A diagonal is the set of cells for which... | How many described diagonals are there in total? How many cells do they contain? In total we have $2 n - 1$ diagonals. There is only one diagonal that contains $n$ cells, two containing $n - 1$ cells, ..., and two containing only one cell each (namely passing through $(1, n)$ and $(n, 1)$). Obviously, in this case, it ... | [
"brute force",
"greedy",
"implementation",
"math"
] | 800 | def solver():
n, k = map(int, input().split())
a, b = n, n - 1
ans = 0
while k > 0:
k -= a
ans += 1
a, b = b, (b if a != b else b - 1)
print(ans)
t = int(input())
for _ in range(t):
solver() |
1995 | B1 | Bouquet (Easy Version) | \textbf{This is the easy version of the problem. The only difference is that in this version, the flowers are specified by enumeration.}
A girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ flowers in the store, each of which is characterized by the number of petal... | For each number of petals, we can bruteforce the answer for $x, x + 1$ First, we can aggregate number of flowers with $x$ petals into $c_{x}$ (for example, sort the array and then create array of pairs $(x, c_{x})$, where $c_{x}$ is the length of segment with elements equal to $x$). Note that $\sum_{x} c_{x} = n$. Also... | [
"binary search",
"brute force",
"greedy",
"sortings",
"two pointers"
] | 1,100 | tests = int(input())
p = 10 ** 9 + 7
def pow(x, q):
if q == 0:
return 1
i = pow(x, q // 2)
if q % 2 == 0:
return (i * i) % p
return (i * i * x) % p
def solve():
global p
n, m = map(int, input().split(" "))
a = list(map(int, input().split(" ")))
hs = {}
for x i... |
1995 | B2 | Bouquet (Hard Version) | \textbf{This is the hard version of the problem. The only difference is that in this version, instead of listing the number of petals for each flower, the number of petals and the quantity of flowers in the store is set for all types of flowers.}
A girl is preparing for her birthday and wants to buy the most beautiful... | Maybe there is a way to change bruteforce into checking optimal values for counts of $x, x + 1$? Maybe there are only few types of optimal bouquets for $x, x + 1$? We already have a list of $c_x$. We can use hash map to be able to check for any $c_x$ by $x$. We again will try to assemble the bouquet only with flowers w... | [
"binary search",
"data structures",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,700 | def solve():
n, m = map(int, input().split(" "))
a = list(map(int, input().split(" ")))
c = list(map(int, input().split(" ")))
ch = {}
ans = 0
for a1, c1 in zip(a, c):
if a1 not in ch:
ch[a1] = 0
ch[a1] += c1
for x, c_x in ch.items():
ans = max(ans, min(m ... |
1995 | C | Squaring | ikrpprpp found an array $a$ consisting of integers. He likes justice, so he wants to make $a$ fair — that is, make it non-decreasing. To do that, he can perform an act of justice on an index $1 \le i \le n$ of the array, which will replace $a_i$ with $a_i ^ 2$ (the element at position $i$ with its square). For example,... | How many times we need to apply the operation to index $i$, so that $a[i - 1] \leq a[i]$? Let's call it $op[i]$ It's easy to calculate these values in no time. Can we just accumulate them? We almost can. But, let's take $[4, 2, 4]$ as an example. op[2] = 1, but we don't want to do anything with a[3]. So, sometimes $a[i... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
const long long kk = 1000;
const long long ml = kk * kk;
const long long mod = ml * kk + 7;
const long long inf = ml * ml... |
1995 | D | Cases | You're a linguist studying a mysterious ancient language. You know that
- Its words consist only of the first $c$ letters of the Latin alphabet.
- Each word has a case which can be unambiguously determined by its last letter (different letters correspond to different cases). For example, words "ABACABA" and "ABA" (if ... | If letter is chosen as an ending to some case, each occurrence of this letter may in the text can be considered an ending? The length of the word is something too complex. How can you simplify the restriction? The final letter must be an ending of some case and among any $k$ consecutive letters there must be at least o... | [
"bitmasks",
"brute force",
"dp",
"strings"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, c, k;
cin >> n >> c >> k;
string s;
cin >> s;
vector<vector<int>> cumsums(c, vector<int>(n + 1));
for (int i = 0; i < c; ++i)
for (int j = 0; j < n; ++j)
cumsums[i][j + 1] = cumsums[i][j] + (s[j] ==... |
1995 | E1 | Let Me Teach You a Lesson (Easy Version) | \textbf{This is the easy version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}
Arthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in p... | Consider cases of odd and even $n$. Which one is simpler? Even. In this case you can solve the problem for the opposite desks independently. From now on $n$ is odd. Let a desk have knights with intelligence $a$, $b$ and the opposite one with $c$, $d$. Since $(a + b) + (c + d) = (a + c) + (b + d)$, the minimal total int... | [
"2-sat",
"data structures",
"dp",
"matrices",
"two pointers"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
constexpr int VB = 2'000'000'001;
void solve() {
#define M(x) (((x) + 2 * n) % (2 * n))
int n;
cin >> n;
vector<int> v(2 * n);
for (auto &e: v) {
cin >> e;
}
if (n % 2 == 0) {
int ma = 0;
int mi = VB;
for (... |
1995 | E2 | Let Me Teach You a Lesson (Hard Version) | \textbf{This is the hard version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}
Arthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in p... | Read the first two hints to E1. There are $4 n$ possible desks in total. One of them will be the minimal desk and another one will be the maximal. What is the common-used technique for such problems? Sort them and then use two pointers. The data structure you need is very famous. (Read the hints.) Assign a boolean matr... | [
"data structures",
"dp",
"matrices",
"two pointers"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
struct desk {
bool t[2][2]{};
desk() = default;
desk(bool t11, bool t01, bool t10, bool t00) : t{{t00, t01}, {t10, t11}} {
}
};
desk operator*(const desk &a, const desk &b) {
desk c {a.t[1][1] && b.t[1][1] || a.t[1][0] && b.t[0][1],
a... |
1996 | A | Legs | It's another beautiful day on Farmer John's farm.
After Farmer John arrived at his farm, he counted $n$ legs. It is known only chickens and cows live on the farm, and a chicken has $2$ legs while a cow has $4$.
What is the minimum number of animals Farmer John can have on his farm assuming he counted the legs of all ... | If $n$ is a multiple of $4$, then you can have $\frac{n}{4}$ cows. Otherwise, you must have at least one chicken, so you can have $\frac{n-2}{4}$ cows and $1$ chicken. | [
"binary search",
"math",
"ternary search"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tc;
cin >> tc;
while (tc--){
int n;
cin >> n;
cout << (n + 2) / 4 << "\n";
}
} |
1996 | B | Scale | Tina has a square grid with $n$ rows and $n$ columns. Each cell in the grid is either $0$ or $1$.
Tina wants to reduce the grid by a factor of $k$ (\textbf{$k$ is a \underline{divisor} of $n$}). To do this, Tina splits the grid into $k \times k$ nonoverlapping blocks of cells such that every cell belongs to exactly on... | Let's define every $k$ by $k$ block of cells by its value in the top left corner, since all cells in the block must have the same value. So, we can just print out the value of the cell in every $k$'th row and every $k$'th column. | [
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tc;
cin >> tc;
while (tc--){
int n, k;
cin >> n >> k;
char A[n][n];
for (auto &row : A)
for (char &c : row)
cin >> c;
... |
1996 | C | Sort | You are given two strings $a$ and $b$ of length $n$. Then, you are (forced against your will) to answer $q$ queries.
For each query, you are given a range bounded by $l$ and $r$. In one operation, you can choose an integer $i$ ($l \leq i \leq r$) and set $a_i = x$ where $x$ is any character you desire. Output the mini... | For two strings to be the same after sorting, they must have the same occurrences of every possible lowercase letter. To answer the query for a range $[l, r]$, we must ensure that after the operations, $cnt_c = cnt2_c$ must where $cnt_c$ is the number of times character $c$ occurs in the range for $a$ and $cnt2_c$ is d... | [
"dp",
"greedy",
"sortings",
"strings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n, q;
cin >> n >> q;
vector<vector<int>> pre1(n + 1, vector<int>(26, 0));
vector<vector<int>> pre2(n + 1, vector<int>(26, 0));
for (int i = 1; i <= n; i++){
char c;
cin >> c;
pre1[i][c - 'a']++;
for ... |
1996 | D | Fun | \begin{quote}
Counting is Fun!
\hfill — satyam343
\end{quote}
Given two integers $n$ and $x$, find the number of triplets ($a,b,c$) of \textbf{positive integers} such that $ab + ac + bc \le n$ and $a + b + c \le x$.
Note that order matters (e.g. ($1, 1, 2$) and ($1, 2, 1$) are treated as different) and $a$, $b$, $c$ ... | There are several solutions to this problem, The easiest way is to just fix either $a$, $b$ or $c$. Let's fix $a$. Since $ab + ac + bc \leq n$, we know at the minimum, $ab \leq n$. Divide on both sides to get $b \leq \frac{n}{a}$. When $a = 1$, there are $n$ choices for $b$. When $a = 2$, there are $\frac{n}{2}$ choice... | [
"binary search",
"brute force",
"combinatorics",
"math",
"number theory"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main(){
int tc;
cin >> tc;
while (tc--){
int n, x;
cin >> n >> x;
long long ans = 0;
for (int a = 1; a <= min(n, x); a++){
for (int b = 1; a * b <= n and a + b <= x; b++){
int highestC =... |
1996 | E | Decode | {In a desperate attempt to obtain your \sout{waifu} favorite character, you have hacked into the source code of the game. After days of struggling, you finally find the binary string that encodes the gacha system of the game. In order to decode it, you must first solve the following problem.}
You are given a binary st... | How can we efficiently check if a range contains the same amount of zeroes and ones? Let's create an array $a$ where $a_i = -1$ if $s_i = 0$ and $a_i = 1$ if $s_i = 1$. Let's denote $p$ as the prefix sum array of $a$. We want the contribution of $-1$ by the zeroes to cancel out with the ones, so if $p_r - p_{l-1} = 0$,... | [
"combinatorics",
"data structures",
"implementation",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
const int MOD = 1e9 + 7;
void solve(){
string S;
cin >> S;
int n = S.size();
S = " " + S;
vector<int> P(n + 1, 0);
for (int i = 1; i <= n; i++){
P[i] = (S[i] == '1' ? 1 : -1) + P[i - 1];
}
map<int, ll> cnt... |
1996 | F | Bomb | Sparkle gives you two arrays $a$ and $b$ of length $n$. Initially, your score is $0$. In one operation, you can choose an integer $i$ and add $a_i$ to your score. Then, you must set $a_i$ = $\max(0, a_i - b_i)$.
You only have time to perform $k$ operations before Sparkle sets off a nuclear bomb! What is the maximum sc... | Let's first solve the problem in $\mathcal{O}(k)$. One possible solution is to loop through each operation and take the largest $a_i$ each time, and set $a_i = \max(0, a_i - b_i)$. This can be done with a set or a priority queue. With that in mind, let's binary search for the largest $x$ such that every value we add to... | [
"binary search",
"greedy",
"math"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
int n, k;
cin >> n >> k;
vector<int> A(n), B(n);
for (int &i : A)
cin >> i;
for (int &i : B)
cin >> i;
auto getInfo = [&](int cutoff){
ll ops = 0;
ll sum = 0;
for (... |
1996 | G | Penacony | On Penacony, The Land of the Dreams, there exists $n$ houses and $n$ roads. There exists a road between house $i$ and $i+1$ for all $1 \leq i \leq n-1$ and a road between house $n$ and house $1$. All roads are bidirectional. However, due to the crisis on Penacony, the overseeing family has gone into debt and may not be... | There are two configurations to satisfy every friendship $(a, b)$: activate all the roads from $a \rightarrow a+1 \rightarrow \dots \rightarrow b$ or $b \leftarrow \dots \leftarrow n \leftarrow 1 \leftarrow \dots \leftarrow a$. Let's fix a road we deactivate. Say it goes from $i \rightarrow i+1$. Observe that the confi... | [
"brute force",
"data structures",
"graphs",
"greedy",
"hashing"
] | 2,200 | #include <bits/stdc++.h>
#define int long long
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int n,m,a,b,k,t;
void solve() {
cin >> n >> m;
vector<int> v(n);
while (m--) {
k=rng(); cin >> a >> b;
v[a-1]^=k;
v[b-1]^=k;
}
map<int,int> c;
for (int r:v) m=max(... |
1997 | A | Strong Password | Monocarp's current password on Codeforces is a string $s$, consisting of lowercase Latin letters. Monocarp thinks that his current password is too weak, so he wants to \textbf{insert exactly one lowercase Latin letter} into the password to make it stronger. Monocarp can choose any letter and insert it anywhere, even be... | The time it takes to type a string can actually be calculated as follows: $2 \cdot |s| - p$, where $|s|$ is the number of characters in the string, and $p$ is the number of pairs of adjacent equal characters (usually a character takes $2$ seconds to type, but the right character in every pair of adjacent equal characte... | [
"brute force",
"implementation",
"strings"
] | 800 | #include<bits/stdc++.h>
using namespace std;
void solve()
{
string s;
cin >> s;
int n = s.size();
int idx = -1;
for(int i = 0; i + 1 < n; i++)
if(s[i] == s[i + 1])
idx = i;
if(idx == -1)
{
if(s.back() == 'a') cout << (s + "b") << endl;
else cout << (s + "a") << endl;
}
else
{
string t = "a";
... |
1997 | B | Make Three Regions | There is a grid, consisting of $2$ rows and $n$ columns. Each cell of the grid is either free or blocked.
A free cell $y$ is reachable from a free cell $x$ if at least one of these conditions holds:
- $x$ and $y$ share a side;
- there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable fro... | Since the chosen cell should split a connected region into $3$ non-empty parts, this cell should share a side with all $3$ of them. But any cell has at most $3$ neighbor cells (because there are only $2$ rows), and they should be split from each other by blocked cells. From the above, we can conclude how a pattern of a... | [
"constructive algorithms",
"two pointers"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<string> s(2);
for (auto& x : s) cin >> x;
int ans = 0;
for (int i = 1; i < n - 1; ++i) {
bool ok = true;
ok &= (s[0][i] == '.' && s[1][i] == '.');
ok &= (... |
1997 | C | Even Positions | Monocarp had a regular bracket sequence $s$ of length $n$ ($n$ is even). He even came up with his own way to calculate its cost.
He knows that in a regular bracket sequence (RBS), each opening bracket is paired up with the corresponding closing bracket. So he decided to calculate the cost of RBS as the sum of distance... | Let's define a balance of a bracket sequence as the $\texttt{number_of_opening_brackets} - \texttt{number_of_closing_brackets}$. It's a well-known fact that for RBS the balance of all its prefixes must be greater than or equal to zero and the balance of the whole string must be exactly zero. So, if we want to restore R... | [
"constructive algorithms",
"data structures",
"greedy"
] | 1,100 | import java.util.LinkedList
fun main() {
repeat(readln().toInt()) {
val n = readln().toInt()
val s = readln()
var ans = 0L
val bracketPositions = LinkedList<Int>()
for (i in s.indices) {
var c = s[i]
if (c == '_') {
c = if (bracketP... |
1997 | D | Maximize the Root | You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.
You can perform the following operation any number of times (possibly zero): choose a vertex $v$ \textbf{which has at least on... | We can clearly say that if some value $k$ can be obtained at the root, then any value from $a_1$ to $k$ can also be obtained. Using that fact, we can use binary search to solve the problem. Let's fix some value $\mathit{mid}$ in binary search and check if it is possible to apply an operation from the statement $\mathit... | [
"binary search",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto& x : a) cin >> x;
vector<vector<int>> g(n);
for (int i = 1; i < n; ++i) {
int... |
1997 | E | Level Up | Monocarp is playing a computer game. He starts the game being level $1$. He is about to fight $n$ monsters, in order from $1$ to $n$. The level of the $i$-th monster is $a_i$.
For each monster in the given order, Monocarp's encounter goes as follows:
- if Monocarp's level is strictly higher than the monster's level, ... | I would like to describe two different intended solutions to this problem. Solution One. Let's start with the following idea. How many times can the character's level increase for a fixed $k$? Given that there are $n$ monsters, even if we fight all of them, the level will not exceed $\frac{n}{k}$. That is, if we sum ov... | [
"binary search",
"brute force",
"data structures",
"divide and conquer",
"implementation"
] | 2,200 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct query{
int i, j;
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
vector<int> a(n);
forn(i, n) cin >> a[i];
vector<vector<query>> q(n + 1);
forn(j, m){
int i, x;
... |
1997 | F | Chips on a Line | You have $n$ chips, and you are going to place all of them in one of $x$ points, numbered from $1$ to $x$. There can be multiple chips in each point.
After placing the chips, you can perform the following four operations (in any order, any number of times):
- choose a chip in point $i \ge 3$, remove it and place two ... | The operations described in the statement are kinda similar to the identities for Fibonacci numbers, so maybe the solution will be connected to them. Let's assign each chip placement a weight: if chips are placed in points $x_1, x_2, \dots, x_n$ (repeating if multiple chips are in the same position), the weight of this... | [
"brute force",
"combinatorics",
"dp",
"greedy",
"math"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int main()
{
int n, x, m;
cin >> n >> x >> m;
vector<int> fib = {0, 1};
f... |
1998 | A | Find K Distinct Points with Fixed Center | \begin{quote}
I couldn't think of a good title for this problem, so I decided to learn from LeetCode.
\hfill — Sun Tzu, The Art of War
\end{quote}
You are given three integers $x_c$, $y_c$, and $k$ ($-100 \leq x_c, y_c \leq 100$, $1 \leq k \leq 1000$).
You need to find $k$ \textbf{distinct} points ($x_1, y_1$), ($x_2... | We can construct a solution by fixing all $x_i$ as $x_c$ or all $y_i$ as $y_c$. For example, if we fix all $y_i$ as $y_c$, then we can output pairs $(x_c-1, y_c), (x_c+1, y_c), (x_c-2, y_c), (x_c+2, y_c), ... , (x_c- \lfloor \frac{k}{2} \rfloor, y_c), (x_c + \lfloor \frac{k}{2} \rfloor, y_c)$. If the $k$ is odd, we nee... | [
"constructive algorithms",
"implementation",
"math"
] | 800 | #include <iostream>
using namespace std;
int main() {
int t; cin >> t;
while(t--){
int x, y, k; cin >> x >> y >> k;
for(int i = 0; i < k - k % 2; i++){
cout << x - (i & 1 ? 1 : -1) * (i / 2 + 1) << " " << y << "\n";
}
if(k & 1){
cout << x << " " << y << "\n";
}
}
} |
1998 | B | Minimize Equal Sum Subarrays | \begin{quote}
It is known that Farmer John likes Permutations, but I like them too!
\hfill — Sun Tzu, The Art of Constructing Permutations
\end{quote}
You are given a permutation$^{\text{∗}}$ $p$ of length $n$.
Find a permutation $q$ of length $n$ that minimizes the number of pairs ($i, j$) ($1 \leq i \leq j \leq n$)... | We can always construct a solution such that the number of pairs $(i, j)$ is $1$ where the only pair is $(1, n)$. There exists several constructions, such as rotating $p$ once or increment all $p_i$ (and $p_i = n$ turns into $p_i = 1$). Consider the former construction, where $q = [p_2, p_3, ..., p_n, p_1]$. For an arb... | [
"constructive algorithms",
"math",
"number theory"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
int n; cin >> n;
vector<int> p(n);
for(int& i: p) cin >> i;
rotate(p.begin(), p.begin() + 1, p.end());
for(int i: p) cout << i << " ";
cout << "\n";
}
} |
1998 | C | Perform Operations to Maximize Score | \begin{quote}
I see satyam343. I'm shaking. Please more median problems this time. I love those. Please satyam343 we believe in you.
\hfill — satyam343's biggest fan
\end{quote}
You are given an array $a$ of length $n$ and an integer $k$. You are also given a binary array $b$ of length $n$.
You can perform the follow... | satyam343, Dominater069 First, solve for $k = 0$. Find some nice characterization about $med(c_i)$ and thus the maximum score. Divide into $2$ cases where we either increment the max element or the median. Apply binary search Let's forget about the operations of adding $1$ to $a_i$ and figure out how to find an array's... | [
"binary search",
"brute force",
"constructive algorithms",
"greedy",
"implementation"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while (t--){
int n, k; cin >> n >> k;
vector <pair<int, int>> a(n);
for (auto &x : a) cin >> x.first;
for (auto &x : a) cin >> x.second;
sort(a.begin(), a.end());
l... |
1998 | D | Determine Winning Islands in Race | \begin{quote}
MOOOOOOOOOOOOOOOOO
\hfill — Bessie the Cow, The Art of Racing on Islands
\end{quote}
Two of Farmer John's cows, Bessie and Elsie, are planning to race on $n$ islands. There are $n - 1$ main bridges, connecting island $i$ to island $i + 1$ for all $1 \leq i \leq n - 1$. Additionally, there are $m$ alterna... | First, let's consider if there was no alternative bridges. Then obviously, if Bessie starts at island $i$ and keeps moving forwards, it is impossible for Elsie to move past island $i$ since the bridge would have already collapsed. From this, we can deduce that Bessie cannot let Elsie use these alternative bridges to ov... | [
"data structures",
"dp",
"graphs",
"greedy",
"shortest paths"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define FOR(i,a,b) for(int i = (a); i < (b); ++i)
#define ROF(i,a,b) for(int i = (a); i >= (b); --i)
#define trav(a,x) for(auto& a: x)
void solve() {
int n, m; cin >> n >> m;
vector<vector<int>> g(n), rg(n);
FOR(i,0,m){
int u, v; cin >> u >> v;
... |
1998 | E1 | Eliminating Balls With Merging (Easy Version) | \begin{quote}
Drink water.
\hfill — Sun Tzu, The Art of Becoming a Healthy Programmer
\end{quote}
\textbf{This is the easy version of the problem. The only difference is that $x=n$ in this version. You must solve both versions to be able to hack.}
You are given two integers $n$ and $x$ ($x=n$). There are $n$ balls li... | Consider the ball with the maximum number. Let this ball be $m$. That ball can clearly be the last ball remaining. And if we are able to merge some ball $i$ with ball $m$ (whilst removing $m$), then ball $i$ can also be the last ball remaining. We can do a divide and conquer solution. For some range $[l,r]$, let $m$ be... | [
"binary search",
"brute force",
"data structures",
"divide and conquer",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
int n, x;
cin >> n >> x;
vector<int> A(n + 5);
vector<ll> P(n + 5);
vector<int> ans(n + 5, 0);
vector<int> ord(n);
set<int> S{0, n + 1};
for (int i = 1; i <= n; i++){
cin >> A[i];
P[i] =... |
1998 | E2 | Eliminating Balls With Merging (Hard Version) | \begin{quote}
Drink water.
\hfill — Sun Tzu, The Art of Becoming a Healthy Programmer
\end{quote}
\textbf{This is the hard version of the problem. The only difference is that $x=1$ in this version. You must solve both versions to be able to hack.}
You are given two integers $n$ and $x$ ($x=1$). There are $n$ balls li... | Consider the naive greedy solution. We continuously merge with the balls on the left and right without removing our ball until we can't anymore or our ball is the final remaining one. Suppose at some point in this greedy approach, we can not merge with the balls on our left and right anymore without discarding our ball... | [
"binary search",
"brute force",
"data structures",
"divide and conquer",
"greedy",
"implementation"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
int n, x;
cin >> n >> x;
vector<ll> A(n + 5, 0);
vector<ll> P(n + 5, 0);
vector<vector<ll>> rmq(n + 5, vector<ll>(18, 0));
for (int i = 1; i <= n; i++){
cin >> A[i];
P[i] = P[i - 1] + A[i]; ... |
1999 | A | A+B Again? | Given a two-digit positive integer $n$, find the sum of its digits. | You can take the input as a string and output the sum of the two characters in the string. There is also a formula: $\lfloor \frac{n}{10} \rfloor + n \bmod 10$. The first term is the tens digit, the second term - the ones digit. | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
cout << (n / 10) + (n % 10) << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
} |
1999 | B | Card Game | Suneet and Slavic play a card game. The rules of the game are as follows:
- Each card has an integer value between $1$ and $10$.
- Each player receives $2$ cards which are face-down (so a player doesn't know their cards).
- The game is turn-based and consists \textbf{exactly of two turns}. In a round, both players pic... | For each test case, we can brute force through all possible games (there are only four of them) and calculate who is the winner of the game by simulating the game. | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,000 | def f(a, b):
if (a > b): return 1
if (a == b): return 0
if (a < b): return -1
for _ in range(int(input())):
a, b, c, d = map(int, input().split())
ans = 0
if f(a, c) + f(b, d) > 0:
ans += 1
if f(a, d) + f(b, c) > 0:
ans += 1
if f(b, c) + f(a, d) > 0:
ans += 1
... |
1999 | C | Showering | As a computer science student, Alex faces a hard challenge — showering. He tries to shower daily, but despite his best efforts there are always challenges. He takes $s$ minutes to shower and a day only has $m$ minutes!
He already has $n$ tasks planned for the day. Task $i$ is represented as an interval $(l_i$, $r_i)$,... | We just need to find the lengths of the gaps between intervals. Note that from the additional constraint on the input, the intervals are in sorted order. So you need to find if for any $i > 1$, $l_i - r_{i - 1} \geq s$, and also if $l_1 \geq s$ (the initial interval), or if $m - r_{n} \geq s$ (the final interval). | [
"greedy",
"implementation"
] | 800 | def solve():
n, s, m = map(int, input().split())
segs = [[0, 0], [m, m]] + [list(map(int, input().split())) for i in range(n)]
segs.sort()
for i in range(1, n + 2):
if segs[i][0] - segs[i - 1][1] >= s:
print('YES')
return
print('NO')
#sys.stdin = open('in', 'r')
for... |
1999 | D | Slavic's Exam | Slavic has a very tough exam and needs your help in order to pass it. Here is the question he is struggling with:
There exists a string $s$, which consists of lowercase English letters and possibly zero or more "?".
Slavic is asked to change each "?" to a lowercase English letter such that string $t$ becomes a subseq... | Let's use a greedy strategy with two pointers, one at the start of $s$ (called $i$) and one at the start of $t$ (called $j$). At each step, advance $i$ by $1$. If $s_i = \texttt{?}$, then we set it to $t_j$ and increment $j$. If $s_i = t_j$ then we also increment $j$ (because there is a match). It works because if ther... | [
"greedy",
"implementation",
"strings"
] | 1,100 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_cases; cin >> test_cases;
while(test_cases--) {
string s, t; cin >> s >> t;
int idx = 0;
for(int i = 0; i < (int)s.size(); ++i) {
if(s[i] == '?') {
if(idx < (int)t.size()) s[i] = t[idx++];
else s[i] ... |
1999 | E | Triple Operations | On the board Ivy wrote down all integers from $l$ to $r$, inclusive.
In an operation, she does the following:
- pick two numbers $x$ and $y$ on the board, erase them, and in their place write the numbers $3x$ and $\lfloor \frac{y}{3} \rfloor$. (Here $\lfloor \bullet \rfloor$ denotes rounding down to the nearest integ... | Consider writing the numbers in ternary (it is like binary but instead we use three digits, and for clarity we will use "digit" in the solution instead of "bit" or "trit"). In the operation, we will add a $0$ to the end of the number $x$ and remove the last digit of $y$. For example, if $x=8$ and $y=11$, then in ternar... | [
"dp",
"implementation",
"math"
] | 1,300 |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
int a[MAX], psum[MAX];
int f(int x) {
int cnt = 0;
while (x) {
x /= 3;
cnt++;
}
return cnt;
}
void solve() {
int l, r;
cin >> l >> r;
cout << psum[r] - psum[l - 1] + a[l] << '\n';
}
int main() {
ios:... |
1999 | F | Expected Median | Arul has a \textbf{binary} array$^{\text{∗}}$ $a$ of length $n$.
He will take all subsequences$^{\text{†}}$ of length $k$ ($k$ is odd) of this array and find their median.$^{\text{‡}}$
What is the sum of all these values?
As this sum can be very large, output it modulo $10^9 + 7$. In other words, print the remainder... | Say the array has $x$ ones and $y$ zeroes. If the median of a subsequence of length $k$ is $1$, then there are at least $\lfloor \frac{k}{2} \rfloor + 1$ ones in the array. Let's iterate over the number of ones in the subsequence from $\lfloor \frac{k}{2} \rfloor + 1$ to $x$. Suppose there are $i$ ones. Then there are ... | [
"combinatorics",
"math"
] | 1,500 |
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5, mod = 1e9 + 7;
int64_t fact[N];
int64_t pw(int64_t a, int64_t b) {
int64_t r = 1;
while(b > 0) {
if(b & 1) r = (r * a) % mod;
b /= 2;
a = (a * a) % mod;
}
return r;
}
int64_t C(int64_t n, int64_t k) {
if(n < k) return 0LL;
return (fact[... |
1999 | G1 | Ruler (easy version) | This is the easy version of the problem. The only difference between the two versions is that in this version, you can make at most $\mathbf{10}$ queries.
This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.
We have a secret ruler ... | Consider queries of the form $\texttt{?}~~\texttt{1}~~y$. Since $x > 1$, the height of the rectangle is always measured correctly. That means: If $y < x$, the response is $y$. If $y \geq x$, the response is $y+1$. | [
"binary search",
"interactive"
] | 1,500 |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
void solve() {
int l = 2, r = 1000;
while (l < r) {
int mid = l + (r - l) / 2;
cout << "? 1 " << mid << endl;
int resp; cin >> resp;
if (resp == mid) {
l = mid + 1;
}
else {
r = mid;
}
... |
1999 | G2 | Ruler (hard version) | This is the hard version of the problem. The only difference between the two versions is that in this version, you can make at most $\mathbf{7}$ queries.
This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.
We have a secret ruler t... | Consider one query of the form $\texttt{?}~~a~~b$ for $a < b$. That means: If $a < b < x$, the response is $a \cdot b$ (both $a$ and $b$ are measured correctly). If $a < x \leq b$, the response is $a \cdot (b + 1)$ ($a$ is measured correctly, but $b$ is not). If $x \leq a < b$, the repsone is $(a + 1) \cdot (b + 1)$ (b... | [
"binary search",
"interactive",
"ternary search"
] | 1,700 |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
void solve() {
int l = 1, r = 999;
while (r - l > 2) {
int a = (2 * l + r) / 3;
int b = (2 * r + l) / 3;
cout << "? " << a << ' ' << b << endl;
int resp; cin >> resp;
if (resp == (a + 1) * (b + 1)... |
2000 | A | Primary Task | Dmitry wrote down $t$ integers on the board, and that is good. He is sure that he lost an important integer $n$ among them, and that is bad.
The integer $n$ had the form $\text{10^x}$ ($x \ge 2$), where the symbol '$\text{^}$' denotes exponentiation.. Something went wrong, and Dmitry missed the symbol '$\text{^}$' whe... | You need to check that the number has the form '$\text{10x}$', where $x$ is an integer without leading zeros. This means it must start with '10'; if the length of the number is $3$, then the third digit must be at least $2$; if the length is greater, then the third digit must be at least $1$ (all such numbers $x$ are a... | [
"implementation",
"math",
"strings"
] | 800 | for _ in range(int(input())):
a = int(input())
if 102 <= a <= 109 or 1010 <= a <= 1099:
print("YES")
else:
print("NO") |
2000 | B | Seating in a Bus | In Berland, a bus consists of a row of $n$ seats numbered from $1$ to $n$. Passengers are advised to always board the bus following these rules:
- If there are no occupied seats in the bus, a passenger can sit in any free seat;
- Otherwise, a passenger should sit in any free seat that has at least one occupied neighbo... | To solve the problem, it is enough to use an array $used$ of size $2 \cdot 10^5 + 1$ (maximal value $n + 1$) consisting of boolean variables. When a passenger gets on the bus to seat $a_i$, we will replace the value of $used[a_i]$ with true. Then, for all passengers, starting from the second one, we should check that a... | [
"two pointers"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
vector<int>a(n);
for(auto &i : a) cin >> i;
int left = a[0], right = a[0];
for(int i = 1; i < n; i++){
if(a[i] + 1 == left) left = a[i];
else if(a[i] - 1 == right) right = a[i];
else {
... |
2000 | C | Numeric String Template | Kristina has an array $a$, called a template, consisting of $n$ integers. She also has $m$ strings, each consisting only of lowercase Latin letters. The strings are numbered from $1$ to $m$. She wants to check which strings match the template.
A string $s$ is considered to match the template if all of the following co... | To solve the problem, we can use two dictionaries (map): match the characters of the string to the numbers of the array in the map $m_1$ and the numbers of the array to the characters of the string in the map $m_2$. First, we check the length of the string to see if it is equal to the number $n$. If the string is longe... | [
"data structures",
"strings"
] | 1,000 | def solve():
n = int(input())
a = list(map(int, input().split()))
m = int(input())
for _ in range(m):
m_1 = {}
m_2 = {}
s = input().strip()
if len(s) != n:
print("NO")
continue
ok = True
for j in range(n):
if s[j] not ... |
2000 | D | Right Left Wrong | Vlad found a strip of $n$ cells, numbered from left to right from $1$ to $n$. In the $i$-th cell, there is a positive integer $a_i$ and a letter $s_i$, where all $s_i$ are either 'L' or 'R'.
Vlad invites you to try to score the maximum possible points by performing any (possibly zero) number of operations.
In one ope... | Note that since all characters of the selected segment of the string $s$ are erased after applying the operation, the segments we choose cannot overlap. However, they can be nested if we first choose an inner segment and then an outer one. Since all numbers in the array are positive, it is always beneficial to take the... | [
"greedy",
"implementation",
"two pointers"
] | 1,200 | def solve():
n = int(input())
a = [0]
for x in input().split():
x = int(x)
a.append(a[-1] + x)
s = input()
ans = 0
l = 0
r = n - 1
while r > l:
while l < n and s[l] == 'R':
l += 1
while r >= 0 and s[r] == 'L':
r -= 1
if l < ... |
2000 | E | Photoshoot for Gorillas | You really love gorillas, so you decided to organize a photoshoot for them. Gorillas live in the jungle. The jungle is represented as a grid of $n$ rows and $m$ columns. $w$ gorillas agreed to participate in the photoshoot, and the gorilla with index $i$ ($1 \le i \le w$) has a height of $a_i$. You want to place \textb... | We will learn how to find the number of sub-squares that cover the cell $(i, j)$: $(\min(i, n - k) - \max(-1, i - k)) \cdot (\min(j, m - k) - \max(-1, j - k))$. Next, we will use a straightforward greedy algorithm: we will place the tallest gorillas in the cells covered by the maximum number of squares. This can be don... | [
"combinatorics",
"data structures",
"greedy",
"math"
] | 1,400 | #include <bits/stdc++.h>
#define int long long
using namespace std;
#define MAXW 200200
#define MAXNM 200200
int n, m, k, w, p;
int arr[MAXW], prr[MAXNM];
static inline int calcc(int i, int j) {
int upr = min(i, n - k);
int leftr = min(j, m - k);
int upl = max(-1LL, i - k);
int leftl = max(-1L... |
2000 | F | Color Rows and Columns | You have $n$ rectangles, the $i$-th of which has a width of $a_i$ and a height of $b_i$.
You can perform the following operation an unlimited number of times: choose a rectangle and a cell in it, and then color it.
Each time you completely color any row or column, you earn $1$ point. Your task is to score at least $k... | We will use the idea from the knapsack problem: let $dp[i][j]$ be the minimum number of operations required to achieve $j$ points using the first $i$ rectangles. To calculate the next value, we will iterate over the number of points scored in the $i$-th rectangle. To count the number of operations, we note that it is a... | [
"dp",
"greedy",
"implementation",
"math"
] | 1,900 | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n), b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i] >> b[i];
}
vector<vector<int>> dp(n + 1, vector<int>(k + 1, 1e9));
dp[0][0] = 0;
for (int ... |
2000 | G | Call During the Journey | You live in a city consisting of $n$ intersections and $m$ streets connecting some pairs of intersections. You can travel in either direction on each street. No two streets connect the same pair of intersections, and no street connects an intersection to itself. You can reach any intersection from any other, possibly p... | Let's find the maximum time $ans_i$ for each vertex, at which it is possible to leave from it and reach vertex $n$ at time $t_0$. To find this value, we will run Dijkstra's algorithm from the last vertex. When processing the next edge, we will check if it is possible to travel by bus during the time interval from $ans_... | [
"binary search",
"brute force",
"graphs",
"greedy",
"shortest paths"
] | 2,100 | #include <iostream>
#include <vector>
#include <set>
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
int t0, t1, t2;
cin >> t0 >> t1 >> t2;
vector<vector<vector<int>>> g(n);
for (int i = 0; i < m; ++i) {
int u, v, l1, l2;
cin >> u >> v >> l1 >> l2;
u--, v... |
2000 | H | Ksyusha and the Loaded Set | Ksyusha decided to start a game development company. To stand out among competitors and achieve success, she decided to write her own game engine. The engine must support a set initially consisting of $n$ distinct integers $a_1, a_2, \ldots, a_n$.
The set will undergo $m$ operations sequentially. The operations can be... | We will maintain the elements of a set in std::set. We will also maintain a std::set of free segments (in the form of half-intervals). These segments can be easily updated during insertion and deletion operations. In one case, we need to remove a large segment and insert two small ones; in another case, we need to remo... | [
"binary search",
"brute force",
"data structures",
"implementation"
] | 2,200 | #pragma GCC optimize("O3,unroll-loops")
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef pair<int, int> ipair;
#define INF 1'000'000'009
#define MAXN 200200
#define MAXMEM 5'000'000
#define MAXLEN 2'000'100
#define X first
#define Y second
mt19937 rng(chrono::steady_clock::now().tim... |
2001 | A | Make All Equal | You are given a cyclic array $a_1, a_2, \ldots, a_n$.
You can perform the following operation on $a$ at most $n - 1$ times:
- Let $m$ be the current size of $a$, you can choose any two adjacent elements where the previous one is no greater than the latter one (In particular, $a_m$ and $a_1$ are adjacent and $a_m$ is ... | What's the most obvious lower bound of the answer? Is the lower bound achievable? One standard way to solve optimization problem is to make observation on lower(upper) bound of the answer and prove such bound is achievable, it's useful in lot of problems. Let $x$ be one of the most frequent elements in $a$, then the an... | [
"greedy",
"implementation"
] | 800 | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(NULL);
int t; cin >> t;
while(t--) {
int n; cin >> n;
vector<int> a(n);
for(int &x : a) cin >> x;
vector<int> freq(n + 1);
for(int x : a) freq[x]++;
cout <... |
2001 | B | Generate Permutation | There is an integer sequence $a$ of length $n$, where each element is initially $-1$.
Misuki has two typewriters where the first one writes letters from left to right, with a pointer initially pointing to $1$, and another writes letters from right to left with a pointer initially pointing to $n$.
Misuki would choose ... | Write a few small cases (ex. $n = 3, 4, 5$) and play with it, can you notice something interesting about the cost function? Write a few examples and play with it is a good start to solve ad-hoc problems. Consider subtask - decision version of the problem (i.e. yes/no problem) as follow: "Given a fixed $p$, check if thi... | [
"constructive algorithms"
] | 800 | #include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(NULL);
int t; cin >> t;
while(t--) {
int n; cin >> n;
if (n % 2 == 0) {
cout << -1 << '\n';
} else {
vector<int> p(n);
iota(p.begin(), p.end(), 1);
... |
2001 | C | Guess The Tree | This is an interactive problem.
Misuki has chosen a secret tree with $n$ nodes, indexed from $1$ to $n$, and asked you to guess it by using queries of the following type:
- "? a b" — Misuki will tell you which node $x$ minimizes $|d(a,x) - d(b,x)|$, where $d(x,y)$ is the distance between nodes $x$ and $y$. If more th... | Imagine we have $n$ isolated vertices initially, can you find any edge connect two component using reasonable number of queries? Use binary search. It's easy to verify that querying $a$ and $b$ will return the midpoint of the path between $a$ and $b$. In case the path has odd length, the node closer to $a$ of the two c... | [
"binary search",
"brute force",
"dfs and similar",
"divide and conquer",
"dsu",
"greedy",
"interactive",
"trees"
] | 1,500 | #include <iostream>
#include <numeric>
#include <vector>
#include <array>
using namespace std;
int query(int u, int v) {
cout << "? " << u + 1 << ' ' << v + 1 << '\n';
int x; cin >> x;
return x - 1;
}
int main() {
int t; cin >> t;
while(t--) {
int n; cin >> n;
vector<array<int, 2>> e;
vector<i... |
2001 | D | Longest Max Min Subsequence | You are given an integer sequence $a_1, a_2, \ldots, a_n$. Let $S$ be the set of all possible non-empty subsequences of $a$ without duplicate elements. Your goal is to find the longest sequence in $S$. If there are multiple of them, find the one that minimizes lexicographical order after multiplying terms at odd positi... | Forget about minimize lexicographical order. What's the size of longest $b$ we can get? It's the number of different elements. Try to minimize/maximize first element in $b$ without reducing the max size of $b$ we can get. When solving problem asking for minimize/maximize lexicographical order of something, we can often... | [
"brute force",
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 1,900 | #include <cstdint>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
void solve() {
int N; cin >> N;
vector<int> A(N);
for (int &x : A) cin >> x, --x;
vector<int> cnt(N, 0), is_last(N, 0), last_pos(N, -1);
for (int i = N-1; i >= 0; --i) {
if (!cnt[A[i]]++)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.