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
1450
C1
Errich-Tac-Toe (Easy Version)
\textbf{The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.} Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are $n$ rows and $n$ column...
For each cell $(i,j)$, let's associate it with the color $(i+j)\bmod 3$. Every three consecutive cells contains one of each color. So, if we choose one color and flip all tokens with that color, it will be a solution. We need only prove that there is a color associated with at most one third of the tokens. Let there be...
[ "constructive algorithms", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 305; int n; string s[N]; void solve() { cin >> n; // cnt[color] = occurrences of X on that color cell. int cnt[3] = {0, 0, 0}; for(int i = 0; i < n; i++) { cin >> s[i]; for(int j = 0; j < n; j++) { if(s[i][j] =...
1450
C2
Errich-Tac-Toe (Hard Version)
\textbf{The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.} Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are $n$ rows and $n$ column...
If for every three consecutive tokens in the grid, we make sure there is an X and there is an O, we are done. For each cell $(i,j)$, let's associate it with the color $(i+j)\bmod 3$. Since every three consecutive cells contains one of each color, if we make all of one color X and all of a different color O, it would be...
[ "constructive algorithms", "math" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 305; int te, n; string s[N]; void solve() { cin >> n; // Let X = 0, O = 1. Let cnt[r][b] = the number of tokens b in diagonals with label r. int cnt[3][2] = {{0, 0}, {0, 0}, {0, 0}}; int k = 0; for(int i = 0; i < n; i++) { cin...
1450
D
Rating Compression
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers $a$ of length $n$. You are now updating the infrastructure, so you've created a program to compress these graphs. The program works as follows. Given an integer parameter $k$, the program takes the minim...
For $k=1$, we simply need to check that the array is a permutation. If $k=n$, we simply need to check that the array has minimum $1$. For $1<k<n$, we know the $k$-compression should contain exactly one occurrence of $1$. But $1$ is the minimum possible element, so it should occur in only one length $k$ subarray. Theref...
[ "binary search", "data structures", "greedy", "implementation", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; const int mxN = 300001; int arr[mxN]; // input array int cnt[mxN]; // cnt[x] = number of occurrences of x in the array bool ans[mxN]; // the final answer int n; void solve() { cin>>n; for(int i = 0; i <= n; ++i) { cnt[i] = 0; ans[i] = 0; } ...
1450
E
Capitalism
A society can be represented by a connected, undirected graph of $n$ vertices and $m$ edges. The vertices represent people, and an edge $(i,j)$ represents a friendship between people $i$ and $j$. In society, the $i$-th person has an income $a_i$. A person $i$ is envious of person $j$ if $a_j=a_i+1$. That is if person ...
Firstly, each edge connects a person with even income and a person with odd income. So if the graph is not bipartite, then a solution does not exist. Consider a friendship between people $u$ and $v$, where we don't know the direction. Since $|a_u-a_v|=1$, we know that $a_u-a_v\le 1$ and $a_v-a_u\le 1$. Consider a direc...
[ "constructive algorithms", "dfs and similar", "graphs", "shortest paths" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 205, M = 2005; int n, m, u[M], v[M], b[M]; int dist[N][N]; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(i != j) dist[i][j] = INT_MA...
1450
F
The Struggling Contestant
To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants. The contest consists of $n$ problems, where the tag of the $i$-th problem is denote...
Suppose $p$ is a permutation that satisfies the condition. Imagine we add a divider between adjacent indices that are not adjacent in $p$. If $k$ is the number of "jumps" in $p$, then we have split the array $a$ into $k+1$ consecutive segments. The permutation will scan these segments in some order, and each segment ca...
[ "constructive algorithms", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); vector<int> f(n + 1, 0), ends(n + 1, 0); int cuts = 0; for(int i = 0; i < n; i++) { cin >> a[i]; f[a[i]]++; if(i > 0 && a[i] == a[i - 1]) { ends[a[i]]++; ...
1450
G
Communism
\textbf{Please pay attention to the unusual memory limit in this problem.} In a parallel universe, Satan is called "Trygub". For that reason, the letters of his namesake were deleted from the alphabet in ancient times. The government has $n$ workers standing in a row and numbered with integers from $1$ to $n$ from le...
Let $C$ denote the set of distinct characters in $s$. Suppose there is a sequence of operations that transforms every character to $x$ in the end. For an operation where we transform all occurrences of $y$ to $z$, let's add a directed edge $(y\to z)$. The resulting structure is a directed tree rooted at $x$. This is be...
[ "bitmasks", "dp", "trees" ]
3,500
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0), cin.tie(0); int n, ka, kb; string s; cin >> n >> ka >> kb >> s; // sort characters of string by first occurrence int p = 0; vector<int> id(26, -1); vector<char> mp(26); for (int i = 0; i < n; ++i) { int c = s[...
1450
H1
Multithreading (Easy Version)
\textbf{The only difference between the two versions of the problem is that there are no updates in the easy version.} There are $n$ spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white. For any two spools of the same ...
Lets first solve for a given coloring, $c$, the value of $f(c)$. Let $B_{odd}$, $B_{even}$ denote the number of black spots on even positions, and odd positions respectively. We notate similarly for $W_{odd}$ and $W_{even}$. Claim: $f(c) = \frac12 |B_{odd} - B_{even}|$. Proof: Let's show for any coloring where $B_{odd}...
[ "combinatorics", "fft", "math" ]
2,900
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll MOD = 998244353; const int mxN = 200001; ll fact[mxN], ifact[mxN]; ll nCr(int n, int r) { if(n==r)return 1; if(r > n || r < 0)return 0; return ((fact[n]*ifact[n-r])%MOD*ifact[r])%MOD; } ll binpow(ll a,ll b) { ll res=1; whil...
1450
H2
Multithreading (Hard Version)
\textbf{The only difference between the two versions of the problem is that there are no updates in the easy version.} There are $n$ spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white. For any two spools of the same ...
Continued from Easy Version tutorial. Recall the answer is $\frac{1}{2^F}\sum_{0\le i\le F\atop i\equiv x\pmod 2} |x-i| {{F}\choose{i}}.$ Now we have to maintain this sum over updates. Let's ignore the $2^{F}$, and rewrite the sum as $\sum_{0\le i\le x-2\atop i\equiv x\pmod 2} x{{F}\choose{i}} - \sum_{0\le i\le x-2\ato...
[ "combinatorics", "implementation", "math" ]
3,300
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll MOD = 998244353; const int mxN = 200001; ll fact[mxN], ifact[mxN]; ll nCr(int n, int r) { if(r > n || r < 0)return 0; return ((fact[n]*ifact[n-r])%MOD*ifact[r])%MOD; } ll binpow(ll a,ll b) { ll res=1; while(b) { if(b&1)...
1451
A
Subtract or Divide
Ridbit starts with an integer $n$. In one move, he can perform one of the following operations: - divide $n$ by one of its \textbf{proper} divisors, or - subtract $1$ from $n$ if $n$ is greater than $1$. A proper divisor is a divisor of a number, excluding itself. For example, $1$, $2$, $4$, $5$, and $10$ are proper...
Key Idea: For $n > 3$, the answer is $2$ when $n$ is even and $3$ when $n$ is odd. Cases when $n \leq 3$ can be handled separately. Solution: Case 1: $n \leq 3$ For $n = 1, 2, 3$, it can be shown that the minimum number of operations required are $0$, $1$, $2$ respectively. Case 2: $n > 3$ and $n$ is even If $n$ is eve...
[ "greedy", "math" ]
800
import java.util.*; import java.util.ArrayList; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++) { int n = sc.nextInt(); System.out.println(Math.min(2 + (n & ...
1451
B
Non-Substring Subsequence
Hr0d1y has $q$ queries on a binary string $s$ of length $n$. A binary string is a string containing only characters '0' and '1'. A query is described by a pair of integers $l_i$, $r_i$ $(1 \leq l_i \lt r_i \leq n)$. For each query, he has to determine whether there exists a good subsequence in $s$ that is equal to th...
Key Idea: In each query, the answer is YES iff the first character of the given substring is not the first occurence of that character or the last character of the given substring is not the last occurrence of that character in the string. Solution: The condition stated above is both necessary and sufficient. Proof tha...
[ "dp", "greedy", "implementation", "strings" ]
900
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int cases = 0; cases < t; cases++) { ...
1451
C
String Equality
Ashish has two strings $a$ and $b$, each of length $n$, and an integer $k$. The strings only contain lowercase English letters. He wants to convert string $a$ into string $b$ by performing some (possibly zero) operations on $a$. In one move, he can either - choose an index $i$ ($1 \leq i\leq n-1$) and swap $a_i$ and...
Key Idea: For the answer to be YES, the frequencies of each character of the alphabet must match after performing some sequence of operations. Let $freq_{i, a}$ and $freq_{i, b}$ be the frequencies of the $i$-th character of the alphabet in strings $a$ and $b$ respectively. For each $i$ starting from "a", we keep exact...
[ "dp", "greedy", "hashing", "implementation", "strings" ]
1,400
import java.util.*; import java.util.ArrayList; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int cases = 0; cases < t; cases++) { int n = sc.nextInt(); int k = sc.nextInt(); ...
1451
D
Circle Game
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves \textbf{first}. Consider the 2D plane. There is a token which is initially at \textbf{$(0,0)$}. In one move a player must increase either the $x$ coordinate or the $y$ coordinate of the token by \te...
Key Idea: Let $z$ be the maximum integer such that the point $(kz, kz)$ is within the circle. If the point $(kz, k(z+1))$ is also within the circle, player 1 wins. Otherwise player 2 wins. Solution: Regardless of what move player 1 makes, player 2 can force the token to be at some point on the line $x = y$ at the end o...
[ "games", "geometry", "math" ]
1,700
import java.util.*; import java.util.ArrayList; public class Main { public static boolean is_within(long x, long y, long dsq, long k) { return dsq - k * k * x * x - k * k * y * y >= 0; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc....
1451
E1
Bitwise Queries (Easy Version)
\textbf{The only difference between the easy and hard versions is the constraints on the number of queries.} \textbf{This is an interactive problem.} Ridbit has a hidden array $a$ of $n$ integers which he wants Ashish to guess. Note that $n$ is a \textbf{power of two}. Ashish is allowed to ask three different types o...
Key Idea: $a + b = (a \oplus b) + 2 * (a \& b)$ Pick and distinct $i, j, k$ and find $a_{i} + a_{j} = x$, $a_{i} + a_{k} = y$ and $a_{j} + a_{k} = z$ by querying their XOR and AND values ($6$ queries). This is a system of linear equation with three equations and three variables and thus us a unique solution. Solving it...
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
2,000
import java.util.Scanner; public class Main { public static int queries(String s, Scanner sc) { System.out.println(s); System.out.flush(); int x = sc.nextInt(); if(x == -1) System.exit(0); return x; } public static void main(String args[]) { ...
1451
E2
Bitwise Queries (Hard Version)
\textbf{The only difference between the easy and hard versions is the constraints on the number of queries.} \textbf{This is an interactive problem.} Ridbit has a hidden array $a$ of $n$ integers which he wants Ashish to guess. Note that $n$ is a \textbf{power of two}. Ashish is allowed to ask three different types o...
Key Idea: Query the $n - 1$ xor values of the form $(1, i)$, for $2 \leq i \leq n$ initially. Since numbers lie in the range $[0, n - 1]$, one of two cases can arise: 1. There exists indices j, k such that $a_{j} = a_{k}$. This can be found as $a_{i}$ $\oplus$ $a_{j}$ $=$ $a_{i}$ $\oplus$ $a_{k}$. So we can just use th...
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
2,300
import java.util.*; import java.util.ArrayList; public class Main { public static int queries(String s, int i, int j, Scanner sc) { System.out.println(s + " " + i + " " + j); System.out.flush(); int x = sc.nextInt(); if(x == -1) System.exit(0); return x; }...
1451
F
Nullify The Matrix
Jeel and Ashish play a game on an $n \times m$ matrix. The rows are numbered $1$ to $n$ from top to bottom and the columns are numbered $1$ to $m$ from left to right. They play turn by turn. Ashish goes \textbf{first}. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform...
Let's consider diagonals $d$ of the form $r+c$ - the diagonals where the sum of row index $(r)$ and column index $(c)$ is constant. Then xor of a diagonal $d$ will be $xor(d) = a(r_1,c_1)\oplus a(r_2,c_2)\oplus...a(r_n,c_n)$, such that $r_1 + c_1 = d$, $r_2 + c_2 = d$, .... $r_n + c_n = d$. $Solution:$ If $\forall d,\h...
[ "constructive algorithms", "games" ]
2,700
import java.util.*; public class NullifyTheMatrix { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int x = 0; x < t; ++x) { int n = sc.nextInt(); int m = sc.nextInt(); int mat[][] = new int[n][...
1452
A
Robot Program
There is an infinite 2-dimensional grid. The robot stands in cell $(0, 0)$ and wants to reach cell $(x, y)$. Here is a list of possible commands the robot can execute: - move north from cell $(i, j)$ to $(i, j + 1)$; - move east from cell $(i, j)$ to $(i + 1, j)$; - move south from cell $(i, j)$ to $(i, j - 1)$; - mov...
Obviously, you can always obtain the optimal answer without using west or south moves. So the shortest path consists of $x$ east moves and $y$ north moves. Let's estimate the lower bound of the answer. Take a look at these constructions: "E?E?E?E?E" and "N?N?N?N?N" (let question mark be any command different from the u...
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int x, y; cin >> x >> y; int ans = max(x, y) * 2 - 1; if(x == y) ans++; cout << ans << endl; } }
1452
B
Toy Blocks
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has $n$ boxes and the $i$-th box has $a_i$ blocks. His game consists of two steps: - he chooses an arbitrary box $i$; - he tries to move \textbf{all} blocks from the $i$-th box to other boxes. If he can make the same number of ...
Since nephew emptying the box $i$ he's chosen and wants to make all other $n - 1$ box equal then it means that at least the $sum$ of all array $a$ should be divisible by $(n - 1)$ and the number of blocks in each other box should be at least $\left\lceil \frac{sum}{n - 1} \right\rceil$ (ceiling function). On the other ...
[ "binary search", "greedy", "math", "sortings" ]
1,400
fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toLong() } val k = maxOf(a.max()!!, (a.sum() + n - 2) / (n - 1)) println(k * (n - 1) - a.sum()) } }
1452
C
Two Brackets
You are given a string $s$, consisting of brackets of two types: '(', ')', '[' and ']'. A string is called a regular bracket sequence (RBS) if it's of one of the following types: - empty string; - '(' + RBS + ')'; - '[' + RBS + ']'; - RBS + RBS. where plus is a concatenation of two strings. In one move you can choo...
Notice that it's never optimal to erase a subsequence of length greater than $2$ because every RBS of length above $2$ contains an RBS of length $2$ inside and removing it won't break the regular property of the outside one. So the task can be solved for the round and the square brackets independently, the answer will ...
[ "greedy" ]
800
def calc(s, x, y): bal, cnt = 0, 0 for c in s: if c == y: if bal > 0: bal -= 1 cnt += 1 elif c == x: bal += 1 return cnt for _ in range(int(input())): s = input() print(calc(s, '(', ')') + calc(s, '[', ']'))
1452
D
Radio Towers
There are $n + 2$ towns located on a coordinate line, numbered from $0$ to $n + 1$. The $i$-th town is located at the point $i$. You build a radio tower in each of the towns $1, 2, \dots, n$ with probability $\frac{1}{2}$ (these events are independent). After that, you want to set the signal power on each tower to som...
The crucial observation is that when the positions of towers are fixed, the way to set their signal powers is unique if it exists. That's because the first tower should have its signal power exactly equal to the required to cover all towns before it, the second tower should have signal power exactly equal to the requir...
[ "combinatorics", "dp", "math" ]
1,600
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int ans = 1; while(y > 0) { i...
1452
E
Two Editorials
Berland regional ICPC contest has just ended. There were $m$ participants numbered from $1$ to $m$, who competed on a problemset of $n$ problems numbered from $1$ to $n$. Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to \textbf{exactly $k$ consecuti...
Consider some participant's segment $[l; r]$ and one of the author's segment $[i; i + k - 1]$. How does the length of intersection change when you move $i$ from left to right? It first increases until the centers of both segments coincide (that's the easiest to notice on the segments of the same length) and then decrea...
[ "brute force", "dp", "greedy", "sortings", "two pointers" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct seg{ int l, r; }; int main() { int n, m, k; cin >> n >> m >> k; vector<seg> a(m); forn(i, m){ cin >> a[i].l >> a[i].r; --a[i].l; } sort(a.begin(), a.end(), [](const seg &a, const seg &b){ return a.l...
1452
F
Divide Powers
You are given a multiset of powers of two. More precisely, for each $i$ from $0$ to $n$ exclusive you have $cnt_i$ elements equal to $2^i$. In one operation, you can choose any one element $2^l > 1$ and divide it into two elements $2^{l - 1}$. You should perform $q$ queries. Each query has one of two types: - "$1$ $...
Several observations: Generally, we have two types of operations: divide $2^l$ and either $l \le x$ or $l > x$. If $2^l \le 2^x$ then in one division we'll get $+1$ element $\le 2^x$, so we can just keep track of the total possible number of these operations as $small$. If $2^l > 2^x$ then if we decide to split whole $...
[ "constructive algorithms", "greedy" ]
2,900
#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; template<class A, class B> ostream& operator <<(ostream& out, const pair<A,...
1452
G
Game On Tree
Alice and Bob are playing a game. They have a tree consisting of $n$ vertices. Initially, Bob has $k$ chips, the $i$-th chip is located in the vertex $a_i$ (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree. The game consists of turns. Each turn, the f...
This task was inspired by an older edu task and another task proposed by RockyB. Let's learn to solve the problem for at least one starting vertex for Alice. Let this vertex be $v$. In general, Alice's strategy is basically this: run to some vertex $u$ as fast as possible and stay in it until Bob reaches $u$. Hesitatio...
[ "data structures", "dfs and similar", "greedy", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; const int N = 200043; const int LN = 18; vector<int> g[N]; vector<int> dist[N]; int sz[N]; int par[N]; bool used[N]; int max_dist[N]; vector<int> val[N]; int calc_size(int x, int p = -1) { sz[x] = 1; for(auto y : g[x]) if(y != p && !used[y]) s...
1453
A
Cancel the Trains
Gildong's town has a train system that has $100$ trains that travel from the bottom end to the top end and $100$ trains that travel from the left end to the right end. The trains starting from each side are numbered from $1$ to $100$, respectively, and all trains have the same speed. Let's take a look at the picture be...
Let's first determine whether it's possible for two trains that start from $(i,0)$ and $(0,j)$ to crash into each other. For this to happen, there must be a point where $(i,T)=(T,j)$, which means $i=T$ and $j=T$. Therefore, a train that starts from the bottom end can crash into a train that starts from the left end if ...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100; const int MAX_COORD = 100; void solve() { int n, m, i, j; cin >> n >> m; bool v[MAX_COORD + 5] = { 0 }; int ans = 0; for (i = 0; i < n; i++) { int x; cin >> x; v[x] = true; } for (i = 0; i < m; i++) { int x; cin >> x; if (v[...
1453
B
Suffix Operations
Gildong has an interesting machine that has an array $a$ with $n$ integers. The machine supports two kinds of operations: - Increase all elements of a suffix of the array by $1$. - Decrease all elements of a suffix of the array by $1$. A suffix is a subsegment (contiguous elements) of the array that contains $a_n$. I...
First, let's find the optimal strategy for Gildong to follow to make all elements of the array equal. It's obvious that there is no need to perform any operation on the suffix starting at $a_1$, since that operation changes all the integers in the array. For $i=2$ to $n$, the only way for $a_i$ to have equal value to $...
[ "constructive algorithms", "implementation" ]
1,400
def solve(): n = int(input()) a = [0] + list(map(int, input().split())) ans = 0 for i in range(2, n + 1): ans += abs(a[i] - a[i - 1]) mx = max(abs(a[2] - a[1]), abs(a[n] - a[n - 1])) for i in range(2, n): mx = max(mx, abs(a[i] - a[i - 1]) + abs(a[i + 1] - a[i]) - ab...
1453
C
Triangles
Gildong has a square board consisting of $n$ rows and $n$ columns of square cells, each consisting of a single digit (from $0$ to $9$). The cell at the $j$-th column of the $i$-th row can be represented as $(i, j)$, and the length of the side of each cell is $1$. Gildong likes big things, so for each digit $d$, he want...
Let's consider each $d$ separately. For each cell that has the digit $d$, we'll check the case where this cell is used as a vertex of the end of a horizontal or vertical side (i.e. the base) of the triangle, and change the digit of another cell and use it as the other end of that side. Let's say the position for this c...
[ "greedy", "implementation" ]
1,700
import sys import copy input = sys.stdin.readline MAX_N = 2000 inf = MAX_N + 9 def solve(a): global inf mnr = [inf]*10 mxr = [0]*10 mnc = [inf]*10 mxc = [0]*10 ans = [0]*10 for i in range(1, n+1): for j in range(1, n+1): x = a[i][j] mnr[x] = min(mnr...
1453
D
Checkpoints
Gildong is developing a game consisting of $n$ stages numbered from $1$ to $n$. The player starts the game from the $1$-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the $n$-th stage. There is at most one checkpoint on each stage, and there is alway...
As already explained in the notes (and is quite obvious), the expected number of tries to beat stage $i$ with a checkpoint where stage $i+1$ also has a checkpoint (or is the end of the game) is $2$. What if stage $i+1$ doesn't have a checkpoint and stage $i+2$ has a checkpoint? We can think of it like this. It takes $2...
[ "brute force", "constructive algorithms", "greedy", "math", "probabilities" ]
1,900
import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); static final int MAX_N = 2000; public static void main(String[] args) { int t = sc.nextInt(); while (t-- > 0) solve(); } public static void solve() { long k = sc.nextLong(); if (k % 2 == 1) { System.out.println...
1453
E
Dog Snacks
Gildong is playing with his dog, Badugi. They're at a park that has $n$ intersections and $n-1$ bidirectional roads, each $1$ meter in length and connecting two intersections with each other. The intersections are numbered from $1$ to $n$, and for every $a$ and $b$ ($1 \le a, b \le n$), it is possible to get to the $b$...
It is obvious that the problem can be modeled as a tree rooted at the $1$-st vertex. Given a large enough $k$, we can see that Badugi will always 'clear out' each subtree and then move back to its parent. This is because if there exists an unvisited child for a vertex, the distance between them is $1$, while any unvisi...
[ "binary search", "dfs and similar", "dp", "greedy", "trees" ]
2,300
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in))...
1453
F
Even Harder
Gildong is now developing a puzzle game. The puzzle consists of $n$ platforms numbered from $1$ to $n$. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the $1$-st platform to the $n$-th platform. The $i$-th platform is labeled with an inte...
Since there is at least one way to win initially, every platform is reachable from the start. Note that this condition should still hold after we achieve what Gildong wants. Because of this, if there are multiple $j$'s where $j + a_j \ge i$, there are at least two ways that can get to the $i$-th platform. Therefore, in...
[ "dp" ]
2,700
import sys input = sys.stdin.readline MAX_N = 3000 inf = MAX_N def solve(): global inf n = int(input()) a = [0] + list(map(int, input().split())) dp = [[0] * (n + 1) for i in range(n + 1)] for i in range(2, n + 1): cnt = 0 for j in range(i, n + 1): dp[i][j] = i...
1454
A
Special Permutation
You are given one integer $n$ ($n > 1$). Recall that a permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation of length $5$, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is al...
There are many possible solutions. One of them is just to print $2, 3, \ldots, n, 1$.
[ "constructive algorithms", "probabilities" ]
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; for (int i = 0; i < n; ++i) { cout << (i + 1) % n + 1 << " "; } cout << endl; } return 0; }
1454
B
Unique Bid Auction
There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem). Let's simplify this game a bit. Formally, there are $n$ participants, the $i$-th participant chose the number $a_i$. The winner of the g...
This is a simple implementation problem. Let's calculate two values for each $i$ from $1$ to $n$: $cnt_i$ - the number of occurrences of $i$ in $a$ and $idx_i$ - any position of $i$ in $a$. Then, let's iterate through $i$ from $1$ to $n$ and, if $cnt_i = 1$, just print $idx_i$ (because if it is the only such element th...
[ "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> cnt(n + 1), idx(n + 1); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x]; ...
1454
C
Sequence Transformation
You are given a sequence $a$, initially consisting of $n$ integers. You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element). To achieve this, you choose some integer $x$ \textbf{that occurs at least once in $a$}, and then perform the followi...
Firstly, let's remove all consecutive equal elements (just keep one occurrence of each such element). For example, the array $[1, 1, 2, 3, 3, 3, 2]$ becomes $[1, 2, 3, 2]$. Now, the answer for each $a_i$ is almost the number of its occurrences plus one. Why is it so? Because we need to remove all segments of elements b...
[ "greedy", "implementation" ]
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<int> res(n + 1, 1); n = unique(a.begin(), a....
1454
D
Number into Sequence
You are given an integer $n$ ($n > 1$). Your task is to find a sequence of integers $a_1, a_2, \ldots, a_k$ such that: - each $a_i$ is strictly greater than $1$; - $a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$ (i. e. the product of this sequence is $n$); - $a_{i + 1}$ is divisible by $a_i$ for each $i$ from $1$ to $k-1$...
Consider $n$ in this canonical form ${p_1}^{a_1} \cdot {p_2}^{a_2} \cdot \ldots \cdot {p_k}^{a_k}$ (just find the prime factorization of $n$). Let $i$ be such an index that $a_i$ is the maximum among all values of $a$. Then the answer length can not exceed $a_i$. This is because if the answer has greater length, then s...
[ "constructive algorithms", "math", "number theory" ]
1,300
#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--) { long long n; cin >> n; vector<pair<int, long long>> val; for (long long i = 2; i * i <= n; ++i) { int cnt = 0; w...
1454
E
Number of Simple Paths
You are given an \textbf{undirected} graph consisting of $n$ vertices and $n$ edges. It is guaranteed that the given graph is \textbf{connected} (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph. Your task is to calculate the number of \textbf{...
Because our graph is just a tree with an additional edge, consider it as a cycle with trees hanged on cycle vertices. Consider some tree hung on a vertex $v$ on a cycle. There is only one path between each pair of its vertices (including the root which is a vertex $v$). So, if the tree has $cnt_v$ vertices, then $\frac...
[ "combinatorics", "dfs and similar", "graphs", "trees" ]
2,000
#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<set<int>> g(n); for (int i = 0; i < n; ++i) { int x, y; cin >> x >> y; --x, --y; g[x...
1454
F
Array Partition
You are given an array $a$ consisting of $n$ integers. Let $min(l, r)$ be the minimum value among $a_l, a_{l + 1}, \ldots, a_r$ and $max(l, r)$ be the maximum value among $a_l, a_{l + 1}, \ldots, a_r$. Your task is to choose three \textbf{positive} (greater than $0$) integers $x$, $y$ and $z$ such that: - $x + y + z...
Let's fix the length of the first block (iterate through $i$ from $0$ to $n-3$). Let's also try to maximize the length of the third block using the second pointer. So, initially the length of the first block is $1$ and the maximum in the block is $a_0$ (after that, its length will be $2$ and the maximum will be $max(a_...
[ "binary search", "data structures", "greedy", "two pointers" ]
2,100
// Author: Ivan Kazmenko (gassa@mail.ru) module solution; import std.algorithm; import std.conv; import std.range; import std.stdio; import std.string; void main () { auto tests = readln.strip.to !(int); foreach (test; 0..tests) { auto n = readln.strip.to !(int); auto a = readln.splitter.map !(to !(int)).array;...
1455
A
Strange Functions
Let's define a function $f(x)$ ($x$ is a positive integer) as follows: write all digits of the decimal representation of $x$ backwards, then get rid of the leading zeroes. For example, $f(321) = 123$, $f(120) = 21$, $f(1000000) = 1$, $f(111) = 111$. Let's define another function $g(x) = \dfrac{x}{f(f(x))}$ ($x$ is a p...
Let's analyze which values can the function $g(x)$ have. It can be proven that the value of $g(x)$ is equal to $10^k$, where $k$ is the number of zero-digits at the end of the number $x$, because $f(f(x))$ is the same number as $x$ except for the fact that it doesn't have any trailing zeroes. Okay, now let's analyze wh...
[ "math", "number theory" ]
800
for i in range(int(input())): print(len(input()))
1455
B
Jumps
You are standing on the $\mathit{OX}$-axis at point $0$ and you want to move to an integer point $x > 0$. You can make several jumps. Suppose you're currently at point $y$ ($y$ may be negative) and jump for the $k$-th time. You can: - either jump to the point $y + k$ - or jump to the point $y - 1$. What is the minim...
At first, let's jump with $+k$ while $x$ is still greater than the current position. Now we finished in some position $pos = 1 + 2 + \dots + steps = \frac{steps (steps + 1)}{2} \ge x$. Note that $0 \le pos - x < steps$ otherwise, we wouldn't make the last step. If $pos = x$ then we are lucky to finish right in point $x...
[ "constructive algorithms", "math" ]
1,200
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int x; cin >> x; int steps = 0; while (steps * (steps + 1) < 2 * x) steps++; if (steps * (steps + 1) / 2 == x + 1) steps++; cout << steps << endl; } }
1455
C
Ping-pong
Alice and Bob play ping-pong with simplified rules. During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return. The one ...
Let's find an answer for a little different version of the game. Let's say that $f(x, y)$ is the final score if the first player has $x$ stamina and the second has $y$ stamina. The first player can either hit the ball or can give up and lose the play. How to calculate $f(x, y)$? Obviously, $f(0, x) = (0, x)$ and $f(x, ...
[ "constructive algorithms", "games", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int x, y; cin >> x >> y; cout << x - 1 << " " << y << endl; } int main() { int t; cin >> t; while (t--) solve(); }
1455
D
Sequence and Swaps
You are given a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$, and an integer $x$. Your task is to make the sequence $a$ sorted (it is considered sorted if the condition $a_1 \le a_2 \le a_3 \le \dots \le a_n$ holds). To make the sequence sorted, you may perform the following operation any number of t...
The main fact that allows us to solve this problem is that the value of $x$ always increases after swaps, and since the resulting sequence should be sorted, the indices of elements we swap with $x$ also increase. This observation is actually enough for us to implement a dynamic programming solution of the form "dp_{i, ...
[ "dp", "greedy", "sortings" ]
1,600
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A,...
1455
E
Four Points
You are given four different integer points $p_1$, $p_2$, $p_3$ and $p_4$ on $\mathit{XY}$ grid. In one step you can choose one of the points $p_i$ and move it in one of four directions by one. In other words, if you have chosen point $p_i = (x, y)$ you can move it to $(x, y + 1)$, $(x, y - 1)$, $(x + 1, y)$ or $(x - ...
Let's discuss two approaches to this problem. Firstly, let's think that we choose not four destination points but four lines on which sides of the square lie. It's two vertical lines with coordinates $x_1$ and $x_2$ and two horizontal lines $y_1$ and $y_2$ (of course, $|x_1 - x_2| = |y_1 - y_2|$). The first approach is...
[ "brute force", "constructive algorithms", "flows", "geometry", "greedy", "implementation", "math", "ternary search" ]
2,400
#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<li, li> pt; const li INF64 = li(1e18); pt p[4]; inline bool read() { fore (i, 0, 4) { if(!(cin >> p[i].x >> ...
1455
F
String and Operations
You are given a string $s$ consisting of $n$ characters. These characters are among the first $k$ lowercase letters of the Latin alphabet. You have to perform $n$ operations with the string. During the $i$-th operation, you take the character that \textbf{initially occupied} the $i$-th position, and perform \textbf{on...
The crucial observation that we have to make is that the character that initially occupied the position $i$ cannot occupy the positions to the left of $i - 2$: we can shift some character two positions to the left using a combination of operations RL, but we can't go any further. So, the prefix of the first $i$ charact...
[ "dp", "greedy" ]
2,800
#include <bits/stdc++.h> using namespace std; const int N = 505; int n, k; string s; string dp[N]; void solve() { cin >> n >> k >> s; for (int i = 1; i <= n; i++) dp[i] = char('z' + 1); for (int i = 0; i < n; i++) { int c = s[i] - 'a'; int nc = min({c, (c + 1) % k, (c + k - 1) % k}); dp[i + 1] = min(dp[i...
1455
G
Forbidden Value
Polycarp is editing a complicated computer program. First, variable $x$ is declared and assigned to $0$. Then there are instructions of two types: - set $y$ $v$ — assign $x$ a value $y$ or spend $v$ burles to remove that instruction (thus, not reassign $x$); - if $y$ $\dots$ end block — execute instructions inside the...
Consider the following dynamic programming. $dp_{ij}$ - the minimum cost to make $x$ have value $j$ after the $i$-th line. The transitions here are pretty easy: on set you just consider two options of skipping or not skipping the instructions and on if you either go to the next line or to the end of the block depending...
[ "data structures", "dp" ]
2,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define x first #define y second using namespace std; const long long INF = 1e18; struct op{ string tp; int y, v, to; }; struct addmap{ long long add; map<int, long long> val; multiset<long long> mn; }; void reset(addmap &a, int x, ...
1456
E
XOR-ranges
Given integers $c_{0}, c_{1}, \ldots, c_{k-1}$ we can define the cost of a number $0 \le x < 2^{k}$ as $p(x) = \sum_{i=0}^{k-1} \left( \left\lfloor \frac{x}{2^{i}} \right\rfloor \bmod 2 \right) \cdot c_{i}$. In other words, the cost of number $x$ is the sum of $c_{i}$ over the bits of $x$ which are equal to one. Let's...
First, we will make all segments exclusive for convenience. Assume we have segment $(l, r)$, we gonna analyze the process of forming $x$ from highest bit to lowest bit: Let $hb$ is the highest bit such that $hb$-th bit of $l$ and $r$ are different (Apparently, bits higher than $hb$ of x has to be same with bits of $l$ ...
[ "dp", "greedy" ]
3,500
null
1458
A
Row GCD
You are given two positive integer sequences $a_1, \ldots, a_n$ and $b_1, \ldots, b_m$. For each $j = 1, \ldots, m$ find the greatest common divisor of $a_1 + b_j, \ldots, a_n + b_j$.
From basic properties of GCD we know that $GCD(x, y) = GCD(x - y, y)$. The same applies for multiple arguments: $GCD(x, y, z, \ldots) = GCD(x - y, y, z, \ldots)$. Let's use this for $GCD(a_1 + b_j, \ldots, a_n + b_j)$ and subtract $a_1 + b_j$ from all other arguments: $GCD(a_1 + b_j, \ldots, a_n + b_j) = GCD(a_1 + b_j,...
[ "math", "number theory" ]
1,600
null
1458
B
Glass Half Spilled
There are $n$ glasses on the table numbered $1, \ldots, n$. The glass $i$ can hold up to $a_i$ units of water, and currently contains $b_i$ units of water. You would like to choose $k$ glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as yo...
Suppose that we want to collect water in a certain set of chosen glasses $S$. Let $A_S$ be the total capacity of chosen glasses, and $B_S$ be the total amount of water currently contained in chosen glasses. Also, let $B$ be the total amount of water in all glasses. Clearly, the optimal way is to directly transfer water...
[ "dp" ]
2,000
null
1458
C
Latin Square
You are given a square matrix of size $n$. Every row and every column of this matrix is a permutation of $1$, $2$, $\ldots$, $n$. Let $a_{i, j}$ be the element at the intersection of $i$-th row and $j$-th column for every $1 \leq i, j \leq n$. Rows are numbered $1, \ldots, n$ top to bottom, and columns are numbered $1,...
For convenience, let's assume that all row and column indices, as well as matrix values, are from $0, \ldots, n - 1$ instead for $1, \ldots, n$. If only shift operations were present, we could solve the problem in linear time: just maintain where the top left corner ends up after all the shifts, and then the matrix can...
[ "math", "matrices" ]
2,700
null
1458
D
Flip and Reverse
You are given a string $s$ of 0's and 1's. You are allowed to perform the following operation: - choose a non-empty contiguous substring of $s$ that contains an equal number of 0's and 1's; - flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; - reverse the substring. For example,...
Let's go over characters of $s$ left to right and keep track of the balance = (the number of $0$'s) - (the number of $1$'s) among the visited characters. We can think about starting at the point $0$, and moving right (from $x$ to $x + 1$) when we see a $0$, and moving left (to $x - 1$) when we see a $1$. Each time we g...
[ "data structures", "graphs", "greedy" ]
3,100
null
1458
E
Nim Shortcuts
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap! In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player...
Given the shortcut positions, we can immediately mark some initial positions as winning or losing for the first player. Namely, all shortcut positions are immedilately losing, and any position within one move of a shortcut position is winning (unless it's also a shortcut position). In an example picture below cells $(x...
[ "data structures", "games" ]
3,100
null
1458
F
Range Diameter Sum
You are given a tree with $n$ vertices numbered $1, \ldots, n$. A tree is a connected simple graph without cycles. Let $\mathrm{dist}(u, v)$ be the number of edges in the unique simple path connecting vertices $u$ and $v$. Let $\mathrm{diam}(l, r) = \max \mathrm{dist}(u, v)$ over all pairs $u, v$ such that $l \leq u,...
Please bear with my formal style for this one as my hand-waving skills are too weak to explain this properly. We'll use the "divide-and-conquer" strategy. Let us implement a recursive procedure $solve(l, r)$ that will compute the sum $\sum_{l \leq i \leq j \leq r} diam(i, j)$. It will do so as follows: If $l = r$, then...
[ "data structures", "trees" ]
3,500
null
1459
A
Red-Blue Shuffle
There are $n$ cards numbered $1, \ldots, n$. The card $i$ has a red digit $r_i$ and a blue digit $b_i$ written on it. We arrange all $n$ cards in random order from left to right, with all permutations of $1, \ldots, n$ having the same probability. We then read all red digits on the cards from left to right, and obtain...
First we can observe that if a card has $r_i = b_i$, then if doesn't affect the comparison between $R$ and $B$ regardless of its position. We can forget about all such cards. Formally, if we erase all such cards after the permutation, then $R$ and $B$ are still compared in the same way, and further all the remaining ca...
[ "math", "probabilities" ]
800
null
1459
B
Move and Turn
A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly $1$ meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot \textbf{can choose any of the four directions}, but then at the end of every second it \textbf{has to ...
We will describe an $O(1)$ formula solution. Some slower solutions were also allowed. First, consider the case when $n$ is even. Regardless of the initial direction, we will make $n / 2$ horizontal (west-east) steps and $n / 2$ vertical (north-south) steps. Further, directions of horizontal and vertical steps may be de...
[ "dp", "math" ]
1,300
null
1461
A
String Generation
One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length $n$ to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules: - the string may only contain characters 'a', 'b', or 'c...
Let's note that the string like "abcabcabcabc..." has only palindromes of length 1, what means it is suitable for us in all cases.
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> #define fi first #define se second #define m_p make_pair #define endl '\n' #define fast_io ios_base::sync_with_stdio(0); cin.tie(0) using namespace std; typedef long long ll; const int MAXN = 1123456; const int MAXINT = 2147483098; const ll MAXLL = 9223372036854775258LL; void next(cha...
1461
B
Find the Spruce
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an $n \times m$ matrix consisting of "*" and ".". To find every spruce first let's define what a spruce in the matrix is. A set of...
Let's iterate over the top of the spruce. When we meet the symbol "*", we will start iterating over the height of the current spruce. If for the current height $k$ for each $1 \le i \le k$ all cells with the row number $x+i-1$ and columns in range $[y - i + 1, y + i - 1]$ are "*", then we increase the value of the answ...
[ "brute force", "dp", "implementation" ]
1,400
def solve(): n, m = map(int, input().split()) a = [] for i in range(n): a.append(input()) dp = [] for i in range(n): dp.append([]) for j in range(m): dp[i].append((1 if a[i][j] == '*' else 0) if j == 0 else dp[i][j - 1] + (1 if a[i][j] == '*' else 0)) answer = 0 for x in range(n): for y in range(m...
1461
C
Random Events
Ron is a happy owner of a permutation $a$ of length $n$. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutati...
Let's first define some variable $R$, which will be equal to the last unsorted number (the largest $i$ for which $r_i != i$). Now we can see that we are not interested in experiments with $r_i < R$. To get the answer, we just need to multiply the remaining $(1-p_i)$. This number will indicate the probability that all t...
[ "dp", "math", "probabilities" ]
1,500
def solve(n, m): a = list(map(int, input().split())) lastCorrectPos = n - 1; while lastCorrectPos >= 0 and a[lastCorrectPos] == lastCorrectPos + 1: lastCorrectPos -= 1 ans = 1.0 if lastCorrectPos == -1: ans = 0.0 for _ in range(m): data = input().split() ...
1461
D
Divide and Summarize
Mike received an array $a$ of length $n$ as a birthday present and decided to test how pretty it is. An array would pass the $i$-th prettiness test if there is a way to get an array with a sum of elements totaling $s_i$, using some number (possibly zero) of slicing operations. An array slicing operation is conducted ...
To begin with, you can notice that the cut operation does not depend on the order of the $a$ array. So we can sort it. Now let's build a tree of transitions from the original array to all its possible states. You can simply prove that the height of this tree does not exceed $log(max)$. Since $max(current_a)-min(current...
[ "binary search", "brute force", "data structures", "divide and conquer", "implementation", "sortings" ]
1,600
q = set() a = [] def go(l, r): global a, q sum = 0 for i in range(l, r + 1): sum += a[i] q.add(sum) mid = (a[l] + a[r]) // 2 pos = -1 for i in range(l, r + 1): if a[i] <= mid: pos = i else: break if pos == -1 or pos == r: return go(l, pos) go(pos + 1, r) def solve(): global a, q...
1461
E
Water Level
In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. Origina...
If $y \le x$, it is quite easy to calculate the answer. Note that at each iteration of the algorithm (except, perhaps, the first), the water level will decrease by x-y liters, and we will have to calculate whether it can decrease t times. Otherwise, lets note, when we use the rise in water level, we change the value of...
[ "brute force", "graphs", "greedy", "implementation", "math" ]
2,200
#include <bits/stdc++.h> #define fi first #define se second #define m_p make_pair #define endl '\n' #define fast_io ios_base::sync_with_stdio(0); cin.tie(0) using namespace std; typedef long long ll; const int MAXN = 1123456; const int MAXINT = 2147483098; const ll MAXLL = 8000000000000000000LL; const long doub...
1461
F
Mathematical Expression
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw $n$ numbers $a_1, a_2, \ldots, a_n$ without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the...
First, let's solve the problem without the multiplication sign. It is always beneficial for us to put a plus or a minus, if there is no plus sign. Now we will solve the problem when there is a sign to multiply. The case when the plus sign is missing is very easy to solve. We put the sign to multiply to the first zero, ...
[ "constructive algorithms", "dp", "greedy" ]
2,700
#include <bits/stdc++.h> #pragma GCC optimize("unroll-loops") #pragma GCC optimize("-O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("fast-math") #pragma GCC optimize("no-stack-protector") #define fi first #define se second #define p_b push_back #define pll pair<ll,ll> #define pii pair<int,int> #define m_p ...
1462
A
Favorite Sequence
Polycarp has a favorite sequence $a[1 \dots n]$ consisting of $n$ integers. He wrote it out on the whiteboard as follows: - he wrote the number $a_1$ to the left side (at the beginning of the whiteboard); - he wrote the number $a_2$ to the right side (at the end of the whiteboard); - then as far to the left as possibl...
In this problem, you can implement an algorithm opposite to that given in the condition. Let's maintain two pointers to the left-most and right-most unhandled element. Then, restoring the original array, you: put the left-most unhandled item in the first position put the right-most unhandled item in the second position...
[ "implementation", "two pointers" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> v(n); for (int &e : v) { cin >> e; } int left = 0, right = n - 1; vector<int> ans(n); for (int i = 0; i < n; i++) { if (i % 2 == 0) { ans[i] = v[left++]; } else { ans[i] = v[right--]; ...
1462
B
Last Year's Substring
Polycarp has a string $s[1 \dots n]$ of length $n$ consisting of decimal digits. Polycarp performs the following operation with the string $s$ \textbf{no more than once} (i.e. he can perform operation $0$ or $1$ time): - Polycarp selects two numbers $i$ and $j$ ($1 \leq i \leq j \leq n$) and removes characters from th...
Let's see how the deleted substring $t$ should look so that after deleting it, the string $s$ turns into the string "2020". The length of the string $t$ must be $n - 4$. Then we can iterate over all substrings of the string $s$ of length $n - 4$ (there are no more than five such substrings) and look at the string obtai...
[ "dp", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; for (int i = 0; i <= 4; i++) { if (s.substr(0, i) + s.substr(n - 4 + i, 4 - i) == "2020") { cout << "YES" << endl; return; } } cout << "NO" << endl; } int main() { int tests; cin >...
1462
C
Unique Number
You are given a positive number $x$. Find the smallest positive integer number that has the sum of digits equal to $x$ and all digits are \textbf{distinct} (unique).
First of all, let's understand that the answer to the problem should not contain zeros (leading zeros are useless, while others increase the number, but do not change the sum). It is also clear that the number we found should have the minimum possible length (since the longer the numbers without leading zeros, the larg...
[ "brute force", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; void solve() { int x; cin >> x; vector<int> ans; int sum = 0, last = 9; while (sum < x && last > 0) { ans.push_back(min(x - sum, last)); sum += last; last--; } if (sum < x) { cout << -1 << "\n"; } else { reverse(ans.begin(), ans.end());...
1462
D
Add to Neighbour and Remove
Polycarp was given an array of $a[1 \dots n]$ of $n$ integers. He can perform the following operation with the array $a$ no more than $n$ times: - Polycarp selects the index $i$ and adds the value $a_i$ to \textbf{one of his choice} of its neighbors. More formally, Polycarp adds the value of $a_i$ to $a_{i-1}$ or to $...
Let $k$ - be the number of operations performed by Polycarp. Let's see how to check if $k$ is the answer. Let's denote by $s$ the sum of numbers in the array $a$. Note that after each operation $s$ does not change. Since we know that after $k$ operations all elements must be the same and the sum of the numbers in the a...
[ "greedy", "math", "number theory" ]
1,400
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; vector<ll> a(n); ll sum = 0; for (ll &x : a) { cin >> x; sum += x; } for (int i = n; i >= 1; i--) { if (sum % i == 0) { ll needSum = sum / i; ll curSum = 0; bool ok = true; ...
1462
E1
Close Tuples (easy version)
\textbf{This is the easy version of this problem. The only difference between easy and hard versions is the constraints on $k$ and $m$ (in this version $k=2$ and $m=3$). Also, in this version of the problem, you DON'T NEED to output the answer by modulo.} You are given a sequence $a$ of length $n$ consisting of intege...
In the easy version of the problem, you can count how many times each number occurs (the numbers themselves do not exceed $n$). Note that we do not have very many options for which triples of numbers can be included in the answer. Let's iterate over $x$ - the minimum number in the triples. Then there are the following ...
[ "binary search", "combinatorics", "math", "sortings", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; vector<ll> cnt(n + 1); for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x]++; } ll ans = 0; for (int i = 2; i < n; i++) { ans += cnt[i - 1] * cnt[i] * cnt[i + 1]; } for (int i = 1; i...
1462
E2
Close Tuples (hard version)
\textbf{This is the hard version of this problem. The only difference between the easy and hard versions is the constraints on $k$ and $m$. In this version of the problem, you need to output the answer by modulo $10^9+7$.} You are given a sequence $a$ of length $n$ consisting of integers from $1$ to $n$. \textbf{The s...
The key idea that allows us to move from the previous version to this one is that the values of the numbers themselves are not important to us. The main idea is to consider all numbers in the interval $[x, x + k]$. Let's also, as in the previous version, iterate over the minimum element $x$ in the tuple. Now let's find...
[ "binary search", "combinatorics", "implementation", "math", "sortings", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 300500; const int mod = 1000000007; ll fact[N]; ll invFact[N]; ll fast_pow(ll a, ll p) { ll res = 1; while (p) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (r...
1462
F
The Treasure of The Segments
Polycarp found $n$ segments on the street. A segment with the index $i$ is described by two integers $l_i$ and $r_i$ — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of $k$ segm...
As we know from the problem statement: Polycarp believes that a set of $k$ segments is good if there is a segment $[l_i, r_i]$ ($1 \leq i \leq k$) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). Let's iterate over this segment (which intersects all the oth...
[ "binary search", "data structures", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { vector<int> L; vector<int> R; int n; cin >> n; vector<pair<int, int>> v(n); for (auto &[l, r] : v) { cin >> l >> r; L.push_back(l); R.push_back(r); } sort(L.begin(), L.end()); ...
1463
A
Dungeon
You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has $a$ health points, the second has $b$ health points, and the third has $c$. To kill the monsters, you can use a cannon that, when fired, deals $1$ damage to the s...
Note that for every $7$ shots, we deal a total of $9$ units of damage. Since we want to kill all the monsters with a shot which index is divisible by $7$, let's denote the number of shots as $7k$. In this case, a total of $a+b+c$ units of damage must be dealt, hence $k=\frac{a+b+c}{9}$ (if the result of the division is...
[ "binary search", "math" ]
1,100
for i in range(int(input())): a, b, c = map(int, input().split()) if (a + b + c) % 9 != 0: print("NO") else: print("YES" if min(a, b, c) >= (a + b + c) // 9 else "NO")
1463
B
Find The Array
You are given an array $[a_1, a_2, \dots, a_n]$ such that $1 \le a_i \le 10^9$. Let $S$ be the sum of all elements of the array $a$. Let's call an array $b$ of $n$ integers \textbf{beautiful} if: - $1 \le b_i \le 10^9$ for each $i$ from $1$ to $n$; - for every pair of adjacent integers from the array $(b_i, b_{i + 1}...
It is enough to consider two possible arrays $b$: ($a_1, 1, a_3, 1, a_5, \dots$) and ($1, a_2, 1, a_4, 1, \dots$). It is not difficult to notice that in these arrays, the condition is met that among two neighboring elements, one divides the other. It remains to show that at least one of these two arrays satisfies the c...
[ "bitmasks", "constructive algorithms", "greedy" ]
1,400
for t in range(int(input())): n = int(input()) a = list(map(int, input().split())) s = sum(a) cur = [0, 0] for i in range(n): cur[i % 2] += a[i] - 1 for j in range(2): if 2 * cur[j] > s: continue for i in range(n): if i % 2 == j: a[i] = 1 break print(*a)
1463
C
Busy Robot
You have a robot that can move along a number line. At time moment $0$ it stands at point $0$. You give $n$ commands to the robot: at time $t_i$ seconds you command the robot to go to point $x_i$. Whenever the robot receives a command, it starts moving towards the point $x_i$ with the speed of $1$ unit per second, and...
The main idea in the problem is not how to solve it but how to code it neatly. I've come up with the following way. Let's store three variables: where is the robot now, what direction does it move ($-1$, $0$ or $1$) and how much time is left until it stops moving. The processing of the commands looks becomes pretty eas...
[ "implementation" ]
1,800
def inside(l, r, x): return min(l, r) <= x <= max(l, r) def sg(x): return -1 if x < 0 else int(x > 0) for _ in range(int(input())): n = int(input()) qs = [] for i in range(n): qs.append(list(map(int, input().split()))) qs.append([4*10**9, 0]) ans = 0 pos, dr, lft = 0, 0, 0 for i in range(n): t, x = qs[i]...
1463
D
Pairs
You have $2n$ integers $1, 2, \dots, 2n$. You have to redistribute these $2n$ elements into $n$ pairs. After that, you choose $x$ pairs and take minimum elements from them, and from the other $n - x$ pairs, you take maximum elements. Your goal is to obtain the set of numbers $\{b_1, b_2, \dots, b_n\}$ as the result of...
Let's prove that in the set $b$ $x$ minimum elements will be from $x$ pairs where we'll take minimums and analogically $n - x$ maximums will be from $n - x$ pairs where we'll take maximums. By contradiction, let's look at two pairs $(a, b)$ ($a < b$) and $(c, d)$ ($c < d$), where we will take maximum from $(a, b)$ and ...
[ "binary search", "constructive algorithms", "greedy", "two pointers" ]
1,900
#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; vector<int> b; inline bool read() { if(!(cin >> n)) return false; b.resize(n); fore (i, 0, n) cin >> b[i]; return true; } int getMax(const ...
1463
E
Plan of Lectures
Ivan is a programming teacher. During the academic year, he plans to give $n$ lectures on $n$ different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the $1$-st, $2$-nd, ..., $n$-th lecture — formally, he wants to choose some permutation of integers fr...
The prerequisites for each lecture form a rooted tree, so let's forget about the legend and learn how to find such an order of vertices of a tree that all conditions work. Let's introduce some algorithm that produces an ordering of vertices for every possible case. If any valid ordering exists, it should produce a vali...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "implementation", "sortings", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) vector<vector<int>> g, h, ng; vector<int> rk, p; int getp(int a){ return a == p[a] ? a : p[a] = getp(p[a]); } void unite(int a, int b){ a = getp(a), b = getp(b); if (a == b) return; if (rk[a] < rk[b]) swap(a, b);...
1463
F
Max Correct Set
Let's call the set of positive integers $S$ \textbf{correct} if the following two conditions are met: - $S \subseteq \{1, 2, \dots, n\}$; - if $a \in S$ and $b \in S$, then $|a-b| \neq x$ and $|a-b| \neq y$. For the given values $n$, $x$, and $y$, you have to find the maximum size of the \textbf{correct} set.
The key idea of the task is to prove that there is an optimal answer where the chosen elements in $S$ has a period equal to $p = x + y$. Let's work with $0, 1, \dots, n - 1$ instead of $1, 2, \dots, n$. Firstly, let's prove that if we've chosen correct set $a_1, \dots, a_k$ in interval $[l, l + p)$ then if we take all ...
[ "bitmasks", "dp", "math" ]
3,100
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int N = 22; int dp[2][1 << N]; int val[2 * N]; int main() { int n, x, y; scanf("%d%d%d", &n, &x, &y); int k = x + y; int m = max(x, y); int FULL = (1 << m) - 1; for (int i = 0; i < k; ++i) val[i] = n / k + (i < n % k); for (int ma...
1464
F
My Beautiful Madness
You are given a tree. We will consider simple paths on it. Let's denote path between vertices $a$ and $b$ as $(a, b)$. Let $d$-neighborhood of a path be a set of vertices of the tree located at a distance $\leq d$ from at least one vertex of the path (for example, $0$-neighborhood of a path is a path itself). Let $P$ b...
When I write "a vertex at a distance $d$ up from the given", I mean such a vertex, if it exists; otherwise the root of the tree. Let's learn how to answer the query of whether the intersection of $d$-neighborhoods of all paths is empty. For a given path poman is a vertex at a distance $d$ up from the LCA of this path. ...
[ "data structures", "trees" ]
3,500
#pragma GCC optimize("O3") #include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; const int LG = 20; const int inf = 1e9 + 228; struct Fenwick { int n; vector<int> t; Fenwick(int n) : n(n), t(n) {} void upd(int v, int x) { for (int i = v; i < n; i |= i + 1) { t[i...
1466
A
Bovine Dilemma
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io. There are $n$ trees growing along the river, where Argus tends Io. For this problem, the river ...
The solution is to iterate over all possible triangles, find their areas, and compute how many of these areas are distinct. So the problem is to calculate the area of a given triangle efficiently. There are many possible ways to do it; I will describe the most straightforward method. Recall the formula for the triangle...
[ "brute force", "geometry", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); vector <int> in(n); for(auto &p: in) scanf("%d", &p); set <int> S; for(int i = 0; i < n; ++i) for(int j = i + 1; j < n; ++j) S.insert(in[j] - in[i]); printf("%d\n", (int)S.size()); } int main() { int cases; scanf...
1466
B
Last minute enhancements
Athenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception. His song consists of $n$ notes, which we will treat as \textbf{positive integers}. The \textbf{diversi...
We describe two solutions. The first focuses on maximal contiguous intervals of values. We notice that for each such interval $[l, r]$ it can either remain unchanged or get increased to $[l, r + 1]$ (other possibilities won't increase the number of different elements; thus, we don't need to consider them). From this ob...
[ "dp", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); set <int> S; for(int i = 1; i <= n; ++i) { int v; scanf("%d", &v); if(S.count(v)) v++; S.insert(v); } printf("%d\n", (int)S.size()); } int main() { int cases; scanf("%d", &cases); while(cases--) solve(); ...
1466
C
Canine poetry
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poet...
The main observation is that if there exists a palindrome of length larger than $3$, then there exists a palindrome of length $2$ or $3$. This observation allows us to simplify the task to erasing all palindromes of length $2$ or $3$. We can also notice that each character will be replaced at most once. From now on, th...
[ "dp", "greedy", "strings" ]
1,300
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7; int n; char in[N]; int dp[N][2][2]; void solve(){ scanf("%s", in + 1); n = strlen(in + 1); for(int ta = 0; ta < 2; ++ta) for(int tb = 0; tb < 2; ++tb) dp[0][ta][tb] = 0; for(int i = 1; i <= n; ++i) for(int ta = 0; ta < 2; ++ta) for...
1466
D
13th Labour of Heracles
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve th...
Description of the algorithm For simplicity, I will describe the partition of edges into colors in terms of modifying the graph. After the modifications, each connected component will correspond to edges in the given color (different color for every component). I will add colors to the coloring one by one. Initially, w...
[ "data structures", "greedy", "sortings", "trees" ]
1,500
#include <bits/stdc++.h> using namespace std; typedef long long int LL; const int N = 100 * 1000 + 7; int n; int w[N]; int deg[N]; void solve() { scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d", &w[i]); deg[i] = 0; } for(int i = 1; i < n; ++i) { int u, v; scanf("%d %d", &u, &v); deg[u]++;...
1466
E
Apollo versus Pan
Only a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following: Let $x_1, x_2, \ldots, x_n$ be the sequence of $n$ non-negative integers. Find th...
The formula given in this task looks difficult to calculate, so we can rewrite it: $\sum_{i=1}^n \sum_{j=1}^n \sum_{k=1}^n (x_i \, \& \, x_j) \cdot (x_j \, | \, x_k) = \sum_{j=1}^n \sum_{i=1}^n (x_i \, \& \, x_j) \sum_{k=1}^n (x_j \, | \, x_k) = \sum_{j=1}^n \left[ \sum_{i=1}^n (x_i \, \& \, x_j) \right] \cdot \left[ \...
[ "bitmasks", "brute force", "math" ]
1,800
#include <bits/stdc++.h> using namespace std; typedef long long int LL; const int N = 500 * 1000 + 7; const int P = 60; const int MX = 1e9 + 7; int n; LL in[N]; int cnt[P]; void solve(){ scanf("%d", &n); for(int i = 0; i < P; ++i) cnt[i] = 0; for(int i = 1; i <= n; ++i){ scanf("%lld", &in[i]); for(int j...
1466
F
Euclid's nightmare
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set $S$ of $n$ $m$-dimensional vectors over the $\mathbb{Z}_2$ field and can perform vector addition on them. ...
We start by simplifying the task. Increase the length of all vectors by $1$, i.e., add additional dimension. For the vectors from $S$, the $m+1$-th character will be $1$ in those with exactly one character $1$. This way, all the vectors in $S$ will have $1$s on precisely two positions. When we have some items and some ...
[ "bitmasks", "dfs and similar", "dsu", "graphs", "greedy", "math", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long int LL; const int N = 5e5 + 7; const int MX = 1e9 + 7; int n, m; int rep[N]; int Find(int a) { if(rep[a] == a) return a; return rep[a] = Find(rep[a]); } bool Union(int a, int b) { a = Find(a); b = Find(b); rep[a] = b; return a != b; } int ...
1466
G
Song of the Sirens
\begin{quote} Whoso in ignorance draws near to them and hears the Sirens' voice, he nevermore returns.Homer, Odyssey \end{quote} In the times of Jason and the Argonauts, it was well known that sirens use the sound of their songs to lure sailors into their demise. Yet only a few knew that every time sirens call a sailo...
We define $f(n, w)$ as the number of occurrences of $w$ in $s_n$. Moreover, we define $g(n, w), n > 0$ as the number of occurrences of $w$ in $s_n$ which contain character $t_{n - 1}$. With these definitions, we write the formula for $f(n, w)$ with $n > 0$: $f(n, w) = 2 \cdot f(n - 1, w) + g(n, w) = f(0, w) \cdot 2^n +...
[ "combinatorics", "divide and conquer", "hashing", "math", "string suffix structures", "strings" ]
2,600
#include <bits/stdc++.h> using namespace std; const int MAXLEN = 1e6 + 7; const int MOD = 1e9 + 7; int n, q; string s, t; vector <string> songs; vector <int> pw; vector <int> sum[26]; void read(string &p) { static char input[MAXLEN]; scanf("%s", input); p = input; } void prepare_songs() { songs = {s}; for(au...
1466
H
Finding satisfactory solutions
Getting so far in this contest is not an easy feat. By solving all the previous problems, you have impressed the gods greatly. Thus, they decided to spare you the story for this problem and grant a formal statement instead. Consider $n$ agents. Each one of them initially has exactly one item, \textbf{$i$-th agent has ...
We start with presenting the algorithm for finding the unique optimal good assignment. It treats agents as vertices in a graph and works in the following way: For every $i$ from $1$ to $n$ create a vertex (a single vertex will represent both the agent and his good) Until there are agents left, perform a round of an alg...
[ "combinatorics", "dp", "graphs", "greedy", "math" ]
3,300
#include <bits/stdc++.h> using namespace std; typedef long long int LL; #define st first #define nd second #define PII pair <int, int> const int N = 60; const int MX = 1e9 + 7; struct state { int sum_picked = 0; int last_picked = 0, cur_picked = 0; int iterator = 0; vector <PII> lengths; state(vector <PII> ...
1466
I
The Riddle of the Sphinx
\begin{quote} What walks on four feet in the morning, two in the afternoon, and three at night? \end{quote} This is an interactive problem. This problem doesn't support hacks. Sphinx's duty is to guard the city of Thebes by making sure that no unworthy traveler crosses its gates. Only the ones who answer her riddle t...
First, we start with a slightly suboptimal solution using $5 \cdot (n + b)$ queries. We investigate the elements in order from $1$ to $n$. While doing so, we will keep the stack with some of these elements. Moreover, we will keep a prefix of the maximum we found till now. We keep the following conditions: The prefix of...
[ "binary search", "data structures", "interactive" ]
3,400
#include <bits/stdc++.h> using namespace std; #define st first #define nd second int n, b; void write(int i, string y){ printf("%d ", i); for(auto p: y) printf("%c", p); puts(""); fflush(stdout); } bool ask(int i, string y){ write(i, y); string ans; cin >> ans; return ans == "yes"; } void solve(vector <...
1467
A
Wizard of Orz
There are $n$ digital panels placed in a straight line. Each panel can show any digit from $0$ to $9$. Initially, all panels show $0$. Every second, the digit shown by each panel increases by $1$. In other words, at the end of every second, a panel that showed $9$ would now show $0$, a panel that showed $0$ would now ...
If there is only one panel, then pause it when digit $9$ appears on it. You cannot do any better than that. Otherwise, it is always optimal to pause the second panel from left, when the digit $8$ appears on it. This would give an answer of the form $98901234567890123456\dots$. You can verify that this is the largest nu...
[ "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; #define int long long int solveTestCase() { int n; cin >> n; string s = "989"; if (n <= 3) return cout << s.substr(0, n) << "\n", 0; cout << s; for (int i = 3; i < n; i++) cout << (i - 3) % 10; cout << "\n"; } signed main() { ...
1467
B
Hills And Valleys
You are given a sequence of $n$ integers $a_1$, $a_2$, ..., $a_n$. Let us call an index $j$ ($2 \le j \le {{n-1}}$) a hill if $a_j > a_{{j+1}}$ and $a_j > a_{{j-1}}$; and let us call it a valley if $a_j < a_{{j+1}}$ and $a_j < a_{{j-1}}$. Let us define the intimidation value of a sequence as the sum of the number of h...
Changing the value of $a_i$ affects the hill/valley status of only elements $\{a_{i-1}, a_i, a_{i+1}\}$. We claim that it is optimal to change $a_i$ to either $a_{i-1}$ or $a_{i+1}$ for valid $i\space(1<i<n)$. Let $x$ be a value of $a_i$ such that the number of hills/valleys among elements $\{a_{i-1},a_i,a_{i+1}\}$ is ...
[ "brute force", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 3e5; int a[N], n; int isValley(int i) { return (i > 0 && i < n - 1 && a[i] < a[i - 1] && a[i] < a[i + 1]); } int isHill(int i) { return (i > 0 && i < n - 1 && a[i] > a[i - 1] && a[i] > a[i + 1]); } int solveTestCase() { ci...
1467
C
Three Bags
You are given \textbf{three} bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number $a$ from the first bag and number $b$ from th...
Model the problem as a rooted tree (graph). There are $n_1+n_2+n_3$ nodes, corresponding to the elements from the three bags. Edges between two nodes represent an operation on the two elements and it can be seen that an edge can exist only between nodes of elements from different sets. A directed edge from $b$ to $a$ m...
[ "constructive algorithms", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 3e5; vector<vector<int>> a(3, vector<int>()); vector<int> n(3, 0); int calc() { int ans = 0, m1 = a[1][0], m2 = a[2][0], s1 = 0, s2 = 0; for (int i : a[0]) ans += i; for (int i = 1; i < n[1]; i++) s1 += a[1][i]; for (int...
1467
D
Sum of Paths
There are $n$ cells, numbered $1,2,\dots, n$ from left to right. You have to place a robot at any cell initially. The robot must make \textbf{exactly} $k$ moves. In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell $i$...
The main idea of the problem is to calculate the contribution of each cell to the answer. Let $cnt_i$ denote the sum of the number of times cell $i$ appears in all good paths of length $k$. Then the answer is equal to $a_1*cnt_1 + a_2*cnt_2 + \dots + a_n*cnt_n$. We shall use dynamic programming to calculate these value...
[ "combinatorics", "dp", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 5005, mod = 1e9 + 7; int dp[N][N], cnt[N], a[N], q, n, k; void pre() { for (int i = 0; i < n; i++) dp[i][0] = 1; for (int j = 1; j < N; j++) { dp[0][j] = dp[1][j - 1]; for (int i = 1; i < n - 1; ...
1467
E
Distinctive Roots in a Tree
You are given a tree with $n$ vertices. Each vertex $i$ has a value $a_i$ associated with it. Let us root the tree at some vertex $v$. The vertex $v$ is called a distinctive root if the following holds: in all paths that start at $v$ and end at some other node, all the values encountered are distinct. Two different pa...
Root the tree arbitrarily. Consider any node $v$. Let us remove $v$ from the tree and examine the trees that will be created in the resultant forest. Let's say that a particular tree was attached to $v$ through node $u$. Further, let's say that this tree has some node $x$ satisfying $a_v = a_x$. Then clearly, if any di...
[ "data structures", "dfs and similar", "dp", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 5e5; vector<int> adj[N]; int a[N], par[N], n; map<int, vector<int>> v, times; int euler[N * 2 - 1], tin[N], tout[N], c = 0; set<pair<int, int>> g; int dp[N], ans; void dfs(int v, int p = -1) { par[v] = p; tin[v] = c; euler...
1468
A
LaIS
Let's call a sequence $b_1, b_2, b_3 \dots, b_{k - 1}, b_k$ almost increasing if $$\min(b_1, b_2) \le \min(b_2, b_3) \le \dots \le \min(b_{k - 1}, b_k).$$ In particular, any sequence with no more than two elements is almost increasing. You are given a sequence of integers $a_1, a_2, \dots, a_n$. Calculate the length o...
Let's add $0$ to the beginning of $a$, then we'll increase LaIS by one and so it will always start from $0$. Let's look at any almost increasing subsequence (aIS) and underline elements, which are minimums in at least one consecutive pair, for example, $[\underline{0}, \underline{1}, \underline{2}, 7, \underline{2}, \u...
[ "data structures", "dp", "greedy" ]
2,200
null
1468
B
Bakery
Monocarp would like to open a bakery in his local area. But, at first, he should figure out whether he can compete with other shops. Monocarp plans that the bakery will work for $n$ days. On the $i$-th day, $a_i$ loaves of bread will be baked in the morning before the opening. At the end of the $n$-th day, Monocarp wi...
Let's look at all $n$ days with some fixed $k$. Obviously, the seller works like a stack, so let's divide all days into segments in such a way, that the stack is emptied between consecutive segments. We can note that after we've got these segments - the answer is the maximum length among all segments. Why? Because the ...
[ "data structures", "dsu" ]
2,900
null
1468
C
Berpizza
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently. At the start of the working day, there are no customers at the Berpizza. They come there one by one. W...
The hardest part of this problem is to efficiently implement the third query, i. e. finding the customer with the greatest value of $m$ and erasing it. Simply iterating on all of them is too slow, since there may be up to $2.5 \cdot 10^5$ such queries and up to $5 \cdot 10^5$ customers at the pizzeria. There are severa...
[ "data structures", "implementation" ]
1,400
null
1468
D
Firecrackers
Consider a long corridor which can be divided into $n$ square cells of size $1 \times 1$. These cells are numbered from $1$ to $n$ from left to right. There are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the $a$-th cell, the guard is in the $b$-th cell ($a \ne b$). \be...
The first crucial observation that we need is the following one: it is optimal to light and drop some firecrackers, and only then start running away from the guard (that's because running away doesn't actually do anything if none of the firecrackers are lit). The hooligan shouldn't drop more than $|a - b| - 1$ firecrac...
[ "binary search", "sortings" ]
1,700
null
1468
E
Four Segments
Monocarp wants to draw four line segments on a sheet of paper. He wants the $i$-th segment to have its length equal to $a_i$ ($1 \le i \le 4$). These segments can intersect with each other, and each segment should be either horizontal or vertical. Monocarp wants to draw the segments in such a way that they enclose a r...
Suppose the values of $a_1$, $a_2$, $a_3$, $a_4$ are sorted in non-descending order. Then the shorter side of the rectangle cannot be longer than $a_1$, because one of the sides must be formed by a segment of length $a_1$. Similarly, the longer side of the rectangle cannot be longer than $a_3$, because there should be ...
[ "greedy" ]
800
null
1468
F
Full Turn
There are $n$ persons located on a plane. The $i$-th person is located at the point $(x_i, y_i)$ and initially looks at the point $(u_i, v_i)$. At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full $360$-degree turn. I...
Lets define for person with index $i$ their initial vision vector as vector ($u_i - x_i$, $v_i - y_i$). It is possible to prove that two persons will make eye contact during 360 rotation if and only if their initial vision vectors are collinear and oppositely directed. Note that the position of the persons does not mat...
[ "geometry", "hashing", "number theory" ]
1,700
null
1468
G
Hobbits
The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains. The mountain relief can be represented as a polyline with $n$ points $(x_i, y_i)$, numbered from $1$ to $n$ ($x_i < x_{i + 1}$ for $1 \le i \le n - 1$). Hobbits start their journ...
Let's start with the general idea of the solution. To solve the problem, we need to iterate over all relief segments and understand, which part the segment is seen by the Eye. A segment point can be hidden from the Eye by several mountains, but it is enough to track only the highest mountain. Generally speaking, the re...
[ "binary search", "geometry" ]
2,500
null
1468
H
K and Medians
Let's denote the median of a sequence $s$ with odd length as the value in the middle of $s$ if we sort $s$ in non-decreasing order. For example, let $s = [1, 2, 5, 7, 2, 3, 12]$. After sorting, we get sequence $[1, 2, 2, \underline{3}, 5, 7, 12]$, and the median is equal to $3$. You have a sequence of $n$ integers $[1...
Since after each operation we erase exactly $k - 1$ element from $a$ then if $(n - m) \not\equiv 0 \pmod{(k - 1)}$ then the answer is NO. Otherwise, if there is such element $b_{pos}$ such that there are at least $\frac{k - 1}{2}$ erased elements lower than $b_i$ and at least $\frac{k - 1}{2}$ erased elements greater t...
[ "constructive algorithms", "greedy", "math" ]
2,200
null
1468
I
Plane Tiling
You are given five integers $n$, $dx_1$, $dy_1$, $dx_2$ and $dy_2$. You have to select $n$ distinct pairs of integers $(x_i, y_i)$ in such a way that, for every possible pair of integers $(x, y)$, there exists exactly one triple of integers $(a, b, i)$ meeting the following constraints: \begin{center} $ \begin{cases} ...
One of the solutions is to consider an infinite 2 dimensional plane and draw a grid with lines parallel to vectors ($dx_1$, $dy_1$) and ($dx_2$, $dy_2$). By doing so we will get a tiling of the plane with parallelepipeds, one of them will have corners at ($0$, $0$), ($dx_1$, $dy_1$), ($dx_1 + dx_2$, $dy_1 + dy_2$), ($d...
[ "geometry", "implementation", "math" ]
2,500
null
1468
J
Road Reform
There are $n$ cities and $m$ bidirectional roads in Berland. The $i$-th road connects the cities $x_i$ and $y_i$, and has the speed limit $s_i$. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform. First of all, maintaining all $m$ roads is...
We will consider two cases: the road network without roads having $s_i > k$ is either connected or not. Checking that may be done with the help of DFS, BFS, DSU, or any other graph algorithm/data structure that allows checking if some graph is connected. If the network without roads having $s_i > k$ is not connected, t...
[ "dsu", "graphs", "greedy" ]
1,800
null
1468
K
The Robot
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates $(0, 0)$. He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding di...
It is obvious that the cell that can be the answer must belong to the original path of the robot. Thus, there are at most $n$ candidate cells in the answer. In order to make sure that a candidate cell is indeed the answer; it is necessary to simulate the movement of the robot, taking into account this cell as an obstac...
[ "brute force", "implementation" ]
1,600
null
1468
L
Prime Divisors Selection
Suppose you have a sequence of $k$ integers $A = [a_1, a_2, \dots , a_k]$ where each $a_i \geq 2$. A sequence of \textbf{prime} integers $P = [p_1, p_2, \dots, p_k]$ is called suitable for the sequence $A$ if $a_1$ is divisible by $p_1$, $a_2$ is divisible by $p_2$ and so on. A sequence of \textbf{prime} integers $P$ ...
Let's find for each prime integer $p \leq 10^{9}$ amount of integers $p^{q}$ among the given integers. If there are no more than 1 such integers, this prime $p$ is not interesting for us: if we add one such integer to the answer, we may always select exactly one divisor $p$ in a suitable sequence so it will not be frie...
[ "binary search", "greedy", "math", "number theory" ]
2,700
null
1468
M
Similar Sets
You are given $n$ sets of integers. The $i$-th set contains $k_i$ integers. Two sets are called similar if they share at least two common elements, i. e. there exist two integers $x$ and $y$ such that $x \ne y$, and they both belong to each of the two sets. Your task is to find two similar sets among the given ones, ...
Let's define $D$ = $m^{1/2}$, where $m$ is the total amount of integers. Now let's call a set of integers 'large' if its size is at least $D$ and 'small' otherwise. Firstly let's check whether there is a large set that has two common integers with some other (small or large) set. Let's try to find a similar set for eac...
[ "data structures", "graphs", "implementation" ]
2,300
null
1469
A
Regular Bracket Sequence
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are given a sequence $s$ of $...
There are two solutions to this problem: casework and greedy. The greedy solution goes as follows: the number of opening brackets in an RBS should be exactly $\frac{|s|}{2}$, and if there is a closing bracket before an opening bracket, it's optimal to swap them, if possible. So, we should replace the first $\frac{|s|}{...
[ "constructive algorithms", "greedy" ]
1,000
t = int(input()) for i in range(t): s = input() n = len(s) a = [s[i] for i in range(n)] cnt = n // 2 - 1 for j in range(n): if a[j] == '?': if cnt > 0: cnt -= 1 a[j] = '(' else: a[j] = ')' bal = 0 minbal = 0 ...
1469
B
Red and Blue
Monocarp had a sequence $a$ consisting of $n + m$ integers $a_1, a_2, \dots, a_{n + m}$. He painted the elements into two colors, red and blue; $n$ elements were painted red, all other $m$ elements were painted blue. After painting the elements, he has written two sequences $r_1, r_2, \dots, r_n$ and $b_1, b_2, \dots,...
Denote $p_i$ as the sum of first $i$ elements of $r$, and $q_j$ as the sum of first $j$ elements of $b$. These values can be calculated in $O(n + m)$ with prefix sums. The first solution is to use dynamic programming. Let $dp_{i, j}$ be the maximum value of $f(a)$ if we placed the first $i$ elements of $r$ and the firs...
[ "dp", "greedy" ]
1,000
for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] m = int(input()) b = [int(x) for x in input().split()] dp = [[-10**9 for j in range(m + 1)] for i in range(n + 1)] dp[0][0] = 0 ans = 0 for i in range(n + 1): for j in range(m + 1): if i < n: dp[i + 1][j] = max(dp[i + ...
1469
C
Building a Fence
You want to build a fence that will consist of $n$ equal sections. All sections have a width equal to $1$ and height equal to $k$. You will place all sections in one line side by side. Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the $i$-th section ...
Let's set sections from left to right. Note that for the $i$-th section all valid heights $x$ (heights for which it's possible to choose heights for all sections $1 \dots i$ meeting all rules and finishing with the height of $i$ equal to $x$) form a segment. It's not hard to prove by induction. For the first section, t...
[ "dp", "greedy", "implementation", "two pointers" ]
1,600
fun main() { repeat(readLine()!!.toInt()) { val (n, k) = readLine()!!.split(' ').map { it.toInt() } val h = readLine()!!.split(' ').map { it.toInt() } var mn = h[0] var mx = h[0] var ok = true for (i in 1 until n) { mn = maxOf(mn - k + 1, h[i]) ...