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 ⌀ |
|---|---|---|---|---|---|---|---|
1618 | G | Trader Problem | Monocarp plays a computer game (yet again!). This game has a unique trading mechanics.
To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price $x$, then he can trade it ... | Suppose we have fixed the value of $k$, so we can trade an item with price $i$ for an item with price $j$ if $j \in [0, i + k]$. We can see that it's never optimal to trade an item with higher price for an item with lower price, and we could just simulate the trading process as follows: try to find an item owned by Pol... | [
"data structures",
"dsu",
"greedy",
"sortings"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
long long get(const vector<int>& pcnt, const vector<long long>& psum, pair<int, int> seg)
{
int L = seg.first;
int R = seg.second;
int cnt = pcnt[R] - pcnt[L];
return psum[R] - psum[R - cnt];
}
int main()
{
int n, m, q;
scanf("%d %d %d", &n, &m, &q... |
1619 | A | Square String? | A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.
For a given string $s$ determine if it is square. | If the length of the given string $s$ is odd, then the answer is NO, since adding two strings cannot do that. Otherwise, let $n$ be the length of the string. Let's go through the first half of the string, comparing whether its first and $\frac{n}{2} + 1$ characters are equal, its second and $\frac{n}{2} + 2$ characters... | [
"implementation",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
string s;
cin >> s;
bool ok = true;
if (s.length() % 2 == 0) {
forn(i, s.length() / 2)
if (s[i] != s... |
1619 | B | Squares and Cubes | Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: $1$, $4$, $8$, $9$, ....
For a given number $n$, count the number of integers from $1$ to $n$ that Polycarp likes. In other words, find the number of such $x$ that $x$ is a square of a positive integer num... | We'll search for positive integers not larger than $n$, and add their squares or cubes to the set if they don't exceed $n$. If $n = 10^9$, the maximum number Polycarp will like is $31622^2 = 999950884$, so the running time will be within the time limit. The answer to the problem is the length of the resulting set. | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n;
cin >> n;
set<int> a;
for (int i = 1; i * i <= n; i++)
a.insert(i * i);
for (int i = 1; i * i * i <= ... |
1619 | C | Wrong Addition | Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $a$ and $b$ using the following algorithm:
- If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.
- The numbers are processed from right to left (that ... | Let's compute the answer to the array $b$, where $b_ k$ is the digit at the $k$ position in the number we are looking for. Let $i$ be the position of the last digit in number $a$, $j$ be the position of the last digit in number $s$. Then denote $x = a_i$, $y = s_j$, and consider the cases: if $x \le y$, then the sum of... | [
"implementation"
] | 1,200 | #include<bits/stdc++.h>
#define len(s) (int)s.size()
using namespace std;
using ll = long long;
void solve(){
ll a, s;
cin >> a >> s;
vector<int>b;
while(s){
int x = a % 10;
int y = s % 10;
if(x <= y) b.emplace_back(y - x);
else{
s /= 10;
y += 10... |
1619 | D | New Year's Problem | Vlad has $n$ friends, for each of whom he wants to buy one gift for the New Year.
There are $m$ shops in the city, in each of which he can buy a gift for any of his friends. If the $j$-th friend ($1 \le j \le n$) receives a gift bought in the shop with the number $i$ ($1 \le i \le m$), then the friend receives $p_{ij}... | Note that if we cannot get joy $x$, then we cannot get $x+1$, and if we can get at least $x$, then we can get at least $x-1$. These facts allow us to use binary search to find the answer. Now we need to understand how exactly we can recognize whether we can gain joy at least $x$ or not. We can enter at most $n-1$ shops... | [
"binary search",
"greedy",
"sortings"
] | 1,800 | //
// Created by Vlad on 17.12.2021.
//
#include <bits/stdc++.h>
#define int long long
#define mp make_pair
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
/*#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimiz... |
1619 | E | MEX and Increments | Dmitry has an array of $n$ non-negative integers $a_1, a_2, \dots, a_n$.
In one operation, Dmitry can choose any index $j$ ($1 \le j \le n$) and increase the value of the element $a_j$ by $1$. He can choose the same index $j$ multiple times.
For each $i$ from $0$ to $n$, determine whether Dmitry can make the $\mathrm... | First, let's sort the array. Then we will consider its elements in non-decreasing order. To make MEX equal to $0$, you need to increase all zeros. To make MEX at least $n$, you first need to make MEX at least $n - 1$, and then, if the number $n - 1$ is missing in the array, you need to get it. If there are no extra val... | [
"constructive algorithms",
"data structures",
"dp",
"greedy",
"implementation",
"math",
"sortings"
] | 1,700 | #include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAX_N = 2e5;
int main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n;
cin >> n;
vector<int> a(n), cnt(n + 1);
for (int i = 0; i < n... |
1619 | F | Let's Play the Hat? | The Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play).
$n$ people gathered in a room with $m$ tables ... | For each game, we want to seat $n$ people at $m$ tables, $n \mod m$ of them will be big and $B = \lceil\frac{n}{m}\rceil$ will sit at them, and $m - n \mod m$ will be small. Each round $p = n \mod m * B$ people will sit at the big tables. Let's put people with numbers $0, 1, 2 \dots p - 1$ at large tables in the first ... | [
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n, m, k;
cin >> n >> m >> k;
vector<int> p(n);
forn(i, n)
p[i] = i;
if (tt > 0)
cout << endl... |
1619 | G | Unusual Minesweeper | Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.
There are mines on the field, for each the coordinates of its location are known ($x_i, y_i$). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates... | Our first task is to separate mines into components. We will store in the hashmap $mapx$ at the $x$ coordinate all the $y$ coordinates where there is a mine. Let's do the same with the $mapy$ hashmap. Thus, going through the available arrays in $mapx$ and $mapy$, we connect adjacent elements into one component, if $|ma... | [
"binary search",
"dfs and similar",
"dsu",
"greedy",
"sortings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int k;
map <int, vector<int>> mx;
map <int, vector<int>> my;
map <pair<int ,int>, bool> used;
map <pair<int, int>, int> time_of;
int dfs(int x, int y) {
used[{x, y}] = true;
int _m... |
1619 | H | Permutation and Queries | You are given a permutation $p$ of $n$ elements. A permutation of $n$ elements is an array of length $n$ containing each integer from $1$ to $n$ exactly once. For example, $[1, 2, 3]$ and $[4, 3, 5, 1, 2]$ are permutations, but $[1, 2, 4]$ and $[4, 3, 2, 1, 2]$ are not permutations. You should perform $q$ queries.
The... | Let's compute an array $a$ of $n$ integers - answers to all possible second-type queries with $k = Q$, $Q \approx \sqrt n$. Now, if we have to perform any second-type query, we can split it into at most $n / Q$ queries with $k = Q$ and at most $Q - 1$ queries with $k = 1$. Let's also compute an array $r$ of $n$ integ... | [
"brute force",
"data structures",
"divide and conquer",
"two pointers"
] | 2,400 | #include <bits/stdc++.h>
//#define int long long
#define ld long double
#define x first
#define y second
#define pb push_back
using namespace std;
const int Q = 100;
int n, q, p[100005], r[100005], a[100005];
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
... |
1620 | A | Equal or Not Equal | You had $n$ positive integers $a_1, a_2, \dots, a_n$ arranged in a circle. For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, ..., $a_{n - 1}$ and $a_n$, and $a_n$ and $a_1$), you wrote down: are the numbers in the pair equal or not.
Unfortunately, you've lost a piece of paper with the array $a$. ... | Let's look at a group of E: it's easy to see that each such a group is equal to the same number. Now, let's look at how these groups are distributed on the circle: If there are no N then all $a_i$ are just equal to each other. It's okay. If there is exactly one N then from one side, all of them are still in one group, ... | [
"constructive algorithms",
"dsu",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
cout << (count(s.begin(), s.end(), 'N') == 1 ? "NO\n" : "YES\n");
}
} |
1620 | B | Triangles on a Rectangle | A rectangle with its opposite corners in $(0, 0)$ and $(w, h)$ and sides parallel to the axes is drawn on a plane.
You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.
Your task is to choose t... | The area of a triangle is equal to its base multiplied by its height divided by $2$. Let the two points that have to be on the same side of a rectangle form its base. To maximize it, let's choose such two points that are the most apart from each other - the first and the last in the list. Then the height will be determ... | [
"geometry",
"greedy",
"math"
] | 1,000 | for _ in range(int(input())):
w, h = map(int, input().split())
ans = 0
for i in range(4):
a = [int(x) for x in input().split()][1:]
ans = max(ans, (a[-1] - a[0]) * (h if i < 2 else w))
print(ans) |
1620 | C | BA-String | You are given an integer $k$ and a string $s$ that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).
Each asterisk should be replaced with several (from $0$ to $k$ inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.
The result... | Find all segments of asterisks in the string. Let there be $t$ of them, and the number of asterisks in them be $c_1, c_2, \dots, c_t$. That tells us that the $i$-th segment of asterisks can be replaced with at most $c_i \cdot k$ letters 'b'. Notice that we can compare two strings lexicographically using just the number... | [
"brute force",
"dp",
"greedy",
"implementation",
"math"
] | 1,800 | for _ in range(int(input())):
n, k, x = map(int, input().split())
x -= 1
s = input()[::-1]
res = []
i = 0
while i < n:
if s[i] == 'a':
res.append(s[i])
else:
j = i
while j + 1 < n and s[j + 1] == s[i]:
j += 1
cur = (j - i + 1) * k + 1
res.append('b' * (x % cur))... |
1620 | D | Exact Change | One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of $n$ different flavors. A bag of the $i$-th flavor costs $a_i$ burles.
The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in thi... | Let's define $m = \max(a_i)$, then it should be obvious that we need at least $r = \left\lceil \frac{m}{3} \right\rceil$ coins to buy a bag of chips of cost $m$. Now, it's not hard to prove that $r + 1$ coins is always enough to buy a bag of chips of any cost $c \le m$. Proof: if $m \equiv 0 \pmod 3$, we'll take $r - 1... | [
"brute force",
"constructive algorithms",
"greedy"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.y << ")";
}
template<class A> ostream& operator <<(ostream... |
1620 | E | Replace the Numbers | You have an array of integers (initially empty).
You have to perform $q$ queries. Each query is of one of two types:
- "$1$ $x$" — add the element $x$ to the end of the array;
- "$2$ $x$ $y$" — replace all occurrences of $x$ in the array with $y$.
Find the resulting array after performing all the queries. | Let's solve the problem from the end. Let's maintain the array $p_x$ - what number will $x$ become if we apply to it all the already considered queries of type $2$. If the current query is of the first type, then we simply add $p_x$ to the resulting array. If the current query is of the second type, then we have to cha... | [
"constructive algorithms",
"data structures",
"dsu",
"implementation"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int N = 500 * 1000 + 13;
int n, q;
vector<int> pos[N];
int main() {
scanf("%d", &q);
while (q--) {
int t, x, y;
scanf("%d", &t);
if (t == 1) {
scanf("%d", &x);
pos[x].push_back(n++);
} else {
scanf("%d%d", &x, &y);
if (x... |
1620 | F | Bipartite Array | You are given a permutation $p$ consisting of $n$ integers $1, 2, \dots, n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).
Let's call an array $a$ bipartite if the following undirected graph is bipartite:
- the graph consists of $n$ vertices;
- two vertices $i$ and $j$ are connect... | To begin with, let's understand that an array is bipartite if and only if there is no decreasing subsequence of length $3$ in the array. Now we can write dynamic programming $dp_{i, x, y}$: is there an array $a$ of length $i$ such that $x$ is the maximum last element of a decreasing subsequence of length $1$, and $y$ i... | [
"dp",
"greedy"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int INF = 1e9;
const int N = 1000 * 1000 + 13;
int n;
int p[N], a[N];
int dp[N][2], pr[N][2];
void solve() {
scanf("%d", &n);
forn(i, n) scanf("%d", &p[i]);
forn(i, n) forn(j, 2) dp[i][j] = INF;
dp[0][0]... |
1620 | G | Subsequences Galore | For a sequence of strings $[t_1, t_2, \dots, t_m]$, let's define the function $f([t_1, t_2, \dots, t_m])$ as the number of different strings (\textbf{including the empty string}) that are subsequences of \textbf{at least one} string $t_i$. $f([]) = 0$ (i. e. the number of such strings for an empty sequence is $0$).
Yo... | For a string $t$, let's define its characteristic mask as the mask of $n$ bits, where $i$-th bit is $1$ if and only if $t$ is a subsequence of $s_i$. Let's suppose we somehow calculate the number of strings for each characteristic mask, and we denote this as $G(x)$ for a mask $x$. How can we use this information to fin... | [
"bitmasks",
"combinatorics",
"dp"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
const int N = 23;
const int A = 26;
const int S = 20043;
int n;
string inp[N];
char buf[S];
int cnt[N][A];
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 sub(int x, int y)
{
... |
1621 | A | Stable Arrangement of Rooks | You have an $n \times n$ chessboard and $k$ rooks. Rows of this chessboard are numbered by integers from $1$ to $n$ from top to bottom and columns of this chessboard are numbered by integers from $1$ to $n$ from left to right. The cell $(x, y)$ is the cell on the intersection of row $x$ and collumn $y$ for $1 \leq x \l... | It is easy to see that if there are two rooks in the neighbouring rows we can move one of them to the another of these two rows, so there shouldn't be two rooks in the neighbouring rows in a stable arrangement. Let's split chessboard into $\lceil \frac{n}{2} \rceil$ regions in the following way: region $1$ contains all... | [
"constructive algorithms"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
if (k > (n + 1) / 2)
{
cout << "-1\n";
continue;
}
vector<string> s(n, string(n, '.'));
for (int i = 0; i... |
1621 | B | Integers Shop | The integers shop sells $n$ segments. The $i$-th of them contains all integers from $l_i$ to $r_i$ and costs $c_i$ coins.
Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of ... | Let $L$ be the minimum integer Vasya will buy and $R$ be the maximum integer Vasya will buy. Then it is easy to see that he will get all integers between $L$ and $R$ and only them after receiving a gift. Because Vasya wants to maximise the number of integers he will get, he should buy the smallest and the largest integ... | [
"data structures",
"greedy",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int answer(set<vector<int> > &byL, set<vector<int> > &byR, map<pair<int, int>, set<int> > &all)
{
if (byL.size() == 0)
return 0;
int L = (*byL.begin())[0];
int R = (*byR.rbegin())[0];
int Lc = (*byL.begin())[1];
int Rc = -(*byR.rbegin())[1];
... |
1621 | C | Hidden Permutations | \textbf{This is an interactive problem.}
The jury has a permutation $p$ of length $n$ and wants you to guess it. For this, the jury created another permutation $q$ of length $n$. Initially, $q$ is an identity permutation ($q_i = i$ for all $i$).
You can ask queries to get $q_i$ for any $i$ you want. After each query,... | At first, let's solve this problem when $p$ is a cycle of length $n$. It can be done by asking for $q_1$ for $n$ times. After this, we will receive $1$, $p_1$, $p_{p_1}$, $p_{p_{p_1}}, \ldots$ in this order. Since $p$ is a cycle, each $x$ will appear once in this sequence. The next element after $x$ will be $p_x$. When... | [
"dfs and similar",
"interactive",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int ask(int i)
{
cout << "? " << i + 1 << endl;
int x;
cin >> x;
return x - 1;
}
void solve()
{
int n;
cin >> n;
vector<int> myp(n, -1);
for (int i = 0; i < n; i++)
{
if (myp[i] == -1)
{
vector<int> cyc... |
1621 | D | The Winter Hike | Circular land is an $2n \times 2n$ grid. Rows of this grid are numbered by integers from $1$ to $2n$ from top to bottom and columns of this grid are numbered by integers from $1$ to $2n$ from left to right. The cell $(x, y)$ is the cell on the intersection of row $x$ and column $y$ for $1 \leq x \leq 2n$ and $1 \leq y ... | Let's say that if for cell $(i, j)$, $c_{i, j}=0$ then it is covered with snow but the cost of removing snow from this cell is $0$. It is obvious that we should remove all the snow in the bottom right corner of the grid. In the case $n=1$ we should remove the snow from the exactly one of the remaining cells. Now concid... | [
"constructive algorithms",
"greedy",
"math"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve()
{
int n;
cin >> n;
vector<vector<ll> > a(2 * n, vector<ll>(2 * n));
for (int i = 0; i < 2 * n; i++)
{
for (int j = 0; j < 2 * n; j++)
{
cin >> a[i][j];
}
}
ll ans = 0;
... |
1621 | E | New School | You have decided to open a new school. You have already found $n$ teachers and $m$ groups of students. The $i$-th group of students consists of $k_i \geq 2$ students. You know age of each teacher and each student. The ages of teachers are $a_1, a_2, \ldots, a_n$ and the ages of students of the $i$-th group are $b_{i, 1... | Suppose, that you know average ages of each group of studens $avg_1, avg_2, \ldots, avg_m$. How can we check whether we can start lessons? Let's sort this ages and ages of teachers in the decreasing order. Now we have $avg_1 \geq avg_2 \geq \ldots \geq avg_m$ and $a_1 \geq a_2 \geq \ldots \geq a_n$. In all the followin... | [
"binary search",
"data structures",
"dp",
"greedy",
"implementation",
"sortings"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int comp(pair<long long, int> a, pair<long long, int> b)
{
if (a.first * b.second < b.first * a.second)
return 1;
return 0;
}
void solve()
{
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vector<... |
1621 | F | Strange Instructions | Dasha has $10^{100}$ coins. Recently, she found a binary string $s$ of length $n$ and some operations that allows to change this string (she can do each operation any number of times):
- Replace substring 00 of $s$ by 0 and receive $a$ coins.
- Replace substring 11 of $s$ by 1 and receive $b$ coins.
- Remove 0 from an... | From the rule $4$ it follows that the sequence of types of operations looks like $\ldots$, ($1$ or $3$), $2$, ($1$ or $3$), $2$, ($1$ or $3$), $\ldots$. One can suppose that operation $1$ is "better" than operation $3$ so we can (in optimal solution) do all operations of type $3$ after all operations of type $1$. Howev... | [
"data structures",
"greedy",
"implementation"
] | 2,700 | #include <bits/stdc++.h>
typedef long long ll;
const int INF = 1e9;
using namespace std;
#define forn(i, n) for (int i = 0; (i) != (n); (i)++)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
void solver(int turn, ll &ans, ll a, ll b, ll c, vector<int> blocks, ll other0, ll single0... |
1621 | G | Weighted Increasing Subsequences | You are given the sequence of integers $a_1, a_2, \ldots, a_n$ of length $n$.
The sequence of indices $i_1 < i_2 < \ldots < i_k$ of length $k$ denotes the subsequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ of length $k$ of sequence $a$.
The subsequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ of length $k$ of sequence $a$ is... | At first, this problem can be easily reduced to the problem about permutations by replacing $a_i$ by pair $(a_i, -i)$. The relative order of such pairs is the same as in the problem, however all of them are different so we can replace them with permutation. Let the weight of increasing subsequence $a_{i_1}, a_{i_2}, \l... | [
"data structures",
"dp",
"math"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
void add(int pos, int x, vector<int> &fenw)
{
while (pos < fenw.size())
{
fenw[pos] += x;
fenw[pos] %= MOD;
pos |= (pos + 1);
}
}
int get(int pos, vector<int> &fenw)
{
int res = 0;
while (pos >= 0)... |
1621 | H | Trains and Airplanes | Railway network of one city consists of $n$ stations connected by $n-1$ roads. These stations and roads forms a tree. Station $1$ is a city center. For each road you know the time trains spend to pass this road. You can assume that trains don't spend time on stops. Let's define $dist(v)$ as the time that trains spend t... | Let $scans_{v, i}$ be the number of scans in the $i$-th zone if we start from the vertex $v$ and $scans_{v, z_v} = 0$. Note that $scans$ doesn't change during queries. Now our task is to calculate $\sum_{z \in zones} \min (scans_{v, z} \cdot fine_{z}, pass_{z})$ over some set of vertices $A_i$ described in the $i$-th q... | [
"dfs and similar",
"graphs",
"shortest paths",
"trees"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 5;
pair<vector<long long>, vector<pair<int, int> > > get_total_and_changes(int vv, int k, int T, vector<long long> &depth, vector<int> &checkpoint, string &z)
{
//int vv = par;
long long enter_time = 0;
long long cur_time = 0;
... |
1621 | I | Two Sequences | Consider an array of integers $C = [c_1, c_2, \ldots, c_n]$ of length $n$. Let's build the sequence of arrays $D_0, D_1, D_2, \ldots, D_{n}$ of length $n+1$ in the following way:
- The first element of this sequence will be equals $C$: $D_0 = C$.
- For each $1 \leq i \leq n$ array $D_i$ will be constructed from $D_{i-... | Let's denote the construction of array $D_i$ from array $D_{i-1}$ as the $i$-th step of transformation $op$. Also let's behave as all steps affect $C$ instead of creating multiple new arrays. The solution consists of $4$ parts: Show that there exists small $m$, such that $B_m = B_{m-1}$. If $n \leq 10^5$ then $m$ doesn... | [
"data structures",
"hashing",
"string suffix structures"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define all(x) (x).begin(), (x).end()
#define l first
#define r second
const int INF = 1e9 + 1;
const int N = 202000;
const ll MOD1 = 998244391;
const ll M1 = 1e6 + 3;
int deg1[N];
vector<int> lcp(vector<int> &s,... |
1622 | A | Construct a Rectangle | There are three sticks with integer lengths $l_1, l_2$ and $l_3$.
You are asked to break exactly one of them into two pieces in such a way that:
- both pieces have positive (strictly greater than $0$) \textbf{integer} length;
- the total length of the pieces is equal to the original length of the stick;
- it's possib... | First, the condition about being able to construct a rectangle is the same as having two pairs of sticks of equal length. Let's fix the stick that we are going to break into two parts. Now there are two cases. The remaining two sticks can be the same. In that case, you can break the chosen stick into equal parts to mak... | [
"geometry",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
vector<int> l(3);
for (int i = 0; i < 3; ++i)
cin >> l[i];
bool ok = false;
for (int i = 0; i < 3; ++i)
ok |= l[i] == l[(i + 1) % 3] + l[(i + 2) % 3];
for (int i = 0; i < 3; ++i) if (l[i] % ... |
1622 | B | Berland Music | Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.
So imagine Monocarp got recommended $n$ songs, numbered from $1$ to $n$. The $i$-th song had its predicted rating equal to $p_i$, where $1 \le p_i \le n$ ... | Since we know that every disliked song should have lower rating than every liked song, we actually know which new ratings should belong to disliked songs and which should belong to the liked ones. The disliked songs take ratings from $1$ to the number of zeros in $s$. The liked songs take ratings from the number of zer... | [
"data structures",
"greedy",
"math",
"sortings"
] | 1,000 | for _ in range(int(input())):
n = int(input())
p = [int(x) for x in input().split()]
s = input()
l = sorted([[s[i], p[i], i] for i in range(n)])
q = [-1 for i in range(n)]
for i in range(n):
q[l[i][2]] = i + 1
print(*q) |
1622 | C | Set or Decrease | You are given an integer array $a_1, a_2, \dots, a_n$ and integer $k$.
In one step you can
- either choose some index $i$ and decrease $a_i$ by one (make $a_i = a_i - 1$);
- or choose two indices $i$ and $j$ and set $a_i$ equal to $a_j$ (make $a_i = a_j$).
What is the minimum number of steps you need to make the sum... | First, we can prove that the optimal way to perform operations is first, decrease the minimum value several (maybe, zero) times, then take several (maybe, zero) maximums and make them equal to the minimum value. The proof consists of several steps: Prove that first, we make decreases, only then sets: if some $a_i = a_i... | [
"binary search",
"brute force",
"greedy",
"sortings"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
typedef long long li;
const int INF = int(1e9);
const li INF64 = li(1e18);
int n;
li k;
vector<int> a;
inline bool read() {
if(!(cin >> n >> k))
return false;
a.resize(n);
for... |
1622 | D | Shuffle | You are given a binary string (i. e. a string consisting of characters 0 and/or 1) $s$ of length $n$. You can perform the following operation with the string $s$ \textbf{at most once}: choose a substring (a contiguous subsequence) of $s$ having \textbf{exactly} $k$ characters 1 in it, and shuffle it (reorder the charac... | We could iterate on the substrings we want to shuffle and try to count the number of ways to reorder their characters, but, unfortunately, there's no easy way to take care of the fact that shuffling different substrings may yield the same result. Instead, we will iterate on the first and the last character that are cha... | [
"combinatorics",
"math",
"two pointers"
] | 2,000 | #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 main()
{
int n;
cin >> n;
int k;
cin >> k;
string s;
cin >> s;
vector<int> p(n + 1);
for(int ... |
1622 | E | Math Test | Petya is a math teacher. $n$ of his students has written a test consisting of $m$ questions. For each student, it is known which questions he has answered correctly and which he has not.
If the student answers the $j$-th question correctly, he gets $p_j$ points (otherwise, he gets $0$ points). Moreover, the points for... | Note that there are only two ways to fix the result of the operation of taking an absolute value in the expression $|x_i - r_i|$: $x_i - r_i$ or $r_i - x_i$. Since the value of $n$ is small enough that we can iterate over all $2^n$ options, and choose the one for which the sum is maximum. For each student, let's fix wi... | [
"bitmasks",
"brute force",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, m;
scanf("%d%d", &n, &m);
vector<int> x(n);
forn(i, n) scanf("%d", &x[i]);
vector<vector<int>> a(n, vector<int>(m));
forn(i, n) for... |
1622 | F | Quadratic Set | Let's call a set of positive integers $a_1, a_2, \dots, a_k$ quadratic if the product of the factorials of its elements is a square of an integer, i. e. $\prod\limits_{i=1}^{k} a_i! = m^2$, for some integer $m$.
You are given a positive integer $n$.
Your task is to find a quadratic subset of a set $1, 2, \dots, n$ of... | A good start to solve the problem would be to check the answers for small values of $n$. One can see that the answers (the sizes of the maximum subsets) are not much different from $n$ itself, or rather not less than $n-3$. Let's try to prove that this is true for all $n$. Consider $n$ is even. Let $n=2k$, let's see wh... | [
"constructive algorithms",
"hashing",
"math",
"number theory"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int N = 1000 * 1000 + 13;
using li = unsigned long long;
int pr[N];
li hs[N], f[N];
unordered_map<li, int> rf;
int main() {
int n;
scanf("%d", &n);
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
iota(pr, pr + N, 0);
for (int ... |
1623 | A | Robot Cleaner | A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $n$ rows and $m$ columns. The rows of the floor are numbered from $1$ to $n$ from top to bottom, and columns of the floor are numbered from $1$ to $m$ from left to right. The cell on the intersection of the $r$-th row... | Let's consider the 1-D problem of this problem: there are $n$ cells, lying in a row. The robot is at the $x$-th cell, and the dirty cell is at the $y$-th cell. Each second, the robot cleans the cell at its position. The robot initially moves by 1 cell to the right each second. If there is no cell in the movement direct... | [
"brute force",
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int ntest;
cin >> ntest;
while (ntest--) {
int n, m, rb, cb, rd, cd;
cin >> n >> m >> rb >> cb >> rd >> cd;
cout << min(
rb <= rd ? rd - rb : 2 * n - rb - rd,
cb <= cd ? cd - cb : 2 * m - cb - cd
... |
1623 | B | Game on Ranges | Alice and Bob play the following game. Alice has a set $S$ of disjoint ranges of integers, initially containing only one range $[1, n]$. In one turn, Alice picks a range $[l, r]$ from the set $S$ and asks Bob to pick a number in the range. Bob chooses a number $d$ ($l \le d \le r$). Then Alice removes $[l, r]$ from $S$... | If the length of a range $[l, r]$ is 1 (that is, $l = r$), then $d = l = r$. Otherwise, if Bob picks a number $d$, then Alice has to put the sets $[l, d - 1]$ and $[d + 1, r]$ (if existed) back to the set. Thus, there will be a moment that Alice picks the range $[l, d - 1]$ (if existed), and another moment to pick the ... | [
"brute force",
"dfs and similar",
"implementation",
"sortings"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int ntest;
cin >> ntest;
while (ntest--) {
int n;
cin >> n;
vector mark(n + 1, vector<bool>(n + 1));
vector<int> l(n), r(n);
for (int i = 0; i < n; ++i) {
... |
1623 | C | Balanced Stone Heaps | There are $n$ heaps of stone. The $i$-th heap has $h_i$ stones. You want to change the number of stones in the heap by performing the following process once:
- You go through the heaps from the $3$-rd heap to the $n$-th heap, in this order.
- Let $i$ be the number of the current heap.
- You can choose a number $d$ ($0... | The answer can be binary searched. That is, we can find the biggest number $x$, such that we can make all heap having at least $x$ stones. So our job here is to check if we can satisfy the said condition with a number $x$. Let's consider a reversed problem: we go from $1$ to $n - 2$, pick a number $d$ ($0 \le 3\cdot d ... | [
"binary search",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 201010;
int n;
int h[maxn];
bool check(int x) {
vector<int> cur_h(h, h + n);
for (int i = n - 1; i >= 2; --i) {
if (cur_h[i] < x) return false;
int d = min(h[i], cur_h[i] - x) / 3;
cur_h[i - 1] += d;
cur_h[i - 2] ... |
1623 | D | Robot Cleaner Revisit | The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $n$ rows and $m$ columns. The rows of the floor are... | In order to see how my solution actually works, let's solve this problem, the math way! You can skip to the "In general, ..." part if you don't really care about these concrete examples. First of all, let $\overline{p}$ be the probability of not cleaning, that is, the probability that the robot will not be able to clea... | [
"implementation",
"math",
"probabilities"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
// I swear that I type this everytime, so this is not count as template :))
#define defop(type, op) \
inline friend type operator op (type u, const type& v) { return u op ##= v; } \
type& operator op##=(const type& o)
template<int mod>
st... |
1623 | E | Middle Duplication | A binary tree of $n$ nodes is given. Nodes of the tree are numbered from $1$ to $n$ and the root is the node $1$. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote $l_u$ and $r_u$ as the left and the right child of the node $u$ respectively, $l_u = 0... | Firstly, we need to determine if a label should be duplicated at all. For example, in the string "bac", the characters 'b' and 'c' should never be duplicated, since duplicating them always make the result worse ("bbac" and "bacc" are both lexicographically greater than "bac"). This is because, next to the character 'b'... | [
"data structures",
"dfs and similar",
"greedy",
"strings",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 202020;
int n, k;
string c;
int l[maxn], r[maxn];
vector<int> in_order;
void build_in_order(int u) {
if (u == 0) return ;
build_in_order(l[u]);
in_order.push_back(u);
build_in_order(r[u]);
}
bool good[maxn];
bool duplicated[maxn];
//... |
1624 | A | Plus One on the Subset | Polycarp got an array of integers $a[1 \dots n]$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $a_1=a_2=\dots=a_n$).
- In one operation, he can take some indices in the array and increase the elements of the array... | Let's sort the numbers in ascending order. It becomes immediately clear that it is not profitable for us to increase the numbers that are equal to the last number (the maximum of the array). It turns out that every time you need to take such a subset of the array, in which all the numbers, except the maximums. And once... | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i, n) for (int i = 0; i < int(n); i++)
void solve() {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int MIN = INT_MAX;
int MAX = INT_MIN;
for (int i = 0; i < n; ++i) {
... |
1624 | B | Make AP | Polycarp has $3$ positive integers $a$, $b$ and $c$. He can perform the following operation \textbf{exactly once}.
- Choose a \textbf{positive} integer $m$ and multiply \textbf{exactly one} of the integers $a$, $b$ or $c$ by $m$.
Can Polycarp make it so that after performing the operation, the sequence of three numbe... | Let's iterate over the number that we want to multiply by $m$. How can we check that we can multiply the current number so that an AP is formed? Note that those $2$ numbers that we do not touch should form an AP themselves. For instance, let at the current operation we want somehow multiply the number $c$. Then $a = x_... | [
"implementation",
"math"
] | 900 | #include<bits/stdc++.h>
using namespace std;
void solveTest() {
int a, b, c;
cin >> a >> b >> c;
int new_a = b - (c - b);
if(new_a >= a && new_a % a == 0 && new_a != 0) {
cout << "YES\n";
return;
}
int new_b = a + (c - a)/2;
if(new_b >= b && (c-a)%2 == 0 && new_b % b == 0... |
1624 | C | Division by Two and Permutation | You are given an array $a$ consisting of $n$ positive integers. You can perform operations on it.
In one operation you can replace any element of the array $a_i$ with $\lfloor \frac{a_i}{2} \rfloor$, that is, by an integer part of dividing $a_i$ by $2$ (rounding down).
See if you can apply the operation some number o... | Let's sort the array $a$ in descending order of the values of its elements. Then let's create a logical array $used$, where $used[i]$ will have the value true if we already got element $i$ of the permutation we are looking for, and the value false otherwise. We loop through the elements of the array $a$ and assign $x =... | [
"constructive algorithms",
"flows",
"graph matchings",
"greedy",
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
vector<int>a(n), used(n + 1, false);
for(auto &i : a) cin >> i;
sort(a.begin(), a.end(), [] (int a, int b) {
return a > b;
});
bool ok = true;
for(auto &i : a){
int x = i;
while(x > n or ... |
1624 | D | Palindromes Coloring | You have a string $s$ consisting of lowercase Latin alphabet letters.
You can color some letters in colors from $1$ to $k$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.
Then you can swap any two symbols painted in the same color as many times as you w... | We will solve the problem greedily. First, we will try to add pairs of identical characters to palindromes. As long as there are at least $k$ pairs, let's add them. After that, it is no longer possible to add a couple of characters, but you can try to add one character in the middle. This can be done if there are at le... | [
"binary search",
"greedy",
"sortings",
"strings"
] | 1,400 | #include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAX_N = 2e5;
int main(int argc, char* argv[]) {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n, k;
string s;
cin >> n >> k >> s;
vector<in... |
1624 | E | Masha-forgetful | Masha meets a new friend and learns his phone number — $s$. She wants to remember it as soon as possible. The phone number — is a string of length $m$ that consists of digits from $0$ to $9$. The phone number may start with 0.
Masha already knows $n$ phone numbers (all numbers have the same length $m$). It will be eas... | The key idea is that any string of length greater than 3 can be obtained by concatenating strings of length $2$ or $3$. Then when reading the data, remember all occurring substring of length $2$ and $3$. There are at most $10^4$. Now we will count the dynamics on the prefix: $dp[i] = true$ if we can get the prefix of l... | [
"brute force",
"constructive algorithms",
"dp",
"hashing",
"implementation",
"strings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define sz(v) (int)v.size()
const int N = 1e4;
map<string, bool> have;
map<string, tuple<int,int,int>> pos;
void solve() {
int n, m; cin >> n >> m;
vector<bool> dp(m+1, false);
vector<int> pr(m+1);
vect... |
1624 | F | Interacdive Problem | \textbf{This problem is interactive.}
We decided to play a game with you and guess the number $x$ ($1 \le x < n$), where you know the number $n$.
You can make queries like this:
- + c: this command assigns $x = x + c$ ($1 \le c < n$) and then returns you the value $\lfloor\frac{x}{n}\rfloor$ ($x$ divide by $n$ and r... | After each query we know the $\lfloor\frac{x}{n}\rfloor$ value, then we need to find $x \mod n$ to find the current $x$ value. To find it, we will use a binary search. Suppose $x \mod n$ is in the $[l, r)$ half-interval, in order to understand which half it is in, we will make a query, select the middle $m$ of the half... | [
"binary search",
"constructive algorithms",
"interactive"
] | 2,000 | #include <bits/stdc++.h>
#define int long long
#define mp make_pair
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(143);
const int inf = 1e10;
const int M = 998244353;
con... |
1624 | G | MinOr Tree | Recently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of $n$ vertices and $m$ edges for his birthday.
Vlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum poss... | We need to minimize the result of the bitwise operation, so for convenience, we represent the answer as a mask. Firstly, let's assume that this mask is composed entirely of ones. Let's go from the most significant bit to the least significant one and try to reduce the answer. To understand whether it is possible to rem... | [
"bitmasks",
"dfs and similar",
"dsu",
"graphs",
"greedy"
] | 1,900 | #include <bits/stdc++.h>
#define int long long
#define mp make_pair
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(143);
const int inf = 1e9;
const int M = 998244353;
cons... |
1625 | A | Ancient Civilization | Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.
They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and e... | Note that the problem can be solved independently for each bit, as the bits don't influence each other. Set the $i$th bit to zero if the numbers in the array contain more zeros than ones in the $i$th bit. Otherwise, set it to one. | [
"bitmasks",
"greedy",
"math"
] | 800 | null |
1625 | B | Elementary Particles | Martians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.
A group of scientists conducts experiments to build a fa... | Note the following fact. For each optimal pair of harmonious strings, it's true that the right string ends on the last character. Proof: suppose it's wrong. Then, we can expand the strings to the right by one character, and they will remain harmonious. Now, prove the following statement, that will help us to solve this... | [
"brute force",
"greedy",
"sortings"
] | 1,100 | null |
1625 | C | Road Optimization | The Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.
One of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the rever... | First you need to understand that this problem must be solved with dynamic programming. Let $dp_{i,j}$ is the minimum time to drive between the two cities, if we consider first $i$ signs and have already removed $j$ signs. We also assume that the $i$th sign is taken. Then, the initial state is: $dp_{0,0} = 0$, $dp_{i,0... | [
"dp"
] | 1,700 | null |
1625 | D | Binary Spiders | Binary Spiders are species of spiders that live on Mars. These spiders weave their webs to defend themselves from enemies.
To weave a web, spiders join in pairs. If the first spider in pair has $x$ legs, and the second spider has $y$ legs, then they weave a web with durability $x \oplus y$. Here, $\oplus$ means bitwis... | To solve the problem, we need the following well-known fact. Suppose we have a set of numbers and we need to find minimal possible $xor$ over all the pairs. It is true that, if we sort the numbers in non-descending order, the answer will be equal to minimal $xor$ over neighboring numbers. We need the minimal $xor$ to b... | [
"bitmasks",
"data structures",
"implementation",
"math",
"sortings",
"trees"
] | 2,300 | null |
1625 | E1 | Cats on the Upgrade (easy version) | This is the easy version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version.
"Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice a... | First, we need to make the input string an RBS. Consider one of the possible ways to do it. First, we keep the stack of all the opening brackets. We remove the bracket from the stack if we encounter the corresponding closing bracket. If there is an unpaired closing bracket or an opening bracket which is not removed, th... | [
"brute force",
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"graphs",
"trees"
] | 2,500 | null |
1625 | E2 | Cats on the Upgrade (hard version) | This is the hard version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version.
"Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice a... | Now, we need to see how to handle removal queries in this task. Build an SQRT decomposition in the following way. We will rebuild the entire tree after each $\sqrt{n}$ queries and recalculate the DP. Between the rebuilds, we hold a list of removed leaves. Now look how we can recalculate the answer if some leaves are re... | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"trees"
] | 2,800 | null |
1626 | A | Equidistant Letters | You are given a string $s$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.
Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to a... | Let's consider a very special case of equal distances. What if all distances were equal to $1$? It implies that if some letter appears exactly twice, both occurrences are placed right next to each other. That construction can be achieved if you sort the string, for example: first right down all letters 'a', then all le... | [
"constructive algorithms",
"sortings"
] | 800 | for _ in range(int(input())):
print(''.join(sorted(input()))) |
1626 | B | Minor Reduction | You are given a decimal representation of an integer $x$ without leading zeros.
You have to perform the following reduction on it \textbf{exactly once}: take two neighboring digits in $x$ and replace them with their sum without leading zeros (if the sum is $0$, it's represented as a single $0$).
For example, if $x = ... | Let's think how a reduction changes the length of $x$. There are two cases. If two adjacent letters sum up to $10$ or greater, then the length doesn't change. Otherwise, the length decreases by one. Obviously, if there exists a reduction that doesn't change the length, then it's better to use it. Which among such reduc... | [
"greedy",
"strings"
] | 1,100 | for _ in range(int(input())):
x = [ord(c) - ord('0') for c in input()]
n = len(x)
for i in range(n - 2, -1, -1):
if x[i] + x[i + 1] >= 10:
x[i + 1] += x[i] - 10
x[i] = 1
break
else:
x[1] += x[0]
x.pop(0)
print(''.join([chr(c + ord('0')) for c in x])) |
1626 | C | Monsters And Spells | Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.
The level he's currently on contains $n$ monsters. The $i$-th of them appears $k_i$ seconds after the start of the level and has $h_i$ health points. As an additional c... | Consider the problem with $n=1$. There is a single monster with some health $h$ that appears at some second $k$. In order to kill it, we have to wind up our spell until it has damage $h$. So we have to use it from second $k - h + 1$ to second $k$. Look at it as a segment $[k - h + 1; k]$ on a timeline. Actually, to avo... | [
"binary search",
"data structures",
"dp",
"greedy",
"implementation",
"math",
"two pointers"
] | 1,700 | for _ in range(int(input())):
n = int(input())
k = list(map(int, input().split()))
h = list(map(int, input().split()))
st = []
for i in range(n):
st.append([k[i] - h[i], k[i]])
st.sort()
l, r = -1, -1
ans = 0
for it in st:
if it[0] >= r:
ans += (r - l) * (r - l + 1) // 2
l, r = it
... |
1626 | D | Martial Arts Tournament | Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.
In particular, that implies that the number of participants in each division should be a power... | Sort the weights, now choosing $x$ and $y$ will split the array into three consecutive segments. Consider a naive solution to the problem. You can iterate over the length of the first segment and the second segment. The third segment will include everyone remaining. Now you have to check if there exist some $x$ and $y$... | [
"binary search",
"brute force",
"greedy",
"math"
] | 2,100 | calc = 1
nxt = [1, 0]
for _ in range(int(input())):
n = int(input())
a = sorted(list(map(int, input().split())))
while calc <= n:
for i in range(calc):
nxt.append(calc - i - 1)
calc *= 2
left = []
for i in range(n + 1):
if i == 0 or i == n or a[i] != a[i - 1]:
left.append(i)
else:... |
1626 | E | Black and White Tree | You are given a tree consisting of $n$ vertices. Some of the vertices (at least two) are black, all the other vertices are white.
You place a chip on one of the vertices of the tree, and then perform the following operations:
- let the current vertex where the chip is located is $x$. You choose a black vertex $y$, an... | I think there are some ways to solve this problem with casework, but let's try to come up with an intuitive and easy-to-implement approach. It's always possible to move closer to some black vertex, no matter in which vertex you are currently and which black vertex was used in the previous operation. However, sometimes ... | [
"dfs and similar",
"greedy",
"trees"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
const int N = 300043;
vector<int> g[N];
int cnt[N];
int c[N];
vector<int> g2[N];
int par[N];
int used[N];
void dfs(int x, int p = -1)
{
par[x] = p;
for(auto y : g[x])
if(y != p)
{
dfs(y, x);
cnt[x] += cnt[y];
}
... |
1626 | F | A Random Code Problem | You are given an integer array $a_0, a_1, \dots, a_{n - 1}$, and an integer $k$. You perform the following code with it:
\begin{verbatim}
long long ans = 0; // create a 64-bit signed variable which is initially equal to 0
for(int i = 1; i <= k; i++)
{
int idx = rnd.next(0, n - 1); // generate a random integer between ... | I think it's easier to approach this problem using combinatorics instead of probability theory methods, so we'll calculate the answer as "the sum of values of ans over all ways to choose the index on each iteration of the loop". If a number $a_{idx}$ is chosen on the iteration $i$ of the loop, then it is reduced to the... | [
"combinatorics",
"dp",
"math",
"number theory",
"probabilities"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int L = 720720;
int add(int x, int y, int m = MOD)
{
x += y;
if(x >= m) x -= m;
return x;
}
int mul(int x, int y, int m = MOD)
{
return (x * 1ll * y) % m;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)... |
1627 | A | Not Shading | There is a grid with $n$ rows and $m$ columns. Some cells are colored black, and the rest of the cells are colored white.
In one operation, you can select some \textbf{black} cell and do \textbf{exactly one} of the following:
- color all cells in its row black, or
- color all cells in its column black.
You are given... | There are several cases to consider: If all the cell are white, then it is impossible to perform any operations, so you cannot make any cell black. The answer is $-1$. If the cell in row $r$ and column $c$ is already black, then we don't need to perform any operations. The answer is $0$. If any of the cells in row $r$ ... | [
"constructive algorithms",
"implementation"
] | 800 | for t in range(int(input())):
n, m, r, c = map(int, input().split())
a = [list(input()) for i in range(n)]
if "B" not in str(a):
print(-1)
continue
print(2 - ("B" in a[r-1] + list([*zip(*a)][c-1])) - (a[r-1][c-1] == 'B')) |
1627 | B | Not Sitting | Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $n \times m$ grid. The seat in row $r$ and column $c$ is denoted by $(r, c)$, and the distance between two seats $(a,b)$ and $(c,d)$ is $|a-c| + |b-d|$.
As t... | Let's denote Rahul's seat as $(a, b)$ and Tina's seat as $(c, d)$. Notice that the in the distance between their seats, $|a-c| + |b-d|$, $|a-c|$ and $|b-d|$ are independent of each other, i.e. both the $x$-coordinate and $y$-coordinate of Tina's seat are independent. From the answer to the hint above, we can see that t... | [
"games",
"greedy",
"sortings"
] | 1,300 | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
for t in range(int(input())):
n, m = map(int, input().split())
print(*sorted(max(x, n-1-x) + max(y, m-1-y) for x in range(n) for y in range(m))) |
1627 | C | Not Assigning | You are given a tree of $n$ vertices numbered from $1$ to $n$, with edges numbered from $1$ to $n-1$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.
A prime tree is a tree where the weight of every path ... | Let us first see when a valid assignment does not exist. Claim. If any vertex has 3 or more edges adjacent to it, no valid assignment exists. Proof. Consider a graph where a vertex has edges to three other vertices with weights $x$, $y$ and $z$ respectively. For a valid assignment, $x$, $y$ and $z$ need to be primes th... | [
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] | 1,400 | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
for t in range(int(input())):
n = int(input())
graph = [[] for __ in range(n + 1)]
ans = [-1] * (n - 1)
for i in range(n - 1):
x, y = map(int, input().split())
graph[x] += [(y, i)]
graph[y] += [(x, i)]
if max(le... |
1627 | D | Not Adding | You have an array $a_1, a_2, \dots, a_n$ consisting of $n$ \textbf{distinct} integers. You are allowed to perform the following operation on it:
- Choose two elements from the array $a_i$ and $a_j$ ($i \ne j$) such that $\gcd(a_i, a_j)$ is not present in the array, and add $\gcd(a_i, a_j)$ to the end of the array. Her... | Note that the $\gcd$ of two numbers cannot exceed their maximum. Let the maximum element of the array be $A$. So for every number from $1$ to $A$, we try to check whether that element can be included in the array after performing some operations or not. How to check for a particular number $x$? For $x$ to be in the fin... | [
"brute force",
"dp",
"math",
"number theory"
] | 1,900 | import io, os
from math import gcd
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int, input().split()))
MAXN = 1000000
present = [False] * (MAXN + 1)
for each in a:
present[each] = True
ans = 0
for i in range(MAXN, 0, -1):
if present[i]: continue
g = 0
for ... |
1627 | E | Not Escaping | Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.
The building consists of $n$ floors, each with $m$ rooms each. ... | The building plan of the input consists of $n \cdot m$ rooms, which in the worst case is $10^{10}$ however, most of these rooms are unimportant to us. We can instead use a much reduced version of the building consisting of at most $2k + 2$ rooms, both endpoints of each ladder, as well as our starting and target rooms. ... | [
"data structures",
"dp",
"implementation",
"shortest paths",
"two pointers"
] | 2,200 | import sys, os, io
from collections import defaultdict
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = 5 * 10**16
for _ in range(int(input())):
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
go_to = defaultdict(list)
coords = set()
coords.add((1, 1))
... |
1627 | F | Not Splitting | There is a $k \times k$ grid, where $k$ is even. The square in row $r$ and column $c$ is denoted by $(r,c)$. Two squares $(r_1, c_1)$ and $(r_2, c_2)$ are considered adjacent if $\lvert r_1 - r_2 \rvert + \lvert c_1 - c_2 \rvert = 1$.
An array of adjacent pairs of squares is called strong if it is possible to cut the ... | Claim. Any cut that splits the square into two congruent parts is rotationally symmetric about the center by $180^{\circ}$. Proof. It is a special case when the cut is a vertical or horizontal line. Assume otherwise. Then: One piece has a row containing more than $\frac{k}{2}$, but less than $k$ squares. One piece has ... | [
"geometry",
"graphs",
"greedy",
"implementation",
"shortest paths"
] | 2,700 | import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from heapq import heappop, heappush
for _ in range(int(input())):
q, n = map(int, input().split())
graph = [[[] for j in range(n + 1)] for i in range(n + 1)]
for x in range(n + 1):
for y in range(n + 1):
if x - ... |
1628 | A | Meximum Array | Mihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.
Given an array $a$ of $n$ non-negative integers, Mihai wants to create \textbf{a new array $b$} that is formed in the following way:
While $a$ is not empty:
- Choose an integer $k$ ($1 \leq k \leq |a|$).
- Ap... | The splitting points can be picked greedily. Firstly, find the MEX of all suffixes, this can be easily done in $O(n \cdot log(n))$ or $O(n)$. Instead of removing elements, we consider that we need to split the array into some number of subarrays. Let $p$ be the index we are currently at and MEX($l, r$) - the MEX of the... | [
"binary search",
"constructive algorithms",
"greedy",
"implementation",
"math",
"two pointers"
] | 1,400 | null |
1628 | B | Peculiar Movie Preferences | Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.
You are given a list $s$ of $n$ non-empty strings of length \textbf{at most $3$}, representing the scenes of Mihai's movie.
A subsequence of $s$ is call... | Because of the low constraints on the lengths of the strings, we can prove that it's enough to pair at most $2$ strings to form a palindrome. <proof only checking pairs is enough> Let's assume there is a awesome subsequence of the form xyz where x and z are single strings from s, and y is anything. If x and z are the s... | [
"greedy",
"strings"
] | 1,700 | null |
1628 | C | Grid Xor | Note: The XOR-sum of set $\{s_1,s_2,\ldots,s_m\}$ is defined as $s_1 \oplus s_2 \oplus \ldots \oplus s_m$, where $\oplus$ denotes the bitwise XOR operation.
After almost winning IOI, Victor bought himself an $n\times n$ grid containing integers in each cell. \textbf{$n$ is an even integer.} The integer in the cell in ... | Let's denote count($i,j$) the amount of times the cell ($i,j$) contributed in queries. We notice that count($i,j$) must be odd for all cells ($i,j$). There are multiple possible solutions for this problem. In the editorial we will describe two of them. <first solution> The following construction satisfies the condition... | [
"constructive algorithms",
"greedy",
"implementation",
"interactive",
"math"
] | 2,300 | null |
1628 | D1 | Game on Sum (Easy Version) | \textbf{This is the easy version of the problem. The difference is the constraints on $n$, $m$ and $t$. You can make hacks only if all versions of the problem are solved.}
Alice and Bob are given the numbers $n$, $m$ and $k$, and play a game as follows:
The game has a score that Alice tries to maximize, and Bob tries... | What is the answer for $n = 2$, $m = 1$? Let's call the number Alice picks on the first turn $x$. If $x$ is small, Bob can add it, and then Alice will have to pick $0$ on the last turn since Bob will definitely subtract it from the score if it isn't $0$, meaning the score ends up being $x$. If Alice picks a big number,... | [
"combinatorics",
"dp",
"games",
"math"
] | 2,100 | null |
1628 | D2 | Game on Sum (Hard Version) | \textbf{This is the hard version of the problem. The difference is the constraints on $n$, $m$ and $t$. You can make hacks only if all versions of the problem are solved.}
Alice and Bob are given the numbers $n$, $m$ and $k$, and play a game as follows:
The game has a score that Alice tries to maximize, and Bob tries... | We have base cases $DP[i][0] = 0$ $DP[i][i] = k\cdot i$ And transition $DP[i][j] = (DP[i-1][j-1]+DP[i-1][j])/2$ Check the explanation for the easy version to see why. This $DP$ can be optimized by looking at contributions from the base cases. If we draw the $DP$ states on a grid and ignore the division by $2$ in the tr... | [
"combinatorics",
"dp",
"games",
"math"
] | 2,400 | null |
1628 | E | Groceries in Meteor Town | Mihai lives in a town where meteor storms are a common problem. It's annoying, because Mihai has to buy groceries sometimes, and getting hit by meteors isn't fun. Therefore, we ask you to find the most dangerous way to buy groceries so that we can trick him to go there.
The town has $n$ buildings numbered from $1$ to ... | Consider the edge with the greatest weight. Any path going through that edge will have weight equal to the weight of that edge. If we delete that edge from the tree, a path going through that edge in the original tree has one endpoint in each component that results from the removal of the edge. Consider some query $x$ ... | [
"binary search",
"data structures",
"dsu",
"trees"
] | 3,100 | null |
1628 | F | Spaceship Crisis Management | NASA (Norwegian Astronaut Stuff Association) is developing a new steering system for spaceships. But in its current state, it wouldn't be very safe if the spaceship would end up in a bunch of space junk. To make the steering system safe, they need to answer the following:
Given the target position $t = (0, 0)$, a set ... | The exit position at a specific segment is always the same, only the exit direction changes depending on which angle the spaceship comes in at. Therefore, if we know the set of directions that are good to hit a segment at, we know if a path that hits the segment is good or not. Note that it's only useful to consider di... | [
"binary search",
"data structures",
"geometry",
"sortings"
] | 3,500 | null |
1629 | A | Download More RAM | Did you know you can download more RAM? There is a shop with $n$ different pieces of software that increase your RAM. The $i$-th RAM increasing software takes $a_i$ GB of memory to run (\textbf{temporarily, once the program is done running, you get the RAM back}), and gives you an additional $b_i$ GB of RAM (permanentl... | Using some software is never bad. It always ends up increasing your RAM if you can use it. And for any possible order to use a set of software in, they all result in the same amount RAM in the end. So we can greedily go through the list, using software if you have enough RAM for it. After going through the list, your R... | [
"brute force",
"greedy",
"sortings"
] | 800 | null |
1629 | B | GCD Arrays | Consider the array $a$ composed of all the integers in the range $[l, r]$. For example, if $l = 3$ and $r = 7$, then $a = [3, 4, 5, 6, 7]$.
Given $l$, $r$, and $k$, is it possible for $\gcd(a)$ to be greater than $1$ after doing the following operation at most $k$ times?
- Choose $2$ numbers from $a$.
- Permanently r... | For the $GCD$ of the whole array to be greater than $1$, each of the elements must have a common prime factor, so we need to find the prime factor that's the most common in the array and merge the elements that have this prime factor with those who don't, the answer being the size of the array - number of occurrences o... | [
"greedy",
"math",
"number theory"
] | 800 | null |
1630 | A | And Matching | You are given a set of $n$ ($n$ is always a power of $2$) elements containing all integers $0, 1, 2, \ldots, n-1$ exactly once.
Find $\frac{n}{2}$ pairs of elements such that:
- Each element in the set is in exactly one pair.
- The sum over all pairs of the bitwise AND of its elements must be exactly equal to $k$. Fo... | Try to find a pairing such that $\sum\limits_1^{n/2}{a_i\&{b_i}}=0$ Try to find a pairing for $k>0$ by changing only a few elements from the previous pairing. Let's define $c(x)$, the compliment of $x$, as the number $x$ after changing all bits 0 to 1 and vice versa, for example $c(110010_2) = 001101_2$. It can be show... | [
"bitmasks",
"constructive algorithms"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
int c(int x,int n){
return ( x ^ ( n - 1 ) );
}
int main(){
int tc;
cin >> tc;
while( tc-- ){
int n, k;
cin >> n >> k;
vector<int> a(n/2), b(n/2);
if( k == 0 ){
for(int i=0; i<n/2; i++){
a[i] =... |
1630 | B | Range and Partition | Given an array $a$ of $n$ integers, find a range of values $[x, y]$ ($x \le y$), and split $a$ into \textbf{exactly} $k$ ($1 \le k \le n$) subarrays in such a way that:
- Each subarray is formed by several continuous elements of $a$, that is, it is equal to $a_l, a_{l+1}, \ldots, a_r$ for some $l$ and $r$ ($1 \leq l \... | Focus on how to solve the problem for a fixed interval $[x,y]$ Think about the numbers inside the interval as $+1$, and the other numbers as $-1$ Try to relate a partition into valid subarrays with an increasing sequence of the prefix sums array Note that if some value $x$ ($x>0$) appears on the prefix sums array, $x-1... | [
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"two pointers"
] | 1,800 | #include<bits/stdc++.h>
using namespace std;
int main() {
int tc;
cin >> tc;
while( tc-- ){
int n, k;
cin >> n >> k;
vector<int> a(n), sorted_a(n);
for(int i=0; i<n; i++){
cin >> a[i];
sorted_a[i] = a[i];
}
sort(sorted_a.begin... |
1630 | C | Paint the Middle | You are given $n$ elements numbered from $1$ to $n$, the element $i$ has value $a_i$ and color $c_i$, initially, $c_i = 0$ for all $i$.
The following operation can be applied:
- Select three elements $i$, $j$ and $k$ ($1 \leq i < j < k \leq n$), such that $c_i$, $c_j$ and $c_k$ are all equal to $0$ and $a_i = a_k$, t... | Think about all occurrences of some element, what occurrences are important? Think about the first and last occurrence of each element as a segment. Think about the segments that at least one of its endpoints will end up with $c_i = 0$. For each $x$ such that all the elements $a_1, a_2, ..., a_x$ are different from $a_... | [
"dp",
"greedy",
"sortings",
"two pointers"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
template <typename Tnode,typename Tup>
struct ST{
vector<Tnode> st;
int sz;
ST(int n){
sz = n;
st.resize(4*n);
}
Tnode merge_(Tnode a, Tnode b){
Tnode c;
/// Merge a and b into c
c = min( a , b );
retu... |
1630 | D | Flipping Range | You are given an array $a$ of $n$ integers and a set $B$ of $m$ positive integers such that $1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor$ for $1\le i\le m$, where $b_i$ is the $i$-th element of $B$.
You can make the following operation on $a$:
- Select some $x$ such that $x$ appears in $B$.
- Select an interval from ... | What is the size of the smallest subarray that it is possible to multiply by $-1$ using some operations? Let $s$ be a string such that $s_i=0$ if that element is multiplied by $-1$ or $s_i=1$ otherwise, what such $s$ are reachable? Think about the parity of the sum of all $s_i$ such that $i\mod{g}=constant$, where $g$ ... | [
"constructive algorithms",
"dp",
"greedy",
"number theory"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--)
{
int n,m;
cin >> n >> m;
vector<int> a(n),b(m);
for(int i=0;i<n;i++)
cin >> a[i];
int g=... |
1630 | E | Expected Components | Given a cyclic array $a$ of size $n$, where $a_i$ is the value of $a$ in the $i$-th position, \textbf{there may be repeated values}. Let us define that a permutation of $a$ is equal to another permutation of $a$ if and only if their values are the same for each position $i$ or we can transform them to each other by per... | Burnside's lemma Think about an easy way to count the number of components in a cyclic array. The number of components in a cyclic array is equal to the number of adjacent positions with different values. The problem can be solved by applying Burnside's lemma. The number of different permutations of the cyclic array $a... | [
"combinatorics",
"math",
"number theory",
"probabilities"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 100;
const int MOD = 998244353;
long long fact[MAXN];
long long F[MAXN];
long long qpow(long long a, long long b)
{
long long res = 1;
while(b)
{
if(b&1)res = res*a%MOD;
a = a*a%MOD;
b /= 2;
}
return r... |
1630 | F | Making It Bipartite | You are given an undirected graph of $n$ vertices indexed from $1$ to $n$, where vertex $i$ has a value $a_i$ assigned to it and all values $a_i$ are \textbf{different}. There is an edge between two vertices $u$ and $v$ if either $a_u$ divides $a_v$ or $a_v$ divides $a_u$.
Find the minimum number of vertices to remove... | Think about the directed graph where there is an directed edge from $a$ to $b$ if and only if $b|a$ Let us define the above graph as $G$, make a duplicate graph $G'$ from $G$, and then add directed edges $(x', x)$ for each node $x'$ of the graph $G'$. What happens in this graph? Maximum Antichain First of all, let's an... | [
"flows",
"graph matchings",
"graphs",
"number theory"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
struct HOPCROFT_KARP
{
int n, m;
vector<vector<int>> adj;
vector<int> mu, mv, level, que;
HOPCROFT_KARP(int n, int m) : n(n), m(m), adj(n), mu(n, -1), mv(m, -1), level(n), que(n) {}
void add_edge(int u, int v)
{
adj[u].push_back(v);
}... |
1631 | A | Min Max Swap | You are given two arrays $a$ and $b$ of $n$ positive integers each. You can apply the following operation to them any number of times:
- Select an index $i$ ($1\leq i\leq n$) and swap $a_i$ with $b_i$ (i. e. $a_i$ becomes $b_i$ and vice versa).
Find the \textbf{minimum} possible value of $\max(a_1, a_2, \ldots, a_n) ... | Think about how $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$ will contribute to the answer. The maximum of one array is always $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. How should you minimize then? Let $m_1 = \max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. The answer will always be $m_1 \cdot m_2$ where $m_2$ is ... | [
"greedy"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int calc_max(vector<int> a){
int res = 0;
for( auto i : a )
res = max( res , i );
return res;
}
int main(){
int tc;
cin >> tc;
while( tc-- ){
int n;
cin >> n;
vector<int> a(n), b(n);
for( auto &i : a )
... |
1631 | B | Fun with Even Subarrays | You are given an array $a$ of $n$ elements. You can apply the following operation to it any number of times:
- Select some subarray from $a$ of even size $2k$ that begins at position $l$ ($1\le l \le l+2\cdot{k}-1\le n$, $k \ge 1$) and for each $i$ between $0$ and $k-1$ (inclusive), assign the value $a_{l+k+i}$ to $a_... | It is not possible to modify $a_n$ using the given operation. Think about the leftmost $x$ such that $a_x \neq a_n$. For simplicity, let $b_1, b_2, ..., b_n = a_n, a_{n-1}, ..., a_1$ (let $b$ be $a$ reversed). The operation transforms to select a subarray $[l, r]$ of length $2\cdot{k}$, so $k = \frac{r-l+1}{2}$, then f... | [
"dp",
"greedy"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int tc;
cin >> tc;
while(tc--)
{
int n;
cin >> n;
vector<int> a(n+1);
for(int i=1; i<=n; i++)
cin >> a[i];
vector<int> b = a;
reverse(b.begin()+1,b.end());
int ans = 0, x = ... |
1632 | A | ABC | Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $s$ as input. However, they soon found out that if some substring $t$ of $s$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $s$ so tha... | Only a few strings have the answer "YES". For $n \ge 3$, the answer is "NO". Let $n \ge 3$ and the resulting string be $a$. For there to be no palindromes of length greater than $1$, at least all of these inequalities must be true: $a_1 \neq a_2$, $a_2 \neq a_3$, and $a_1 \neq a_3$. Since our string is binary, this is ... | [
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
string s;
cin >> s;
if(n > 2 || s == "11" || s == "00") {
cout << "NO\n";
} else {
cout << "YES\n";
}
}
} |
1632 | B | Roof Construction | It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $n$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $p$ of integers from $0$ to $n - 1$, where $p_i$ is the height of the $i$-th p... | The cost of construction is a power of two. The cost of construction is $2 ^ k$, where $k$ is the highest set bit in $n - 1$. Let $k$ be the highest set bit in $n - 1$. There will always be a pair of adjacent elements where one of them has the $k$-th bit set and the other one doesn't, so the cost is at least $2^k$. A s... | [
"bitmasks",
"constructive algorithms"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
int k = 0;
while((1 << (k + 1)) <= n - 1) ++k;
for(int i = (1 << k) - 1; i >= 0; i--) {
cout << i << ' ';
}
for(int i = (1 << k); ... |
1632 | C | Strange Test | Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich.
Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $a$ and $b$ ($a < b$). After that, the student can apply any of the follo... | It is optimal to apply the third operation at most once. It is optimal to apply the third operation at most once, because is does not decrease $a$ and always makes $b \le a$. This means that after we use it, we can only apply the second operation. If we don't apply the third operation, the answer is $b - a$. Suppose we... | [
"binary search",
"bitmasks",
"brute force",
"dp",
"math"
] | 1,600 | for _ in range(int(input())):
a, b = map(int, input().split())
ans = b - a
for a1 in range(a, b):
b1 = 0
for i in range(21, -1, -1):
if (b >> i) & 1:
b1 ^= (1 << i)
else:
if (a1 >> i) & 1:
b1 ^= (1 << i)
... |
1632 | D | New Year Concert | New Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.
There are $n$ classes in the school, numbered from $1$ to $n$, the $i$-th class has prepared a scene of length $a_i$ minutes.
As the main one responsible for holding the concert, Idnar knows that if a c... | Let's call a segment $[l, r]$ bad if $\gcd(a_l \ldots a_r) = r - l + 1$. There at most $n$ bad segments. For a fixed $l$, as $r$ increases, $\gcd(a_l \ldots a_r)$ does not increase. Suppose you change $a_i$ into a big prime. How does this affect the bad segments? Read the hints above. Let's find all of the bad segments... | [
"binary search",
"data structures",
"greedy",
"math",
"number theory",
"two pointers"
] | 2,000 | from math import gcd
n = int(input())
a = list(map(int, input().split()))
t = [0] * (4 * n)
def build(v, tl, tr):
global t
if tl == tr - 1:
t[v] = a[tl]
else:
tm = (tl + tr) // 2
build(2*v + 1, tl, tm)
build(2*v + 2, tm, tr)
t[v] = gcd(t[2*v + 1], t[2*v + 2])
def query(v, tl, tr, l, r):
if l >... |
1632 | E2 | Distance Tree (hard version) | \textbf{This version of the problem differs from the previous one only in the constraint on $n$}.
A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.
You are given a weig... | It is optimal to add edges of type $(1, v)$. Try to check if for a fixed $x$ the answer is at most $ans$. For a fixed $x$ and answer $ans$, find the distance between nodes that have $depth_v > ans$. For each node, find two children with the deepest subtrees. Read the hints above. Let $f_{ans}$ be the maximum distance b... | [
"binary search",
"dfs and similar",
"shortest paths",
"trees"
] | 2,700 | import sys
from types import GeneratorType
g = []
d = []
n = 0
inp = list(sys.stdin)
def dfs_from_hell():
st = [[], [0, 0, 0, -1, 0, 0]]
while len(st) > 1:
if len(st[-1]) == 7:
if st[-1][-1] > st[-1][1]:
st[-1][2] = st[-1][1]
st[-1][1] = st[-1][-1]
elif st[-1][-1] > st[-1][2]:
st[-1][2] =... |
1633 | A | Div. 7 | You are given an integer $n$. You have to change the minimum number of digits in it in such a way that the resulting number \textbf{does not have any leading zeroes} and \textbf{is divisible by $7$}.
If there are multiple ways to do it, print any of them. If the given number is already divisible by $7$, leave it uncha... | A lot of different solutions can be written in this problem. The model solution relies on the fact that every $7$-th integer is divisible by $7$, and it means that there is always a way to change the last digit of $n$ (or leave it unchanged) so that the result is divisible by $7$. So, if $n$ is already divisible by $7$... | [
"brute force"
] | 800 | t = int(input())
for i in range(t):
n = int(input())
if n % 7 == 0:
print(n)
else:
ans = -1
for j in range(10):
if (n - n % 10 + j) % 7 == 0:
ans = n - n % 10 + j
print(ans) |
1633 | B | Minority | You are given a string $s$, consisting only of characters '0' and '1'.
You have to choose a contiguous substring of $s$ and remove all occurrences of the character, which is a strict minority in it, from the substring.
That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove... | Let's try to estimate the maximum possible answer. Best case, you will be able to remove either all zeros or all ones from the entire string. Whichever has the least occurrences, can be the answer. If the amounts of zeros and ones in the string are different, this bound is actually easy to reach: just choose the substr... | [
"greedy"
] | 800 | for _ in range(int(input())):
s = input()
print(min((len(s) - 1) // 2, s.count('0'), s.count('1'))) |
1633 | C | Kill the Monster | Monocarp is playing a computer game. In this game, his character fights different monsters.
A fight between a character and a monster goes as follows. Suppose the character initially has health $h_C$ and attack $d_C$; the monster initially has health $h_M$ and attack $d_M$. The fight consists of several steps:
- the ... | First of all, let's understand how to solve the problem without upgrades. To do this, it is enough to compare two numbers: $\left\lceil\frac{h_M}{d_C}\right\rceil$ and $\left\lceil\frac{h_C}{d_M}\right\rceil$ - the number of attacks that the character needs to kill the monster and the number of attacks that the monster... | [
"brute force",
"math"
] | 1,100 | for _ in range(int(input())):
hc, dc = map(int, input().split())
hm, dm = map(int, input().split())
k, w, a = map(int, input().split())
for i in range(k + 1):
nhc = hc + i * a
ndc = dc + (k - i) * w
if (hm + ndc - 1) // ndc <= (nhc + dm - 1) // dm:
print("YES")
... |
1633 | D | Make Them Equal | You have an array of integers $a$ of size $n$. Initially, all elements of the array are equal to $1$. You can perform the following operation: choose two integers $i$ ($1 \le i \le n$) and $x$ ($x > 0$), and then increase the value of $a_i$ by $\left\lfloor\frac{a_i}{x}\right\rfloor$ (i.e. make $a_i = a_i + \left\lfloo... | Let's calculate $d_i$ - the minimum number of operations to get the number $i$ from $1$. To do this, it is enough to use BFS or dynamic programming. Edges in the graph (transitions in dynamic programming) have the form $\left(i, i + \left\lfloor\frac{i}{x}\right\rfloor\right)$ for all $1 \le x \le i$. Now the problem i... | [
"dp",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 1001;
int main() {
vector<int> d(N, N);
d[1] = 0;
for (int i = 1; i < N; ++i) {
for (int x = 1; x <= i; ++x) {
int j = i + i / x;
if (j < N) d[j] = min(d[j], d[i] + 1);
}
}
int t;
cin >> t;
while (t--) {
int n, k;
... |
1633 | E | Spanning Tree Queries | You are given a connected weighted undirected graph, consisting of $n$ vertices and $m$ edges.
You are asked $k$ queries about it. Each query consists of a single integer $x$. For each query, you select a spanning tree in the graph. Let the weights of its edges be $w_1, w_2, \dots, w_{n-1}$. The cost of a spanning tre... | Consider a naive solution using Kruskal's algorithm for finding MST. Given some $x$, you arrange the edges in the increasing order of $|w_i - x|$ and process them one by one. Look closely at the arrangements. At $x=0$ the edges are sorted by $w_i$. How does the arrangement change when $x$ increases? Well, some edges sw... | [
"binary search",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"math",
"sortings",
"trees"
] | 2,400 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct edge{
int v, u, w;
};
vector<int> pr, rk;
int getp(int a){
return a == pr[a] ? a : pr[a] = getp(pr[a]);
}
bool unite(int a, int b){
a = getp(a), b = getp(b);
if (a == b) return false;
if (rk[a] < rk[b]) s... |
1633 | F | Perfect Matching | You are given a tree consisting of $n$ vertices (numbered from $1$ to $n$) and $n-1$ edges (numbered from $1$ to $n-1$). Initially, all vertices except vertex $1$ are inactive.
You have to process queries of three types:
- $1$ $v$ — activate the vertex $v$. It is guaranteed that the vertex $v$ is inactive before this... | Let's root the tree at vertex $1$ and try to analyze when a tree contains a perfect matching. If we want to find the maximum matching in a tree, we can use some greedy approaches like "take a leaf of the tree, match it with its parent and remove both vertices, repeat this process until only isolated vertices remain". I... | [
"data structures",
"divide and conquer",
"interactive",
"trees"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
typedef pair<long long, int> val;
#define x first
#define y second
const int N = 200043;
val operator +(const val& a, const val& b)
{
return make_pair(a.x + b.x, a.y + b.y);
}
val operator -(const val& a, const val& b)
{
return make_pair(a.x - b.x, a.y -... |
1634 | A | Reverse and Concatenate | \begin{quote}
Real stupidity beats artificial intelligence every time.
\hfill — Terry Pratchett, Hogfather, Discworld
\end{quote}
You are given a string $s$ of length $n$ and a number $k$. Let's denote by $rev(s)$ the reversed string $s$ (i.e. $rev(s) = s_n s_{n-1} ... s_1$). You can apply one of the two kinds of oper... | If $k = 0$, the answer is $1$. Otherwise, consider two cases: The string is a palindrome (that is, $s = rev(s)$). Then $rev(s) + s = s + rev(s) = s + s$, so both operations will replace $s$ by the string $s+s$, which is also a palindrome. Then for any $k$ the answer is $1$. Otherwise $s \ne rev(s)$. Then after the firs... | [
"greedy",
"strings"
] | 800 | q = int(input())
for _ in range(q):
n, k = map(int, input().split())
s = input()
if s == s[::-1] or k == 0:
print(1)
else:
print(2) |
1634 | B | Fortune Telling | \begin{quote}
Haha, try to solve this, SelectorUnlimited!
\hfill — antontrygubO_o
\end{quote}
Your friends Alice and Bob practice fortune telling.
Fortune telling is performed as follows. There is a well-known array $a$ of $n$ non-negative integers indexed from $1$ to $n$. The tellee starts with some non-negative num... | Notice that the operations $+$ and $\oplus$ have the same effect on the parity: it is inverted if the second argument of the operation is odd, and stays the same otherwise. By induction, we conclude that if we apply the operations to some even number and to some odd number, the resulting numbers will also be of differe... | [
"bitmasks",
"math"
] | 1,400 | def main():
n, x, y = map(int, input().split())
a = list(map(int, input().split()))
if (sum(a) + x + y) % 2 == 0:
print('Alice')
else:
print('Bob')
for _ in range(int(input())):
main() |
1634 | C | OKEA | \begin{quote}
People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.
\hfill — Pedro Domingos
\end{quote}
You work for a well-known department store that uses leading technologies and employs mechanistic work — th... | If $k = 1$, you can put items on the shelves in any order. Otherwise, there are at least 2 items on each shelf. If there are items of different parity on the shelf, it is obvious that there are two neighboring items of different parity, but then the arithmetic mean of these two items won't be whole, which is against th... | [
"constructive algorithms"
] | 1,000 | def solve():
n, k = map(int, input().split())
if k == 1:
print("YES")
for i in range(1, n + 1):
print(i)
return
if n % 2 == 1:
print("NO")
return
print("YES")
for i in range(1, n + 1):
print(*[i for i in range(i, n * k + 1, n)])
for _ i... |
1634 | D | Finding Zero | \textbf{This is an interactive problem.}
We picked an array of whole numbers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) and concealed \textbf{exactly one} zero in it! Your goal is to find the location of this zero, that is, to find $i$ such that $a_i = 0$.
You are allowed to make several queries to guess the answ... | Notice that for any four numbers $a, b, c, d$ we can locate at least two numbers among them that are certainly not zeroes using only four queries as follows. For each of the four numbers, compute it's complement, that is, the difference between the maximum and the minimum of the other three numbers: $\bar{a} = \max(b, ... | [
"constructive algorithms",
"interactive",
"math"
] | 2,000 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define len(x) (int) (x).size()
using namespace std;
int get(const vector <int>& x) {
cout << "? " << x[0] + 1 << " " << x[1] + 1 << " " << x[2] + 1 << endl;
int ans;
cin >> ans;
return ans;
}
signed main() {
ios_base::sync_w... |
1634 | E | Fair Share | \begin{quote}
Even a cat has things it can do that AI cannot.
\hfill — Fei-Fei Li
\end{quote}
You are given $m$ arrays of positive integers. Each array is of even length.
You need to split all these integers into two \textbf{equal} multisets $L$ and $R$, that is, each element of each array should go into one of two m... | If there is a number that occurs an odd number of times in total, there is no answer. Otherwise, let us construct a bipartite graph as follows. The left part will denote the arrays ($m$ vertices) and the right part will denote the numbers (up to $\sum n_i$ vertices). Each array vertex is connected to all the numbers co... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graph matchings",
"graphs"
] | 2,400 | #include <bits/stdc++.h>
#define len(x) (int) (x).size()
#define all(x) (x).begin(), (x).end()
#define endl "\n"
using namespace std;
const int N = 4e5 + 100, H = 2e5 + 50;
vector <pair <int, int>> g[N];
string ans[N];
int pos[N];
void dfs(int v) {
if (pos[v] == 0) {
ans[v] = string(len(g[v]), 'L');
... |
1634 | F | Fibonacci Additions | \begin{quote}
One of my most productive days was throwing away 1,000 lines of code.
\hfill — Ken Thompson
\end{quote}
\textbf{Fibonacci addition} is an operation on an array $X$ of integers, parametrized by indices $l$ and $r$. Fibonacci addition increases $X_l$ by $F_1$, increases $X_{l + 1}$ by $F_2$, and so on up t... | Let $C_i = A_i - B_i$. Consider another auxiliary array $D$, where $D_1 = C_1$, $D_2 = C_2 - C_1$, and $D_i = C_i - C_{i - 1} - C_{i - 2}$ for $i > 2$. Notice that arrays $A$ and $B$ are equal if and only if all elements of $D$ are equal to $0$. Let's analyze how Fibonacci addition affects $D$. If Fibonacci addition is... | [
"brute force",
"data structures",
"hashing",
"implementation",
"math"
] | 2,700 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define len(x) (int) (x).size()
#define endl "\n"
#define int long long
using namespace std;
const int N = 3e5 + 100;
int MOD;
int fib[N];
vector <int> unfib;
int notzero = 0;
void upd(int ind, int delta) {
notzero -= (unfib[ind] != 0);
unfib[ind] ... |
1635 | A | Min Or Sum | You are given an array $a$ of size $n$.
You can perform the following operation on the array:
- Choose two different integers $i, j$ $(1 \leq i < j \leq n$), replace $a_i$ with $x$ and $a_j$ with $y$. In order not to break the array, $a_i | a_j = x | y$ must be held, where $|$ denotes the bitwise OR operation. Notice... | The answer is $a_1 | a_2 | \cdots | a_n$. Here is the proof: Let $m = a_1 | a_2 | \cdots | a_n$. After an operation, the value $m$ won't change. Since, $a_1 | a_2 | \cdots | a_n \leq a_1 + a_2 + \cdots + a_n$, the sum of the array has a lower bound of $m$. And this sum can be constructed easily: for all $i \in [1, n - ... | [
"bitmasks",
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main () {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int ans = 0;
for (int i = 0, x; i < n; ++i) {
cin >> x;
ans |= x;
}
cout << an... |
1635 | B | Avoid Local Maximums | You are given an array $a$ of size $n$. Each element in this array is an integer between $1$ and $10^9$.
You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $1$ and $10^9$.
Output the minimum number of operations needed such that the ... | Let's check all elements in $a$ from the left. Once we find that $a_i$ is a local maximum, then we should perform an operation to fix it. There are many ways to do this, but the optimal way is to set $a_{i+1}$ to $max(a_{i},a_{i+2})$, because we can avoid $a_i$ and $a_{i+2}$ from being local maximums at the same time. ... | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
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 (int i = 0; i < n; ++i) {
cin >> a[i];
}
int ans = 0;
for (... |
1635 | C | Differential Sorting | You are given an array $a$ of $n$ elements.
Your can perform the following operation no more than $n$ times: Select three indices $x,y,z$ $(1 \leq x < y < z \leq n)$ and replace $a_x$ with $a_y - a_z$. After the operation, $|a_x|$ need to be less than $10^{18}$.
Your goal is to make the resulting array \textbf{non-de... | First of all, if $a_{n-1} > a_n$, then the answer is $-1$ since we can't change the last two elements. If $a_n \geq 0$, there exists a simple solution: perform the operation $(i, n - 1, n)$ for each $1 \leq i \leq n - 2$. Otherwise, the answer exists if and only if the initial array is sorted. Proof: Assume that $a_n <... | [
"constructive algorithms",
"greedy"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
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 (int i = 0; i < n; ++i) {
cin >> a[i];
}
if (a[n - 2] > a[n - 1]) {... |
1635 | D | Infinite Set | You are given an array $a$ consisting of $n$ \textbf{distinct} positive integers.
Let's consider an infinite integer set $S$ which contains all integers $x$ that satisfy at least one of the following conditions:
- $x = a_i$ for some $1 \leq i \leq n$.
- $x = 2y + 1$ and $y$ is in $S$.
- $x = 4y$ and $y$ is in $S$.
F... | First of all, let's discuss the problem where $n = 1$ and $a_1 = 1$. For every integer $x$, there is exactly one integer $k$ satisfying $2^k \leq x < 2^{k + 1}$. Let's define $f(x) = k$. Then, it's quite easy to find out $f(2x + 1) = f(x) + 1$ and $f(4x) = f(x) + 2$. This observation leads to a simple dynamic programmi... | [
"bitmasks",
"dp",
"math",
"matrices",
"number theory",
"strings"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int main () {
ios::sync_with_stdio(false);
cin.tie(0);
int n, p;
cin >> n >> p;
vector <int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
set <int> useful;
for (int i ... |
1635 | E | Cars | There are $n$ cars on a coordinate axis $OX$. Each car is located at an integer point initially and no two cars are located at the same point. Also, each car is oriented either left or right, and they can move at any constant positive speed in that direction at any moment.
More formally, we can describe the $i$-th car... | First of all, let's discuss in what cases will two cars be irrelevant or destined. If two cars are in the same direction, they can either share the same coordinate at some moment or not, depending on their speed. In the picture above, if we set the speed of the blue car to $\infty$ and the red car to $1$, they won't me... | [
"2-sat",
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"sortings"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int N = 200001;
struct edge {
int type, u, v;
};
vector <int> adj[N];
int col[N], topo[N];
void dfs(int v) {
for (int u : adj[v]) if (col[u] == -1) {
col[u] = col[v] ^ 1;
dfs(u);
}
}
bool BipartiteColoring(int n) {
for (int i = 1; ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.