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 ⌀ |
|---|---|---|---|---|---|---|---|
1422 | F | Boring Queries | Yura owns a quite ordinary and boring array $a$ of length $n$. You think there is nothing more boring than that, but Vladik doesn't agree!
In order to make Yura's array even more boring, Vladik makes $q$ boring queries. Each query consists of two integers $x$ and $y$. Before answering a query, the bounds $l$ and $r$ f... | In order to find the LCM of numbers on a segment, you can, for each prime number, find the maximum power with which it enters into any number on the segment and multiply the answer with this power. Let's calculate the LCM for primes less than $\sqrt {MaxA}$ and greater than $\sqrt {MaxA}$ separately using the segment t... | [
"data structures",
"math",
"number theory"
] | 2,700 | #include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define a... |
1425 | A | Arena of Greed | Lately, Mr. Chanek frequently plays the game \textbf{Arena of Greed}. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.
The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest con... | We can solve this problem greedily. The tricky case is if the current number of coins is a multiple of $4$ greater than $8$, it is optimal to take 1 coin instead of taking $\frac{N}{2}$ coins. The proof: Lets say the number of of coins is $4k$ for some $k>0$. If we take $2k$ coins: Mr. Chanek takes $2k$ coins. (remaini... | [
"games",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define mp make_pair
#define fi first
#define se second
typedef long long lli;
typedef pair<int, int> ii;
typedef pair<lli, lli> ll;
lli solve(lli n) {
if (n < 5)
return max(1ll... |
1425 | B | Blue and Red of Our Faculty! | It's our faculty's 34th anniversary! To celebrate this great event, the Faculty of Computer Science, University of Indonesia (Fasilkom), held CPC - Coloring Pavements Competition. The gist of CPC is two players color the predetermined routes of Fasilkom in Blue and Red. There are $N$ Checkpoints and $M$ undirected pred... | First, we must notice that the graph is a clover graph. The graph has cycles with vertex $1$ in common. We can transform the graph into an array $A$, where $A_i$ is the number of edges in cycle $i$. On the final configuration, each cycle has three possible endings: The whole cycle is colored red or blue The whole cycle... | [
"divide and conquer",
"dp"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int MAXN=2e3+5;
int N, M, SA, SB, ans;
int P[MAXN];
int H[MAXN];
int DP[MAXN][3*MAXN];
int PD[MAXN][3*MAXN];
vector <int> A, B;
vector <int> V[MAXN];
set <int> S;
//BEGIN TEMODPLATE
//Template for DP Combin to avoid RLE
const long long MOD=1e9+7, D=(1LL<<61)/MOD... |
1425 | C | Captain of Knights | Mr. Chanek just won the national chess tournament and got a huge chessboard of size $N \times M$. Bored with playing conventional chess, Mr. Chanek now defines a function $F(X, Y)$, which denotes the minimum number of moves to move a knight from square $(1, 1)$ to square $(X, Y)$. It turns out finding $F(X, Y)$ is too ... | An important observation is that it is guaranteed there is a sequence of moves from $(1, 1)$ to $(X, Y)$ where we only visit squares in the rectangle $(1, 1)$ to $(X, Y)$. So we can calculate $F(X, Y)$ independently without concerning $N$ dan $M$. To ease the implementation and explanation, we define $\int(f(x)) = \sum... | [
"math"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
const long long MOD=1e9+7;
struct intmod {
long long val;
intmod operator + (const intmod other) const {
intmod ret;
ret.val=val+other.val;
if (ret.val>=MOD) {
ret.val-=MOD;
}
return ret;
}
intmod operator - (const intmod other) const {
intm... |
1425 | D | Danger of Mad Snakes | Mr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size $1000 \times 1000$ squares. There are $N$ mad snakes on the site, the i... | We are going to count the contribution of two snakes $(I, J)$ separately. Assume that the current snake we are interested in has danger value $B_1$ and $B_2$. The terms where they are killed must be on the form $(... + B_1 + B_2 + ...)^2$. Expanding this gives $B_1^2 + B_2^2 + 2B_1B_2$. So, the contribution of $B_1B_2$... | [
"combinatorics",
"dp",
"math"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
#define MAXN 1010
#define MOD 1000000007
typedef long long ll;
typedef pair<int,int> pii;
ll pref[MAXN+1][MAXN+1];
int dnc(int bas, int power, int mod) {
if(power==0) return 1;
if(power%2==0) {
int res=dnc(bas,power/2,mod);
return 1LL*res*res%mod;
}
return 1... |
1425 | E | Excitation of Atoms | Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are $N$ atoms numbered from $1$ to $N$. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom $i$ req... | Notice that for $K = 2$, we can always make an excitation route starting from any atom in $i$ in $1 \le i < N$ that excites all atoms. So, for $K > 2$, we can always make the routes by toggling bonds. So, there are three cases: If $K = 0$, it is optimal to excite only one atom. We try to excite atom $i$ for every $i$ a... | [
"greedy",
"implementation"
] | 2,200 | #include <iostream>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> PLL;
#define fi first
#define se second
const LL LINF = 4557430888798830399LL;
const LL MAXN = 1000000;
LL n,k;
LL sum[MAXN+5];
PLL isi[MAXN+5];
// Define X is a node that make this true (1 <= X < N)
/**
* [This checks with n... |
1425 | F | Flamingoes of Mystery | This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().
Mr. Chanek wants to buy a flamingo to accompany his chickens on h... | First get the values of the first three elements using three queries: "? 1 3" "? 1 2" "? 2 3" Once you get $A_i$, element $A_{i+1}$ can be obtained using "? i i+1" Time complexity: $O(N)$ | [
"interactive"
] | 1,400 | #include <iostream>
using namespace std;
const int MAXN = 1000;
int n, ans[MAXN+5];
int ask(int l, int r){
cout << "? " << l << " " << r << endl;
int ret; cin >> ret;
return ret;
}
void answer(){
cout << "!";
for(int i = 1;i <= n;i++) cout << " " << ans[i];
cout << endl;
}
int main(){
... |
1425 | H | Huge Boxes of Animal Toys | Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification:
- The first box stores toys with fun values in range of $(-\infty,-1]$.
- The second box stores toys with fun values in range of $(-1, 0)$.
- The third box s... | The main observation of this problem is that the sewing order does not matter. The final fun value is the multiplication of fun values of all toys. There are two separate cases we must consider: Cek the sign of the toy. If $(A + B)$ is even, the sign is positive. Else, it's negative. Cek whether it is possible to make ... | [
"constructive algorithms"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int T;
int A,B,C,D;
int main(){
cin>>T;
for(int i=0;i<T;i++){
cin>>A>>B>>C>>D;
if(A==0 && D == 0){
if(B % 2 == 1){
cout<<"Tidak Ya Tidak Tidak\n";
} else {
cout<<"Tidak Tidak Ya Tidak\n";
}
} else if(B == 0 && C == 0){
if(A % 2 == 1){
cout<<"... |
1425 | I | Impressive Harvesting of The Orchard | Mr. Chanek has an orchard structured as a rooted ternary tree with $N$ vertices numbered from $1$ to $N$. The root of the tree is vertex $1$. $P_i$ denotes the parent of vertex $i$, for $(2 \le i \le N)$. Interestingly, the height of the tree is not greater than $10$. Height of a tree is defined to be the largest dista... | We classify each vertex $i$ into two types. heavy if $A_i > \sqrt{Q}$ and light if $A_i \le \sqrt{Q}$. We craft two different algorithms to solve each case separately. heavy nodes: Flatten the tree using pre-order transversal. Now querying a subtree becomes querying a subarray. Maintain a global set $S$ with all curren... | [
"data structures"
] | 2,800 | #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,popcnt,abm,mmx,avx,avx2,fma,tune=native")
#include <vector>
#include <iostream>
#include <string>
#include <tuple>
#include <algorithm>
#include <assert.h>
using namespace std;
const int NMAX = ... |
1426 | A | Floor Number | Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $n$.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $2$ apartments, every other floor contains $x$ apartments each. Apartments are numbered starting from one,... | If $n \le 2$ then the answer is $1$. Otherwise, you can "remove" the first floor and then the answer is $\left\lfloor\frac{n - 3}{x}\right\rfloor + 2$. | [
"implementation",
"math"
] | 800 | for i in range(int(input())):
n, x = map(int, input().split())
print(1 if n <= 2 else (n - 3) // x + 2) |
1426 | B | Symmetric Matrix | Masha has $n$ types of tiles of size $2 \times 2$. Each cell of the tile contains one integer. Masha has an \textbf{infinite number} of tiles of each type.
Masha decides to construct the square of size $m \times m$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal ... | Firstly, if $m$ is odd then the answer is "NO" by obvious reasons. Otherwise, we can notice that the top left and the bottom right values of the tile do not matter (since we can place tiles symmetrically). So we only need to check that there is some tile that its top right value equals its bottom left value (because th... | [
"implementation"
] | 900 | for i in range(int(input())):
n, m = map(int, input().split())
a = []
for i in range(n):
a.append([[int(x) for x in input().split()] for i in range(2)])
ok = False
for i in range(n):
ok |= a[i][0][1] == a[i][1][0]
ok &= m % 2 == 0
print("YES" if ok else "NO") |
1426 | C | Increase and Copy | Initially, you have the array $a$ consisting of one element $1$ ($a = [1]$).
In one move, you can do one of the following things:
- Increase some (\textbf{single}) element of $a$ by $1$ (choose some $i$ from $1$ to the current length of $a$ and increase $a_i$ by one);
- Append the copy of some (\textbf{single}) eleme... | It is pretty intuitive that we firstly need to do all increments and only then copy numbers (because otherwise we can swap the order of moves and the sum will not decrease). You could notice that the answer does not exceed $O(\sqrt{n})$ so we can just iterate from $1$ to $\left\lfloor\sqrt{n}\right\rfloor$ and fix the ... | [
"binary search",
"constructive algorithms",
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
const long double EPS = 1e-9;
long long f(long long x)
{
long long z = sqrtl(x);
long long ans = 1e18;
for(int i = -5; i <= 5; i++)
{
long long z2 = z - i;
if(z2 > x || z2 < 1)
continue;
ans = min(an... |
1426 | D | Non-zero Segments | Kolya got an integer array $a_1, a_2, \dots, a_n$. The array can contain both positive and negative integers, but Kolya doesn't like $0$, so the array doesn't contain any zeros.
Kolya doesn't like that the sum of some subsegments of his array can be $0$. The subsegment is some consecutive segment of elements of the ar... | Firstly, let's understand that the sum of the segment $[l; r]$ is zero if $p_r - p_{l - 1}$ is zero (in other words, $p_{l - 1} = p_r$), where $p_i$ is the sum of the first $i$ elements ($p_0 = 0$). Let's iterate over elements from left to right and add all prefix sums in the set. If we get the sum that is already in t... | [
"constructive algorithms",
"data structures",
"greedy",
"sortings"
] | 1,500 | n = int(input())
a = [int(x) for x in input().split()]
d = set()
d.add(0)
cur = 0
ans = 0
for i in range(n):
cur += a[i]
if cur in d:
ans += 1
d = set()
d.add(0)
cur = a[i]
d.add(cur)
print(ans) |
1426 | E | Rock, Paper, Scissors | Alice and Bob have decided to play the game "Rock, Paper, Scissors".
The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a d... | The maximum number of rounds Alice can win is pretty easy to calculate greedily: $min(a_1, b_2) + min(a_2, b_3) + min(a_3, b_1)$. What about the minimum number of rounds? It can be shown that if we started using some combination we are better to end it before using the other one. There are six possible combinations to ... | [
"brute force",
"constructive algorithms",
"flows",
"greedy",
"math"
] | 1,800 | #include <bits/stdc++.h>
#define sz(v) int(v.size())
#define all(v) v.begin(), v.end()
#define pb push_back
#define ft first
#define sc second
using namespace std;
int n;
vector<int> a, b;
inline void read() {
cin >> n;
a.resize(3);
b.resize(3);
for (int i = 0; i < 3; i++) cin >> a[i];
for (int i = 0; i < 3; i... |
1426 | F | Number of Subsequences | You are given a string $s$ consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string $s$ be $k$. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all $3^{k}$ possible strings consisting only of letters "a",... | There are several more or less complicated combinatorial solutions to this problem, but I will describe a dynamic programming one which, I think, is way easier to understand and to implement. Suppose we have fixed the positions of a, b and c that compose the subsequence (let these positions be $p_a$, $p_b$ and $p_c$). ... | [
"combinatorics",
"dp",
"strings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
const int MOD = int(1e9) + 7;
const int N = 200043;
const int K = 4;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int n;
string s... |
1427 | A | Avoiding Zero | You are given an array of $n$ integers $a_1,a_2,\dots,a_n$.
You have to create an array of $n$ integers $b_1,b_2,\dots,b_n$ such that:
- The array $b$ is a rearrangement of the array $a$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multis... | First of all, notice that if the sum $a_1+a_2+\cdots+a_n$ is $0$, then, since $b$ is a rearrangement of $a$, it holds $b_1+b_2+\cdots+b_n=0$ and therefore the answer is NO. On the other hand, if $a_1+a_2+\cdots+a_n\not=0$, then there is a valid array $b$. To show this, let us consider two cases. If $a_1+a_2+\cdots+a_n ... | [
"math",
"sortings"
] | 900 | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
... |
1427 | B | Chess Cheater | You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise ... | Notice that the score is equal to $\texttt{score} = 2\cdot\texttt{#\{wins\}} - \texttt{#\{winning_streaks\}}\,,$ In the explanation that follows, the variables $\texttt{#\{wins\}}$, $\texttt{#\{winning_streaks\}}$ are always related to the initial situation. If $k+\texttt{#\{wins\}}\ge n$, then it is possible to win al... | [
"greedy",
"implementation",
"sortings"
] | 1,400 | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
... |
1427 | C | The Hard Work of Paparazzi | You are a paparazzi working in Manhattan.
Manhattan has $r$ south-to-north streets, denoted by numbers $1, 2,\ldots, r$ in order from west to east, and $r$ west-to-east streets, denoted by numbers $1,2,\ldots,r$ in order from south to north. Each of the $r$ south-to-north streets intersects each of the $r$ west-to-eas... | This is a classical dynamic-programming task with a twist. For the solution to work it is fundamental that the city has a small diameter (i.e., $r$ shall not be large) and that there are not simultaneous appearances. We say that two celebrities $i<j$ are compatible if it is possible to take a photo of both, that is $|x... | [
"dp"
] | 2,000 | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
... |
1427 | D | Unshuffling a Deck | You are given a deck of $n$ cards numbered from $1$ to $n$ (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
- Choose $2 \le k \le n$ and split the deck in $k$ nonempty contiguous parts $D_1, D_2,\dots, D_k$ ($D_1$ contains the first $|D_1|$ cards of the deck,... | We say that a pair of consecutive cards in the deck is good if they have consecutive numbers (in the right order). Let $m$ be the number of good pairs. We show that, if the deck is not sorted, with one move we can increase $m$. Hence after at most $n-1$ moves it will hold $m=n-1$ and the deck will be sorted. Since the ... | [
"constructive algorithms",
"implementation"
] | 2,000 | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
... |
1427 | E | Xum | You have a blackboard and initially only an \textbf{odd} number $x$ is written on it. Your goal is to write the number $1$ on the blackboard.
You may write new numbers on the blackboard with the following two operations.
- You may take two numbers (not necessarily distinct) already on the blackboard and write their s... | We present two different solutions. The first solution is by Anton, the second is mine. The first solution is deterministic, it is fundamentally based on Bezout's Theorem and comes with a proof. It performs $\approx 100$ operations and writes numbers up to $O(x^3)$. The second solution is randomized, uses some xor-line... | [
"bitmasks",
"constructive algorithms",
"math",
"matrices",
"number theory"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
res << "[";
for (; b... |
1427 | F | Boring Card Game | When they are bored, Federico and Giada often play the following card game with a deck containing $6n$ cards.
Each card contains one number between $1$ and $6n$ and each number appears on exactly one card. Initially the deck is sorted, so the first card contains the number $1$, the second card contains the number $2$,... | Before describing the solution, let us comment it. The solution is naturally split in two parts: Solving the problem without the "alternating turns" constraint. Noticing that a simple greedy is sufficient to take care of the "alternating turns" constraint. The first part of the solution is a rather standard greedy appr... | [
"data structures",
"greedy",
"trees"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
res << "[";
for (; begin_iter != end_iter ... |
1427 | G | One Billion Shades of Grey | You have to paint with shades of grey the tiles of an $n\times n$ wall. The wall has $n$ rows of tiles, each with $n$ tiles.
The tiles on the boundary of the wall (i.e., on the first row, last row, first column and last column) are already painted and you shall not change their color. All the other tiles are not paint... | We present two solutions: the first solution is mine, the second is by dacin21. The first solution reduces the problem to the computation of $O(n)$ min-cuts and then computes the min-cuts with total complexity $O(n^3)$. This solution requires no advanced knowledge and it fits easily in the time-limit. The second soluti... | [
"flows",
"graphs"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define SZ(x) ((int)((x).size()))
#if DEBUG && !ONLINE_JUDGE
ifstream input_from_file("input.txt");
#define cin input_from_file
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define dbg_arr(x, len) clog << #x << ": " << print_ite... |
1427 | H | Prison Break | A prisoner wants to escape from a prison. The prison is represented by the interior of the convex polygon with vertices $P_1, P_2, P_3, \ldots, P_{n+1}, P_{n+2}, P_{n+3}$. It holds $P_1=(0,0)$, $P_{n+1}=(0, h)$, $P_{n+2}=(-10^{18}, h)$ and $P_{n+3}=(-10^{18}, 0)$.
The prison walls $P_{n+1}P_{n+2}$, $P_{n+2}P_{n+3}$ an... | We fix the unit of measure and say that the prisoner moves at $1$ meter per second. Let us parametrize the boundary of the prison as follows (ignoring the very long, very high walls). Start walking with speed $1$ from $P_1$ towards $P_{n+1}$ staying on the prison wall and let $\gamma(t)$ be the point you are at after t... | [
"binary search",
"games",
"geometry",
"ternary search"
] | 3,500 | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SZ(x) ((int)((x).size()))
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
... |
1428 | A | Box is Pull | Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $(x_1,y_1)$ to the point $(x_2,y_2)$.
He has a rope, which he can use to pull the box. He can only pull the box if he stands \textbf{exactly} $1$ unit away from the box in the direction of one of two coordinat... | Consider when $x_1=x_2$ Consider when $x_1 \ne x_2$ We consider 2 cases. The first is that the starting and ending point lie on an axis-aligned line. In this case, we simply pull the box in 1 direction, and the time needed is the distance between the 2 points as we need 1 second to decrease the distance by 1. The secon... | [
"math"
] | 800 | tc=int(input())
for i in range(tc):
a,b,c,d=map(int,input().split(" "))
ans=abs(a-c)+abs(b-d)
if (a!=c and b!=d): ans+=2
print(ans) |
1428 | B | Belted Rooms | In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $... | There are 2 cases to consider for a room to be returnable. For a room to be returnable, either go one big round around all the rooms or move to an adjacent room and move back. Let's consider two ways to return to the start point. The first is to go one big round around the circle. The second is to move 1 step to the si... | [
"graphs",
"implementation"
] | 1,200 | TC = int(input())
for tc in range(TC):
n = int(input())
s = input()
hasCW = False
hasCCW = False
for c in s:
if c == '>':
hasCW = True
if c == '<':
hasCCW = True
if hasCW and hasCCW:
s += s[0]
ans = 0;
for i in range(... |
1428 | C | ABBB | Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | and oolimry AB and BB means that ?B can be removed. The final string is BAAA... or AAA.... This game is equivalent to processing left to right and maintaining a stack. If the current processed character is A, we add it to the stack, if the current processed character is B, we can either add it to the stack or pop the t... | [
"brute force",
"data structures",
"greedy",
"strings"
] | 1,100 | TC = int(input())
for tc in range(TC):
s = input()
ans=0
for i in s:
if (i=='B' and ans!=0): ans-=1
else: ans+=1
print(ans) |
1428 | D | Bouncing Boomerangs | To improve the boomerang throwing skills of the animals, Zookeeper has set up an $n \times n$ grid with some targets, \textbf{where each row and each column has at most $2$ targets each}. The rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $n$ from left to right.
For each... | Consider $a_i \in \{0,1,2\}$. Consider $a_i=\{3,3,3, \ldots , 3,1\}$. Clearly, columns with $a_j=0$ are completely empty and we can ignore them. Let's first consider just columns with $1$ s and $2$ s. When a boomerang strikes its first target, it will change directions from upwards to rightwards. If $a_j=1$, the boomer... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,900 | def die():
print(-1)
exit(0)
ones = []
ans = []
H = 1
lastThree = (-1,-1)
n = int(input())
arr = list(map(int,input().split(" ")))
for i in range(n-1, -1, -1):
if arr[i] == 0:
continue
elif arr[i] == 1:
ones.append((i,H))
ans.append((i,H))
H += 1
elif arr[i] == ... |
1428 | E | Carrots for Rabbits | There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut ... | Orz proof by: oolimry Greedy. Let us define $f(l,p)$ as the sum of time needed when we have a single carrot of length $l$ and it is split into $p$ pieces. We can show that $f(l,p-1)-f(l,p) \ge f(l,p)-f(l,p+1)$. Let us define $f(l,p)$ as the sum of time needed when we have a single carrot of length $l$ and it is split i... | [
"binary search",
"data structures",
"greedy",
"math",
"sortings"
] | 2,200 | from heapq import *
n,k=map(int,input().split(" "))
def val(l,nums):
unit=l//nums
extra=l-unit*nums
return (nums-extra)*unit*unit+extra*(unit+1)*(unit+1)
pq=[]
arr=list(map(int,input().split(" ")))
total=0
for x in range(n):
total+=arr[x]*arr[x]
heappush(pq,(-val(arr[x],1)+val(arr[x],2),arr... |
1428 | F | Fruit Sequences | Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.
Since wabbit is allergic to eating oranges, Zookeeper would like to find the lon... | Line sweep. How does $f(l,r)$ change when we increase r? For a fixed $r$, let us graph $f(l,r)$ in a histogram with $l$ as the $x$-axis. We notice that this histogram is non-increasing from left to right. Shown below is the histogram for the string $11101011$ with $r = 6$, where $1$ box represents $1$ unit. The area un... | [
"binary search",
"data structures",
"divide and conquer",
"dp",
"two pointers"
] | 2,400 | import sys
range = xrange
input = raw_input
inp=sys.stdin.read().split()
n = int(inp[0])
s=inp[1]
tot=0
cur=0
hist=[0]*1000005
i=0
while (i<n):
if (s[i]=='0'):
tot+=cur
else:
l=i
r=i
while (r+1<n and s[r+1]=='1'): r+=1
for x in range(r-l+1):
cur+=(l+x+1)... |
1428 | G2 | Lucky Numbers (Hard Version) | \textbf{This is the hard version of the problem. The only difference is in the constraint on $q$. You can make hacks only if all versions of the problem are solved.}
Zookeeper has been teaching his $q$ sheep how to write and how to add. The $i$-th sheep has to write exactly $k$ \textbf{non-negative integers} with the ... | 0 is a lucky number as well. There is at most one number whose digits is not entirely 0, 3, 6, 9. Knapsack. Group same items. Suppose in our final solution, there is a certain position (ones, tens...) that has two digits which are not $0$, $3$, $6$, or $9$. Let these two digits are $a$ and $b$. If $a+b \leq 9$, we can ... | [
"dp",
"greedy"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
const long long inf = (1LL << 58LL);
long long F[6];
long long fortune[10] = {0, 0, 0, 1, 0, 0, 2, 0, 0, 3};
long long ten[6] = {1, 10, 100, 1000, 10000, 100000};
long long dp[1000005];
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
int K; int N = 999999;
... |
1428 | H | Rotary Laser Lock | \textbf{This is an interactive problem.}
To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock.
The lock consists of $n$ concentric rings numbered from $0$ to $n-1$. The innermost ring is ring $0$ ... | Using only arc $0$, find at least $1$ position where arc $0$ exactly matches another arc. Binary Search. Flatten the circle such that it becomes $n$ rows of length $nm$ with vertical sections numbered from $0$ to $nm-1$ that loops on the end. We say that the position of an arc is $x$ if the left endpoint of the arc is ... | [
"binary search",
"interactive"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
int queryRotation(int r, int d){ // Auxiliary function to print query and receive answer
int res;
cout << "? " << r << ' ' << d << endl << flush; // Print query
cout.flush();
cin >> res; // Get response
if (res == -1) exit(1); // Error occured, exit... |
1430 | A | Number of Apartments | Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar... | There are many possible solutions to this problem. The simplest one is to notice that, using several flats of size $3$ and one flat of some size (possibly also $3$, possibly not), we can get any $n$ equal to $[3, 6, 9, \dots]$, $[5, 8, 11, \dots]$ or $[7, 10, 13, \dots]$. The only numbers that don't belong to these lis... | [
"brute force",
"constructive algorithms",
"math"
] | 900 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
1430 | B | Barrels | You have $n$ barrels lined up in a row, numbered from left to right from one. Initially, the $i$-th barrel contains $a_i$ liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $x$ and $y$ (the $x$-th barrel shouldn't be empty) and pour any possible ... | A greedy strategy always works: take $k + 1$ largest barrels, choose one barrel among them and pour all water from those barrels to the chosen barrel. That way, we make the minimum amount equal to $0$ (it's quite obvious that we can't do anything better here), and the maximum amount as large as possible, so the differe... | [
"greedy",
"implementation",
"sortings"
] | 800 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
1430 | C | Numbers on Whiteboard | Numbers $1, 2, 3, \dots n$ (each integer from $1$ to $n$ once) are written on a board. In one operation you can erase any two numbers $a$ and $b$ from the board and write one integer $\frac{a + b}{2}$ rounded up instead.
You should perform the given operation $n - 1$ times and make the resulting number that will be le... | It's easy to see that we can't get the result less than $2$, because, if we merge two positive numbers, and at least one of them is $2$ or greater, the new number is always greater than $1$. So we can't get rid of all numbers greater than $1$. To always achieve $2$, we can use a greedy algorithm: always merge two maxim... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"math"
] | 1,000 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
1430 | D | String Deletion | You have a string $s$ consisting of $n$ characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
- select an integer $i$ from $1$ to the length of the string $s$, then delete the character $s_i$ (the string length gets reduced by $1$, the indices of ... | Suppose the string consists of $n$ characters, and each character is different from the adjacent ones (so the string looks like 01010... or 10101...). It's easy to see that we can't make more than $\lceil \frac{n}{2} \rceil$ operations (each operation deletes at least two characters, except for the case when the string... | [
"binary search",
"data structures",
"greedy",
"two pointers"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
char buf[200043];
int main()
{
int t;
scanf("%d", &t);
for(int tc = 1; tc <= t; tc++) {
int n;
scanf("%d", &n);
scanf("%s", buf);
string s = buf;
queue<int> q;
int cur = 0;
for(int i = 0; i < n; i++)
{
if(i > 0 && s[i] != s[i - 1])
cur++;
i... |
1430 | E | String Reversal | You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the s... | First of all, let's find the resulting position for each character of the string. It's easy to see that we don't need to swap equal adjacent characters (it changes nothing), so the first character a in the original string is the first character a in the resulting string, the second character a in the original string is... | [
"data structures",
"greedy",
"strings"
] | 1,900 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
1430 | F | Realistic Gameplay | Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to $k$ and should exterminate $n$ waves of monsters. The $i$-th wave consists of $a_i$ monsters and happens from the $l_i$-th moment of time up to the $r_i$-th moments of time. All $a_i... | Note some observations: if we meet a new wave and start shooting it's optimal to shoot monsters in the wave using full magazines while we can and there are no reasons to take breaks between shooting monsters from one wave. That's why we can track only moments when waves start and the number of remaining bullets in maga... | [
"dp",
"greedy"
] | 2,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())
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
const ld EPS = 1e-9;
... |
1430 | G | Yet Another DAG Problem | You are given a directed acyclic graph (a directed graph that does not contain cycles) of $n$ vertices and $m$ arcs. The $i$-th arc leads from the vertex $x_i$ to the vertex $y_i$ and has the weight $w_i$.
Your task is to select an integer $a_v$ for each vertex $v$, and then write a number $b_i$ on each arcs $i$ such ... | The key observation in this problem is that the values of $a_v$ should form a contiguous segment of integers. For example, suppose there exists a value $k$ such that there is at least one $a_v < k$, there is at least one $a_v > k$, but no $a_v = k$. We can decrease all values of $a_v$ that are greater than $k$ by $1$, ... | [
"bitmasks",
"dfs and similar",
"dp",
"flows",
"graphs",
"math"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
typedef long long li;
const int N = 18;
const int M = (1 << N);
const li INF64 = li(1e18);
int n, m;
vector<int> g[N];
li sum[N];
int need_mask[N];
li dp[N + 1][N + 1][M];
bool p[N + 1][N + 1][M];
vector<int> order;
vector<int> used;
void dfs(int x, bool build_t... |
1433 | A | Boring Apartments | There is a building consisting of $10~000$ apartments numbered from $1$ to $10~000$, inclusive.
Call an apartment \textbf{boring}, if its number consists of the same digit. Examples of boring apartments are $11, 2, 777, 9999$ and so on.
Our character is a troublemaker, and he calls the intercoms of all \textbf{boring... | This problem has a lot of solutions. You could even hard code all possible tests to solve it. But this problem has $O(1)$ solution. Let the digit of $x$ be $dig$. Then our character pressed each digit before $dig$ exactly $10$ times ($1 + 2 + 3 + 4$). And the amount of times he pressed the digit $dig$ depends on the le... | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
string x;
cin >> x;
int dig = x[0] - '0' - 1;
int len = x.size();
cout << dig * 10 + len * (len + 1) / 2 << endl;
}
... |
1433 | B | Yet Another Bookshelf | There is a bookshelf which can fit $n$ books. The $i$-th position of bookshelf is $a_i = 1$ if there is a book on this position and $a_i = 0$ otherwise. It is guaranteed that there is \textbf{at least one book} on the bookshelf.
In one move, you can choose some contiguous segment $[l; r]$ consisting of books (i.e. for... | We can notice that the answer is the number of zeros between the leftmost occurrence of $1$ and the rightmost occurrence of $1$. Why is it true? Let's take the leftmost maximum by inclusion segment of $1$ and just shift it right. We can see that using this algorithm we will do exactly described amount of moves and ther... | [
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) cin >> it;
while (a.back() == 0) a.pop_back();
reverse(a.begin... |
1433 | C | Dominant Piranha | There are $n$ piranhas with sizes $a_1, a_2, \ldots, a_n$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is \textbf{dominant} piranha in the aquarium. The piranha is called \textbf{dominant} if it can eat al... | If all the piranhas have the same size then the answer is -1. Otherwise, there are at least two different sizes of piranhas and the answer always exists. Claim that the answer is such a piranha with the maximum size that one of the adjacent piranhas has the size less than a maximum. Why is it true and why the answer al... | [
"constructive algorithms",
"greedy"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
int mx = 0;
for (auto &it : a) {
cin >> it;
mx = max(mx, it);
}
int idx =... |
1433 | D | Districts Connection | There are $n$ districts in the town, the $i$-th district belongs to the $a_i$-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build $n-1$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).... | If all districts belong to the same gang then the answer is NO. Otherwise, the answer is always YES (yeah, as in the previous problem). How to construct it? Let's choose the first "root" as the district $1$ and connect all such districts $i$ that $a_1 \ne a_i$ to the district $1$. So, all disconnected districts that re... | [
"constructive algorithms",
"dfs and similar"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<pair<int, int>> res;
int idx = -1;
for (in... |
1433 | E | Two Round Dances | One day, $n$ people ($n$ is an even number) met on a plaza and made two round dances, each round dance consists of exactly $\frac{n}{2}$ people. Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\frac{n}{2}$ people. Each person should belong to exactly... | Firstly, we need to choose the set of $\frac{n}{2}$ people to be in the first round dance (the other half is going to the second one). The number of ways to do that is $\binom{n}{\frac{n}{2}}$. Then we need to set some order of people in both round dances, but we don't want to forget about rotation (because rotation ca... | [
"combinatorics",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int N = 21;
long long f[N];
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
f[0] = 1;
for (int i = 1; i < N; ++i) {
f[i] = f[i - 1] * i;
}
long long ans = f[n] / f[n / 2] / f[... |
1433 | F | Zero Remainder Sum | You are given a matrix $a$ of size $n \times m$ consisting of integers.
You can choose \textbf{no more than} $\left\lfloor\frac{m}{2}\right\rfloor$ elements in \textbf{each row}. Your task is to choose these elements in such a way that their sum is \textbf{divisible by} $k$ and this sum is the \textbf{maximum}.
In ot... | This is pretty standard dynamic programming problem. Let $dp[x][y][cnt][rem]$ be the maximum possible sum we can obtain if we are at the element $a_{x, y}$ right now, we took $cnt$ elements in the row $x$ and our current remainder is $rem$. Initially, all states are $-\infty$ except $dp[0][0][0][0] = 0$. Transitions ar... | [
"dp"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 75;
const int INF = 1e9;
int a[N][N];
int dp[N][N][N][N];
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m, k;
cin >> n >> m >> k;
... |
1433 | G | Reducing Delivery Cost | You are a mayor of Berlyatov. There are $n$ districts and $m$ two-way roads between them. The $i$-th road connects districts $x_i$ and $y_i$. The cost of travelling along this road is $w_i$. There is some path between each pair of districts, so the city is connected.
There are $k$ delivery routes in Berlyatov. The $i$... | If we would naively solve the problem, we would just try to replace each edge's cost with zero and run Dijkstra algorithm $n$ times to get the cheapest paths. But this is too slow. Let's try to replace each edge's cost with zero anyway but use some precalculations to improve the speed of the solution. Let's firstly run... | [
"brute force",
"graphs",
"shortest paths"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n;
vector<vector<int>> d;
vector<vector<pair<int, int>>> g;
void dijkstra(int s, vector<int> &d) {
d = vector<int>(n, INF);
d[s] = 0;
set<pair<int, int>> st;
st.insert({d[s], s});
while (!st.empty()) {
int v = st.begin()->second;
st.era... |
1434 | E | A Convex Game | Shikamaru and Asuma like to play different games, and sometimes they play the following: given an increasing list of numbers, they take turns to move. Each move consists of picking a number from the list.
Assume the picked numbers are $v_{i_1}$, $v_{i_2}$, $\ldots$, $v_{i_k}$. The following conditions must hold:
- $i... | It's sufficient to calculate the Grundy value for each game instance. Consider a single game. Let $maxc$ be the maximal value in the sequence $v$. We are going to prove that the Grundy value does not exceed $\sqrt{2 \cdot maxc} + 1$. Proof: Assume the contrary; that is, that the Grundy value equals $d > \sqrt{2 \cdot m... | [
"dsu",
"games"
] | 3,500 | null |
1436 | A | Reorder | For a given array $a$ consisting of $n$ integers and a given integer $m$ find if it is possible to reorder elements of the array $a$ in such a way that $\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$ equals $m$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs durin... | You can notice that the $i$-th number in the array will be included in the sum $i$ times, which means that the value $\frac {a_i} {i}$ will add $a_i$ to the sum. That is, the permutation of the elements does not affect the required sum, and therefore it is enough to check whether the sum of the array elements is equal ... | [
"math"
] | 800 | #include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define a... |
1436 | B | Prime Square | Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square.
A square of size $n \times n$ is called pri... | First, note that the numbers 0 and 1 are not prime. Now let's try to build a square from only these numbers. To begin with, fill in the main and secondary diagonal of the square with ones. If $n$ is even, then the sum in each row and each column is $2$ (prime number), and we have met the condition. If $n$ is odd, then ... | [
"constructive algorithms",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector <vector <int> > a(n);
for (int i = 0; i < n; ++i) {
a[i].resize(n, 0);
}
if (n == 4) {
vector <vector <int> > matrix = {{4, 6, 8, 1}, {4, 9, 9, 9}, {4, 10, 10, 65}, {1, 4, 4, 4}};
c... |
1436 | C | Binary Search | Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudo... | Let's simulate a binary search algorithm. Initially, we have the required position $pos$. For the next $middle$ position in the binary search, we can determine exactly whether the next number at this position should be greater or less than $x$. For all other positions, the values can be eiteher greater or less than $x$... | [
"binary search",
"combinatorics"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int binPow(int a, int n) {
int res = 1;
while (n) {
if (n & 1)
res = (1LL * res * a) % MOD;
a = (1LL * a * a) % MOD;
n >>= 1;
}
return res;
}
void binarySearch(int n, int x_position, int ... |
1436 | D | Bandit in a City | Bandits appeared in the city! One of them is trying to catch as many citizens as he can.
The city consists of $n$ squares connected by $n-1$ roads in such a way that it is possible to reach any square from any other square. The square number $1$ is the main square.
After Sunday walk all the roads were changed to \tex... | First, let's assume that all the citizens are at the root of the tree. Then the answer to the problem will be $\lceil \frac{a_1}{leaves} \rceil$, where $leaves$ is the number of leaves in the tree. According to the Dirichlet principle, this would be the minimum possible number of caught citizens. The answer to the orig... | [
"binary search",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | 1,900 | #pragma GCC optimize("unroll-loops")
#pragma GCC optimize("Ofast")
// hloya template v26
// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░
// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░
// ░░░░░░█░█░▀░░░░░▀░░▀░░░░█░█░░░░░
// ░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░
// █▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░
// ▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄
// ░░▀█▄▄█░... |
1436 | E | Complicated Computations | In this problem MEX of a certain array is the smallest \textbf{positive} integer not contained in this array.
Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.
You are given an array $a$ of length $n$. Lesha considers all ... | Let's iterate over the answer. Let the current answer be $x$, then we can get it only when there are no subarrays, whose MEX is $x$. Note that we need to check the MEX of the subarrays that are between all occurrences of $x$. This can be done, for example, using a segment tree, processing its occurrences in order. A nu... | [
"binary search",
"data structures",
"two pointers"
] | 2,400 | #include <bits/stdc++.h>
#define fi first
#define se second
#define p_b push_back
#define pll pair<ll,ll>
#define pii pair<int,int>
#define m_p make_pair
#define all(x) x.begin(),x.end()
#define sset ordered_set
#define sqr(x) (x)*(x)
#define pw(x) (1ll << x)
#define sz(x) (int)x.size()
#define fout(x) {cout << x << ... |
1436 | F | Sum Over Subsets | You are given a multiset $S$. Over all pairs of subsets $A$ and $B$, such that:
- $B \subset A$;
- $|B| = |A| - 1$;
- greatest common divisor of all elements in $A$ is equal to one;
find the sum of $\sum_{x \in A}{x} \cdot \sum_{x \in B}{x}$, modulo $998\,244\,353$. | Let's calculate the required product of the sums $ans_i$ for the sets, the greatest common divisor of the elements of which is $i$. First, let's select all the elements that are divisible by $i$. To find only those sets whose GCD is exactly $i$, one can find the product of the sums for all subsets and subtract the answ... | [
"combinatorics",
"math",
"number theory"
] | 2,800 | #include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define a... |
1437 | A | Marketing Scheme | You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with $a$ cans in a pack with a discount and some customer wants to buy $x$ cans of cat food. Then he follows a greedy ... | Note that if $\left\lfloor \frac{l}{a} \right\rfloor < \left\lfloor \frac{r}{a} \right\rfloor$ then exists such $k \cdot a$ that $l \le ka \le r$ and, obviously, a customer, who wants to buy $ka$ cans won't buy more than he wants. That's why $\left\lfloor \frac{l}{a} \right\rfloor = \left\lfloor \frac{r}{a} \right\rflo... | [
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
val (l, r) = readLine()!!.split(' ').map { it.toInt() }
println(if (2 * l > r) "YES" else "NO");
}
} |
1437 | B | Reverse Binary Strings | You are given a string $s$ of even length $n$. String $s$ is binary, in other words, consists only of 0's and 1's.
String $s$ has exactly $\frac{n}{2}$ zeroes and $\frac{n}{2}$ ones ($n$ is even).
In one operation you can reverse any substring of $s$. A substring of a string is a contiguous subsequence of that string... | We need to make our string alternating, i. e. $s_i \neq s_{i + 1}$. When we reverse substring $s_l \dots s_r$, we change no more than two pairs $s_{l - 1}, s_l$ and $s_r, s_{r + 1}$. Moreover, one pair should be a consecutive pair 00 and other - 11. So, we can find lower bound to our answer as maximum between number of... | [
"constructive algorithms",
"greedy"
] | 1,200 | #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())
const int INF = int(1e9);
int n;
string s;
inline bool read() {
if(!(cin >> n >> s))
return false;
return true;
}
int cntSame(const string &s) {
int ans = 0;
fore (i, 1, sz(s... |
1437 | C | Chef Monocarp | Chef Monocarp has just put $n$ dishes into an oven. He knows that the $i$-th dish has its optimal cooking time equal to $t_i$ minutes.
At any \textbf{positive integer} minute $T$ Monocarp can put \textbf{no more than one} dish out of the oven. If the $i$-th dish is put out at some minute $T$, then its unpleasant value... | There are a lot of solutions for the problem. Let's start with the easiest one. Sort the dishes in the non-decreasing order of their optimal time. I claim that there is an optimal answer such that the times $T$ for each dish go in the increasing order. That's not too hard to prove (something along the lines of if there... | [
"dp",
"flows",
"graph matchings",
"greedy",
"math",
"sortings"
] | 1,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
template<typename T>
T hungarian(const vector<vector<T>>& cost) {
const T INF = numeric_limits<T>::max();
int n = cost.size(), m = cost[0].size();
vector<T> u(n + 1), v(m + 1), dist(m + 1);
vector<int> p... |
1437 | D | Minimal Height Tree | Monocarp had a tree which consisted of $n$ vertices and was rooted at vertex $1$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
\begin{verbatim}
a = [] # the order in which vertices were processed
q = Queue()
q.put(1... | Due to the nature of BFS, the visiting order consists of several segments: first goes root (has depth $0$), then all vertices with depth $1$, then all vertices with depth $2$ and so on. Since any vertex of depth $d$ is a child of vertex of depth $d - 1$, then it's optimal to make the number of vertices with depth $1$ a... | [
"graphs",
"greedy",
"shortest paths",
"trees"
] | 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())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
int n;
vector<int> a;
inline bool read() {
... |
1437 | E | Make It Increasing | You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$.
In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$.
Cal... | First, let's solve the problem without blocked positions. Let's look at the array $b_i = a_i - i$. Obviously, if $a$ strictly increases, then $b$ does not decrease, and vice versa. Now we have to find the maximum number of positions in the $b$ array that can be left unchanged. And you can always choose an integer that ... | [
"binary search",
"constructive algorithms",
"data structures",
"dp",
"implementation"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 500 * 1000 + 13;
int n, k;
int a[N], b[N];
int main() {
scanf("%d%d", &n, &k);
forn(i, n) scanf("%d", &a[i + 1]);
a[0] = -1e9;
a[n + 1] = 2e9;
forn(i, n + 2) a[i] -= i;
forn(i, k) scanf("%d", &b[i ... |
1437 | F | Emotional Fishermen | $n$ fishermen have just returned from a fishing vacation. The $i$-th fisherman has caught a fish of weight $a_i$.
Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order... | First of all, sort the fishermen so it is easier to consider them in ascending order. The key observation that allows us to solve the problem is the following: there will be an increasing sequence of happy fishermen, and all other fishermen will be unhappy. Consider the fisherman $i$ which belongs to the increasing seq... | [
"combinatorics",
"dp",
"math",
"two pointers"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
const int N = 5043;
const int MOD = 998244353;
int dp[N][N];
int pdp[N][N];
int cntLess[N];
int lastLess[N];
int a[N];
int n;
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)
{
return add(x, MOD... |
1437 | G | Death DBMS | For the simplicity, let's say that the "Death Note" is a notebook that kills a person when their name is written in it.
It's easy to kill with it, but it's pretty hard to keep track of people you haven't killed and still plan to. You decided to make a "Death Database Management System" — a computer program that provid... | I'm feeling extremely amused by the power of Aho-Corasick lately, so I will describe two solutions of this problem with it. Feel free to point out how cool you are solving the task with hashes or some suffix structure but Aho solutions will still be cooler. I also want to mention I'm quite proud of the name I came up w... | [
"data structures",
"string suffix structures",
"strings",
"trees"
] | 2,600 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int AL = 26;
vector<vector<pair<int, int>>> upd;
vector<int> ans;
int n, m;
struct segtree{
vector<int*> where;
vector<int> vals;
vector<int> t;
int n;
segtree(){}
segtree(int n) : n(n){
t.assign(4 * ... |
1438 | A | Specific Tastes of Andre | Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array $b$ \textbf{good}, if sum of its elements is divisible by the length of this array. For example, array $[2, 3, 1]$ is good, as sum of its elements — $6$ — is divisible by $3$, but array $[1, 1, 2, 3]$ isn't g... | The array $a$ = $[1,1,\ldots,1,1]$ is perfect since the sum of every subarray is exactly equal to its length, and thus divisible by it. | [
"constructive algorithms",
"implementation"
] | 800 | null |
1438 | B | Valerii Against Everyone | You're given an array $b$ of length $n$. Let's define another array $a$, also of length $n$, for which $a_i = 2^{b_i}$ ($1 \leq i \leq n$).
Valerii says that every two non-intersecting subarrays of $a$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there ... | We claim the answer is NO if and only if the elements are pairwise distinct. If any element has two occurrences, we can trivially select them as the two subarrays. Otherwise, since all elements are distinct, choosing a subarray is the same as choosing the set bits of a $10^9$ digit long binary number. Since every numbe... | [
"constructive algorithms",
"data structures",
"greedy",
"sortings"
] | 1,000 | null |
1438 | C | Engineer Artem | Artem is building a new robot. He has a matrix $a$ consisting of $n$ rows and $m$ columns. The cell located on the $i$-th row from the top and the $j$-th column from the left has a value $a_{i,j}$ written in it.
If two adjacent cells contain the same value, the robot will break. A matrix is called \textbf{good} if no ... | The increment by one operation essentially allows us to change the parity of any position. Let's color the matrix like a chessboard. Since every pair of adjacent cells consist of cells with different colors, we can make values at all black cells even and values at all white cells odd. | [
"2-sat",
"chinese remainder theorem",
"constructive algorithms",
"fft",
"flows"
] | 2,000 | null |
1438 | D | Powerful Ksenia | Ksenia has an array $a$ consisting of $n$ positive integers $a_1, a_2, \ldots, a_n$.
In one operation she can do the following:
- choose three distinct indices $i$, $j$, $k$, and then
- change all of $a_i, a_j, a_k$ to $a_i \oplus a_j \oplus a_k$ simultaneously, where $\oplus$ denotes the bitwise XOR operation.
She ... | We will first solve the problem for odd $n$, and then extend the solution to even $n$. Note that applying the operation to $a, b, b$ makes all of them equal to $a$. Thus, we can try making pairs of equal elements. This is easy for odd $n$: While at least $3$ unpaired elements exist, apply the operation on any $3$. Pair... | [
"bitmasks",
"constructive algorithms",
"math"
] | 2,200 | null |
1438 | E | Yurii Can Do Everything | Yurii is sure he can do everything. Can he solve this task, though?
He has an array $a$ consisting of $n$ positive integers. Let's call a subarray $a[l...r]$ \textbf{good} if the following conditions are simultaneously satisfied:
- $l+1 \leq r-1$, i. e. the subarray has length at least $3$;
- $(a_l \oplus a_r) = (a_{... | It's natural to think that the number of good subarrays cannot be very large; this is indeed true. The following algorithm works: Fix the left endpoint $l$. Let $k$ be the most significant set bit in $a_l$. Check every $r$ in increasing order by bruteforce while $\text{sum}(l+1,r-1)$ is smaller than $2^{k+1}$. Reverse ... | [
"binary search",
"bitmasks",
"brute force",
"constructive algorithms",
"divide and conquer",
"two pointers"
] | 2,500 | null |
1438 | F | Olha and Igor | \textbf{This is an interactive problem.}
Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.
There is a perfect binary tree of height $h$ consisting of $n = 2^{h} - 1$ nodes. The nodes have been assigned distinct labels from $1$ to $n$. However, \textbf{Igor only knows ... | The solution is as follows. Query $420$ random triples. Let $c_1$ and $c_2$ be the two most frequently returned nodes - these are the children of the root. Query $c_1,c_2$ with every other $i$, and only the root will return $i$. Firstly, note that a query - $u$, $v$, and $w$ - returns a node $x$ that minimizes the sum ... | [
"interactive",
"probabilities",
"trees"
] | 3,000 | null |
1439 | A2 | Binary Table (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.}
You are given a binary table of size $n \times m$. This table consists of symbols $0$ and $1$.
You ... | Consider two cases: If $n = 2$ and $m = 2$, there are only $4$ possible operations, and we can use up to $4$ operations. So, one can check all the $2^4$ possible ways of choosing these operations, and seeing which combination of these operation will result in a full $0$ grid. Otherwise, at least one of $n$ and $m$ is b... | [
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 1,900 | // In The Name Of Allah
#include <bits/stdc++.h>
#define ss second
#define ff first
#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ret(n) return cout << n, 0
#define se(n) cout << setprecision(n) << fixed
#define pb push_back
#define ll long long
#define ld lon... |
1439 | B | Graph Subset Problem | You are given an undirected graph with $n$ vertices and $m$ edges. Also, you are given an integer $k$.
Find either a clique of size $k$ or a non-empty subset of vertices such that each vertex of this subset has at least $k$ neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of... | div1 B : It is easy to see that if $k > \sqrt{2m}$ the answer is $-1$; because if $k > \sqrt{2m}$, no matter whether we have a clique of size $k$ or a subset of the graph with $\delta \geq k$, we will have more than $m$ edges in total. Now, the main idea is to suppose $u$ is the vertex with minimum degree; if $d(u) < k... | [
"constructive algorithms",
"data structures",
"graphs"
] | 2,600 | // In The Name Of Allah
#include <bits/stdc++.h>
#define ss second
#define ff first
#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define se(n) cout << setprecision(n) << fixed
#define pb push_back
//#define int long long
#de... |
1439 | C | Greedy Shopping | You are given an array $a_1, a_2, \ldots, a_n$ of integers. This array is \textbf{non-increasing}.
Let's consider a line with $n$ shops. The shops are numbered with integers from $1$ to $n$ from left to right. The cost of a meal in the $i$-th shop is equal to $a_i$.
You should process $q$ queries of two types:
- 1 x... | We can prove that the hungry man will eat at most $log_2(maxY)$ continiuous subsegments, where $maxY$ is the maximum amount of money possible. Why is that so? Suppose the hungry man buys a meal from the $i$ th shop but can't buy a meal from the $(i + 1)$th one after that. Then, the money the hungry man had before buyin... | [
"binary search",
"data structures",
"divide and conquer",
"greedy",
"implementation"
] | 2,600 | #include <bits/stdc++.h>
#pragma GCC optimize ("O2,unroll-loops")
#pragma GCC optimize("no-stack-protector,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<pii, int> pi... |
1439 | D | INOI Final Contests | Today is the final contest of INOI (Iranian National Olympiad in Informatics). The contest room is a row with $n$ computers. All computers are numbered with integers from $1$ to $n$ from left to right. There are $m$ participants, numbered with integers from $1$ to $m$.
We have an array $a$ of length $m$ where $a_{i}$ ... | Suppose $n = m$. Let $dp1_i$ be the number of $(A , B)$ pairs for $i$ participants and $i$ computers so that no one gets upset. For updating this array we can consider the last participant, and where he will sit. Suppose he sits behind the $j$-th computer. If he comes from left to right, there are $i$ choices of comput... | [
"combinatorics",
"dp",
"fft"
] | 3,100 | // And you curse yourself for things you never done
// Shayan.P 2020-08-29
#include<bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define sz(s) int((s).size())
#define bit(n,k) (((n)>>(k))&1)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 510, inf = 1... |
1439 | E | Cheat and Win | Let's consider a $(10^9+1) \times (10^9+1)$ field. The rows are numbered with integers from $0$ to $10^9$ and the columns are numbered with integers from $0$ to $10^9$. Let's define as $(x, y)$ the cell located in the $x$-th row and $y$-th column.
Let's call a cell $(x, y)$ good if $x \& y = 0$, there $\&$ is the bitw... | First let's solve the problem on arbitrary trees. Consider the following game: on some vertices of the tree we have some tokens. At each step you remove a token from some vertex and put a token in any subset of its ancestors. The first game can be transformed to this one by putting a token in each black vertex. So now ... | [
"bitmasks",
"data structures",
"games",
"trees"
] | 3,500 | #include <bits/stdc++.h>
#pragma GCC optimize ("O2,unroll-loops")
//#pragma GCC optimize("no-stack-protector,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<pii, int> ... |
1440 | A | Buy the String | You are given four integers $n$, $c_0$, $c_1$ and $h$ and a binary string $s$ of length $n$.
A binary string is a string consisting of characters $0$ and $1$.
You can change any character of the string $s$ (the string should be still binary after the change). You should pay $h$ coins for each change.
After some chan... | We will consider each character seperately. Look at the $i$-th character; if it is originally a $1$, we can either change it to a $0$ and pay $h + c_0$ coins for this specific character, or we can not change it and pay $c_1$ coins for it. Since we want to pay as little as possible, we take the minimum of these two. So ... | [
"implementation",
"math"
] | 800 | // In The Name Of Allah
#include <bits/stdc++.h>
#define ss second
#define ff first
#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ret(n) return cout << n, 0
#define se(n) cout << setprecision(n) << fixed
#define pb push_back
#define ll long long
#define ld ... |
1440 | B | Sum of Medians | A median of an array of integers of length $n$ is the number standing on the $\lceil {\frac{n}{2}} \rceil$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $1$. For example, a median of the array $[2, 6, 4, 1, 3, 5]$ is equal to $3$. \textbf{There exist some ot... | We will consider a greedy approach. We take the $\lceil {\frac{n}{2}} \rceil$ biggest numbers from the end of the array and the $\lfloor {\frac{n}{2}} \rfloor$ smallest numbers from the beginning. We take these elements as one group, erase them from our array and then continue the same procedure on the remaining array.... | [
"greedy",
"math"
] | 900 | #include <bits/stdc++.h>
typedef long long int ll;
typedef long double ld;
#define pb push_back
#define pii pair < int , int >
#define F first
#define S second
#define endl '\n'
#define int long long
#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#pragma GCC optimize("Ofast,no-stack-protector,unro... |
1442 | A | Extreme Subtraction | You are given an array $a$ of $n$ positive integers.
You can use the following operation as many times as you like: select any integer $1 \le k \le n$ and do one of two things:
- decrement by one $k$ of the first elements of the array.
- decrement by one $k$ of the last elements of the array.
For example, if $n=5$ a... | The problem sounds like this - check that there are increasing and decreasing arrays, the element-wise sum of which is equal to the given array. This problem can be solved greedily. Let's maximize each element of the decreasing array (let's call this array $a$, and the increasing one $b$). Suppose initial array is $v$ ... | [
"constructive algorithms",
"dp",
"greedy"
] | 1,800 | null |
1442 | B | Identify the Operations | We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.
On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are wi... | Consider element with index $i$ that has value $b_1$ in the array $a$ - $a_i$. There are three options: Both $a_{i-1}$ and $a_{i+1}$ are present in the array $b$. Then both of them should stay in the array $a$ after the first operation - we will write them down later on. However, $a_i$ can only be added to the array b ... | [
"combinatorics",
"data structures",
"dsu",
"greedy",
"implementation"
] | 1,800 | null |
1442 | C | Graph Transpositions | You are given a directed graph of $n$ vertices and $m$ edges. Vertices are numbered from $1$ to $n$. There is a token in vertex $1$.
The following actions are allowed:
- Token movement. To move the token from vertex $u$ to vertex $v$ if there is an edge $u \to v$ in the graph. This action takes $1$ second.
- Graph tr... | Consider a sequence of actions that moves the token from vertex $1$ to vertex $n$. Let us say it has $A$ token movements and $B$ graph transpositions. This sequence takes $A + 2^{B} - 1$ seconds. Note that the optimal path does not visit any edge twice. That means we need to consider only paths with $A \le m$. Consider... | [
"dfs and similar",
"graphs",
"greedy",
"shortest paths"
] | 2,400 | null |
1442 | D | Sum | You are given $n$ \textbf{non-decreasing} arrays of non-negative numbers.
Vasya repeats the following operation $k$ times:
- Selects a non-empty array.
- Puts the first element of the selected array in his pocket.
- Removes the first element from the selected array.
Vasya wants to maximize the sum of the elements in... | Straightforward dp solution, where $s(i, j)$ - max possible sum after $j$ operations on first $i$ arrays and transition in $O(k)$, has complexity of $O(nk^2)$ or precisely $O(k \cdot min(nk, \sum\limits_{i=1}^n t_i))$ and doesn't fit into the time limit. Taking into account the fact that the arrays are sorted helps to ... | [
"data structures",
"divide and conquer",
"dp",
"greedy"
] | 2,800 | null |
1442 | E | Black, White and Grey Tree | You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white a... | Let's solve the task step by step: Suppose that tree is a bamboo without the grey vertices. Such a tree can be viewed as an array of colors $1$ and $2$. We can see that if there are two adjacent vertices of equal color, we can always delete them together in one operation. We can merge adjacent vertices of the same colo... | [
"binary search",
"constructive algorithms",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 3,000 | null |
1442 | F | Differentiating Games | This is an interactive problem
Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam.
As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a dire... | Let's first solve the problem for an empty graph. To do this we need to build a construction with not too many edges, where all vertices are pairwise not equivalent. For acyclic graph, there is not such construction. All Grundy functions of vertices should be different, so they must be integers from 0 to $n-1$. The onl... | [
"games",
"interactive"
] | 3,400 | null |
1443 | A | Kids Seating | Today the kindergarten has a new group of $n$ kids who need to be seated at the dinner table. The chairs at the table are numbered from $1$ to $4n$. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers $a$ and $b$ ($a \neq b$) will indulge if:
- $gcd(a, b) = 1$ or,
- $a$ divid... | Note that this seating arrangement for children satisfies all conditions: $4n, 4n-2, 4n-4, \ldots, 2n+2$. | [
"constructive algorithms",
"math"
] | 800 | null |
1443 | B | Saving the City | Bertown is a city with $n$ buildings in a straight line.
The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $n$, where the $i$-th character is "1" if there is a mine under the building number $i$ and "0" otherwise.
Bertown's best sapper knows how to ... | Since the activation of any mine explodes the entire segment of mines, which it is, you can immediately replace the input string with an array of mine segments. We now have two operations. We can delete any segment by $a$ coins, or turn two adjacent segments $[l_1, r_1]$, $[l_2, r_2]$ ($r_1 < l_2$) into one segment for... | [
"dp",
"greedy",
"math",
"sortings"
] | 1,300 | null |
1443 | C | The Delivery Dilemma | Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up h... | If we order a courier with time $x$, then all couriers with time $y < x$ can also be ordered, since they do not change the answer (all couriers work in parallel). Therefore, you can sort the array, couriers always bring the prefix of the array, and Petya will go for the suffix. The time prefix is the maximum $b[i]$, an... | [
"binary search",
"greedy",
"sortings"
] | 1,400 | null |
1443 | E | Long Permutation | A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ — are permutations, and $[1, 1]$, $[4, 3, 1]$, $[2, 3, 4]$ — no.
Permutation $a$ is lexicographically smaller than permutation $b$ (they have the same length $n$... | Let's notice that most of the elements in the original permutation will not change during all queries. Since the maximum permutation number does not exceed $10^{10}$, only the last $15$ elements of the permutation will change. Thus, after each query of the second type, you need to generate a permutation with the corres... | [
"brute force",
"math",
"two pointers"
] | 2,400 | null |
1444 | A | Division | Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.
To improve his division skills, Oleg came up with $t$ pairs of integers $p_i$ and $q_i$ and for each pair decided to find the \textbf{greatest} integer $x_i$, such that:
- $p_i$ is divisible by $x_i$;
- $x_i$ is not div... | Let $y = p / x$. Let's assume, that there exists prime $a$, such that $a$ divides $y$, but $q$ is not divisible by $a$. Then we can multiply $x$ and $a$ and the result will still divide $p$, but will not be divisible by $q$. So for maximal $x$ there is no such $a$. Let's assume, that there are two primes $a$ and $b$, s... | [
"brute force",
"math",
"number theory"
] | 1,500 | null |
1444 | B | Divide and Sum | You are given an array $a$ of length $2n$. Consider a partition of array $a$ into two subsequences $p$ and $q$ of length $n$ each (each element of array $a$ should be in exactly one subsequence: either in $p$ or in $q$).
Let's sort $p$ in non-decreasing order, and $q$ in non-increasing order, we can denote the sorted ... | No matter how we split the array, the cost of a partition will always be the same. Let's prove it. Without loss of generality we will consider that the array $a$ sorted and denote for $L$ the set of elements with indexes from $1$ to $n$, and for $R$ the set of elements with indexes from $n + 1$ to $2n$. Then split the ... | [
"combinatorics",
"math",
"sortings"
] | 1,900 | null |
1444 | C | Team-Building | The new academic year has started, and Berland's university has $n$ first-year students. They are divided into $k$ academic groups, however, some of the groups might be empty. Among the students, there are $m$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different grou... | You're given an undirected graph without loops and multiple edges, each vertex has some color from $1$ to $k$. Count the number of pairs of colors such that graph induced by vertices of these two colors will be bipartite. Let's check for each color whether the graph induced by it is bipartite (for example, using depth-... | [
"data structures",
"dfs and similar",
"dsu",
"graphs"
] | 2,500 | null |
1444 | D | Rectangular Polyline | One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersecti... | First, note that in a correct polyline, since the horizontal and vertical segments alternate, $h=v$: if this equality does not hold, the answer is negative. Now let's fix a vertex and go around the polyline in some direction. Then in the process of traversin, we will move in one of four possible directions: up, down, r... | [
"constructive algorithms",
"dp",
"geometry"
] | 2,900 | null |
1444 | E | Finding the Vertex | \textbf{This is an interactive problem.}
You are given a tree — connected undirected graph without cycles. One vertex of the tree is special, and you have to find which one. You can ask questions in the following form: given an edge of the tree, which endpoint is closer to the special vertex, meaning which endpoint's ... | Consider the optimal strategy. Some edge will be your first query, mark it with a number $0$. After that, build similar colourings (recursively) for components on both sides of the edge, but increase their weights by one (to have only one zero in total). This colouring corresponds to the strategy, and if $k$ is the max... | [
"brute force",
"dfs and similar",
"dp",
"interactive",
"trees"
] | 3,500 | null |
1445 | A | Array Rearrangment | You are given two arrays $a$ and $b$, each consisting of $n$ positive integers, and an integer $x$. Please determine if one can rearrange the elements of $b$ so that $a_i + b_i \leq x$ holds for each $i$ ($1 \le i \le n$). | It's enough to sort $a$ in non-decreasing order and sort $b$ in non-increasing order and check, whether $a_i + b_i \leq x$ for all $i$. Correctness can be proven by induction: let's show that if answer exists, there is a solution with minimum in $a$ and maximum in $b$ are paired. Let $m_a$ be minimum in $a$ and $m_b$ b... | [
"greedy",
"sortings"
] | 800 | null |
1445 | B | Elimination | There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.
A result of the elimination stage is the tota... | The answer is at least $\max(a + b, d + c)$ because we have at least $100$ participants with the sum of $a + b$ and at least $100$ participants with the sum of $d + c$. If we have $99$ participants with points equal to $(a, c)$, and $2$ participants with points equal to $(a, b)$ and $(d, c)$, then the 100th participant... | [
"greedy",
"math"
] | 900 | null |
1446 | A | Knapsack | You have a knapsack with the capacity of $W$. There are also $n$ items, the $i$-th one has weight $w_i$.
You want to put some of these items into the knapsack in such a way that their total weight $C$ is at least half of its size, but (obviously) does not exceed it. Formally, $C$ should satisfy: $\lceil \frac{W}{2}\rc... | Are there any items which you can put in the knapsack to fulfill the goal with one item? What happens if there are none? If there is an item of size $C$ satisfying: $\lceil \frac{W}{2}\rceil \le C \le W$, it is enough to output only that item. Otherwise, we should exclude items which are larger than the size of the kna... | [
"constructive algorithms",
"greedy",
"sortings"
] | 1,300 | null |
1446 | B | Catching Cheaters | You are given two strings $A$ and $B$ representing essays of two students who are suspected cheaters. For any two strings $C$, $D$ we define their similarity score $S(C,D)$ as $4\cdot LCS(C,D) - |C| - |D|$, where $LCS(C,D)$ denotes the length of the Longest Common \textbf{Subsequence} of strings $C$ and $D$.
You belie... | This is a dynamic programming problem. Recall the DP calculating the Longest Common Substring for two strings. What similarities are there in our setup, and what differs? If a substring has a negative score, we can throw it away and start from scratch. Let $DP[i][j]$ be the maximum similarity score if we end the first ... | [
"dp",
"strings"
] | 1,800 | null |
1446 | C | Xor Tree | For a given sequence of \textbf{distinct} non-negative integers $(b_1, b_2, \dots, b_k)$ we determine if it is \textbf{good} in the following way:
- Consider a graph on $k$ nodes, with numbers from $b_1$ to $b_k$ written on them.
- For every $i$ from $1$ to $k$: find such $j$ ($1 \le j \le k$, $j\neq i$), for which $(... | Is it possible that the graph formed has a cycle? How to evaluate whether a sequence is good? Since we have $n$ edges and two of them must coincide (the pair of numbers with the smallest xor), we will have at most $n-1$ edges in the graph. Thus, we only need to check if the resulting graph is connected. How to do it? L... | [
"binary search",
"bitmasks",
"data structures",
"divide and conquer",
"dp",
"trees"
] | 2,100 | null |
1446 | D1 | Frequency Problem (Easy Version) | \textbf{This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.}
You are given an array $[a_1, a_2, \dots, a_n]$.
Your goal is to find the length of the longest subarray of this array s... | What can you say about the values which are the most frequent ones in the optimal solution? Let $D$ be the most frequent value in the whole sequence. If $D$ is not unique, we output $n$. Otherwise, we can prove that one of the most frequent values in an optimal solution is $D$. We'll prove this by contradiction. Consid... | [
"data structures",
"greedy"
] | 2,600 | null |
1446 | D2 | Frequency Problem (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.}
You are given an array $[a_1, a_2, \dots, a_n]$.
Your goal is to find the length of the longest subarray of this array s... | A bit of thinking may lead you to the observation that solving the task in $O(n log n)$ or even $O(n log^2 n)$ isn't pleasant. The constraints are low enough to allow an $O(n \sqrt n)$ solution, how about giving it a try? If an element $V$ appears more than $\sqrt n$ times, we can simply brute-force this pair with part... | [
"data structures",
"greedy",
"two pointers"
] | 3,000 | null |
1446 | E | Long Recovery | A patient has been infected with an unknown disease. His body can be seen as an infinite grid of triangular cells which looks as follows:
Two cells are neighboring if they share a side. Therefore, each cell ($x$, $y$) has exactly three neighbors:
- ($x+1$, $y$)
- ($x-1$, $y$)
- ($x+1$, $y-1$) if $x$ is even and ($x-1... | We're interested in the longest possible recovery path, so let's imagine choosing the longest sequence of operations ourselves. How long can this process last? Let $P$ be the number of pairs of neighboring cells with different state. Consider what happens to $P$ after an operation where we change the state of a cell $c... | [
"constructive algorithms",
"dfs and similar"
] | 3,500 | null |
1446 | F | Line Distance | You are given an integer $k$ and $n$ distinct points with integer coordinates on the Euclidean plane, the $i$-th point has coordinates $(x_i, y_i)$.
Consider a list of all the $\frac{n(n - 1)}{2}$ pairs of points $((x_i, y_i), (x_j, y_j))$ ($1 \le i < j \le n$). For every such pair, write out the distance from the lin... | Binary search is your friend. To determine if the answer is bigger or smaller than $r$, we need to count the number of pairs of points $A$, $B$ such that $d(O, AB) > r$. We need to reformulate the condition $d(O, AB) > r$ to make the counting easier. Draw a circle of radius $r$ centered on $O$, and consider two points ... | [
"binary search",
"data structures",
"geometry"
] | 3,200 | null |
1447 | A | Add Candies | There are $n$ bags with candies, initially the $i$-th bag contains $i$ candies. You want all the bags to contain an equal amount of candies in the end.
To achieve this, you will:
- Choose $m$ such that $1 \le m \le 1000$
- Perform $m$ operations. In the $j$-th operation, you will pick one bag and add $j$ candies to a... | We're only interested in differences between the elements. Is there another way to express the operation? The operation in the $i$-th turn is equivalent to selecting one element and subtracting $i$ from it. The sequence $1$, $2$, ..., $n$ satisfies task's constraints. After the additions all positions will contain $\fr... | [
"constructive algorithms",
"math"
] | 800 | null |
1447 | B | Numbers Box | You are given a rectangular grid with $n$ rows and $m$ columns. The cell located on the $i$-th row from the top and the $j$-th column from the left has a value $a_{ij}$ written in it.
You can perform the following operation any number of times (possibly zero):
- Choose any two adjacent cells and multiply the values i... | We want to minimize the number of negative numbers as much as we can by applying the operations. What is the minimum possible number of those negatives? Let $X$ be the number of non-zero numbers in the grid, and let's see what happens in different scenarios. both cells have negative numbers, then $X$ goes down by $2$. ... | [
"greedy",
"math"
] | 1,000 | null |
1450 | A | Avoid Trygub | A string $b$ is a subsequence of a string $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string $a$. Your task is to reorder the characters of $a$ so that "trygub" is not a subsequence o... | The string "trygub" is not sorted alphabetically, and a subsequence of a sorted string is necessarily sorted. So, if we sort the input string, it will be a solution. Complexity is $O(n)$ with counting sort. | [
"constructive algorithms",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int te;
cin >> te;
while(te--) {
int n; string s;
cin >> n >> s;
sort(s.begin(), s.end());
cout << s << '\n';
}
} |
1450 | B | Balls of Steel | You have $n$ \textbf{distinct} points $(x_1, y_1),\ldots,(x_n,y_n)$ on the plane and a non-negative integer parameter $k$. Each point is a microscopic steel ball and $k$ is the attract power of a ball when it's charged. The attract power is the same for all balls.
In one operation, you can select a ball $i$ to charge ... | We claim the answer is always $-1$ or $1$. In fact, suppose in the first operation of a solution we select a point $p$. If we aren't done, there will at least one point with distance more than $k$ from $p$. However, there will be no point within distance $k$ of $p$, no matter how we perform future operations. So it is ... | [
"brute force",
"geometry",
"greedy"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<pair<int, int>> a(n);
for (auto &i : a)
cin >> i.first >> i.second;
int ans = -1;
for (int i = 0; i < n; ++i) {
int mx = 0;
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.