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
1714
A
Everyone Loves to Sleep
Vlad, like everyone else, loves to sleep very much. Every day Vlad has to do $n$ things, each at a certain time. For each of these things, he has an alarm clock set, the $i$-th of them is triggered on $h_i$ hours $m_i$ minutes every day ($0 \le h_i < 24, 0 \le m_i < 60$). Vlad uses the $24$-hour time format, so after ...
To begin with, let's learn how to determine how much time must pass before the $i$ alarm to trigger. If the alarm time is later than the current one, then obviously $60*(h_i - H) + m_i - M$ minutes should pass. Otherwise, this value will be negative and then it should pass $24*60 + 60* (h_i - H) + m_i - M$ since a full...
[ "implementation", "math" ]
900
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e15; const int M ...
1714
B
Remove Prefix
Polycarp was presented with some sequence of integers $a$ of length $n$ ($1 \le a_i \le n$). A sequence can make Polycarp happy only if it consists of \textbf{different} numbers (i.e. distinct numbers). In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves. In one mov...
Let's turn the problem around: we'll look for the longest suffix that will make Polycarp happy, since it's the same thing. Let's create an array $cnt$, in which we will mark the numbers already encountered. Let's go along $a$ from right to left and check if $a_i$ does not occur to the right (in this case it is marked i...
[ "data structures", "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; bool yes = false; set<int> c; for (i...
1714
C
Minimum Varied Number
Find the minimum number with the given sum of digits $s$ such that \textbf{all} digits in it are distinct (i.e. all digits are unique). For example, if $s=20$, then the answer is $389$. This is the minimum number in which all digits are different and the sum of the digits is $20$ ($3+8+9=20$). For the given $s$ print...
Let's use the greedy solution: we will go through the digits in decreasing order. If the sum of $s$ we need to dial is greater than the current digit, we add the current digit to the end of the line with the answer. Note that in this way we will always get an answer consisting of the minimum possible number of digits, ...
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int s; cin >> s; string result; for (int d = 9; d >= 1; d--) if (s >= d) { result = char('0' + d) + res...
1714
D
Color with Occurrences
You are given some text $t$ and a set of $n$ strings $s_1, s_2, \dots, s_n$. In one step, you can choose any occurrence of any string $s_i$ in the text $t$ and color the corresponding characters of the text in red. For example, if $t=bababa$ and $s_1=ba$, $s_2=aba$, you can get $t=\textcolor{red}{ba}baba$, $t=b\textco...
The first step is to find the word that covers the maximum length prefix. If there is no such word, we cannot color the string. Then go through the positions inside the found prefix and find the next word, which is a tweak of $t$, has the maximal length, and ends not earlier than the previous found word, and not later ...
[ "brute force", "data structures", "dp", "greedy", "strings" ]
1,600
#include<bits/stdc++.h> #define len(s) (int)s.size() #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int ans = 0; bool ok = true; void Find(int a, int b, string &t, vector<string>&str, vector<pair<int, int>>&match){ int Max = 0, id = -1, pos = -1; for(int i = a; i <= b; i++){ ...
1714
E
Add Modulo 10
You are given an array of $n$ integers $a_1, a_2, \dots, a_n$ You can apply the following operation an arbitrary number of times: - select an index $i$ ($1 \le i \le n$) and replace the value of the element $a_i$ with the value $a_i + (a_i \bmod 10)$, where $a_i \bmod 10$ is the remainder of the integer dividing $a_i...
Let's see which remainders modulo $10$ change into which ones. If the array contains a number divisible by $10$, then it cannot be changed. If there is a number that has a remainder of $5$ modulo $10$, then it can only be replaced once. Thus, if the array contains a number divisible by $5$, then we apply this operation...
[ "brute force", "math", "number theory" ]
1,400
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <queue> using namespace std; int next(int x) { return x + x % 10; } void solve() { int n; cin >> n; vector<int> a(n); bool flag = false; for (int i = 0; i < n; ++i) { cin >> a[i]; if (a[i] % 5 =...
1714
F
Build a Tree and That Is It
A tree is a connected undirected graph without cycles. Note that in this problem, we are talking about not rooted trees. You are given four positive integers $n, d_{12}, d_{23}$ and $d_{31}$. Construct a tree such that: - it contains $n$ vertices numbered from $1$ to $n$, - the distance (length of the shortest path) ...
If the answer exists, you can hang the tree by some vertex such that the distances $d_{12}, d_{23}$ and $d_{31}$ can be expressed through the sums of distances to vertices $1,2$ and $3$. Then from the system of equations we express the required values of distances to vertices $1,2,3$ and construct a suitable tree. If t...
[ "constructive algorithms", "implementation", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> d(3); forn(i, 3) cin >> d[i]; int sum = d[0] + d[1] + d[2]; if (sum % 2 ==...
1714
G
Path Prefixes
You are given a rooted tree. It contains $n$ vertices, which are numbered from $1$ to $n$. The root is the vertex $1$. Each edge has two positive integer values. Thus, two positive integers $a_j$ and $b_j$ are given for each edge. Output $n-1$ numbers $r_2, r_3, \dots, r_n$, where $r_i$ is defined as follows. Consid...
Note that all $b_j$ are positive, which means that the amount on the prefix only increases. This allows us to use binary search to find the answer for the vertex. It remains only to learn how to quickly find the sum of $b_j$ on the path prefix. Let's run a depth-first search and store the prefix sums of the current pat...
[ "binary search", "data structures", "dfs and similar", "trees" ]
1,700
#pragma GCC optimize("O3","unroll-loops") #pragma GCC target("avx2") #include <bits/stdc++.h> using namespace std; #define int long long const int maxn=2e5+5; vector<int> ch[maxn]; int a[maxn]; int b[maxn]; int ans[maxn]; vector<int> vb; int curb=0; int cura=0; void dfs(int x){ curb+=b[x]; cura+=a[x]; vb...
1715
A
Crossmarket
Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $n$ rows and $m$ columns. Stanley and Megan can move to an adjacent cell using $1$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her ...
For convenience let's define going upward as decreasing $x$ coordinate, downward - increasing $x$, left - decreasing $y$, right - increasing y. One of the optimal solutions is the following: Megan goes upward to Stanley, she spends $(n - 1)$ units of energy for that. Then she goes right to her final destination by spen...
[ "constructive algorithms", "greedy", "math" ]
800
import kotlin.math.* fun main() { var t = readLine()!!.toInt() for (test in 0 until t) { val (n, m) = readLine()!!.split(" ").map { it -> it.toInt() } print("${n + m - 3 + min(n, m) + min(max(n, m) - 1, 1)}\n") } }
1715
B
Beautiful Array
Stanley defines the beauty of an array $a$ of length $n$, which contains \textbf{non-negative integers}, as follows: $$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$ which means that we divide each element by $k$, round it down, and sum up the resulting values. Stanley told Sam the integer $k$...
To start with, the sum of the numbers in the array $s$ cannot be less, than $k \cdot b$ (where $k$ is the number by which we divide, and $b$ is beauty ($s \ge k \cdot b$)) It is important, that $s \le k \cdot b + (k - 1) \cdot n$. Let's assume that is not true. Consider the sum of divisible parts of numbers in the arra...
[ "constructive algorithms", "greedy", "math" ]
1,000
t = int(input()) for i in range(t): n, x, s, q = map(int, input().split()) q0 = q a = [0 for i in range(n)] for i in range(n): a[i] = min(x - 1, q) q -= a[i] a[-1] += q q = q0 curr = sum(i // x for i in a) if (curr <= s <= q // x): j = 0 while curr != s: ...
1715
C
Monoblock
Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task. The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an ar...
Let us introduce another definition for the beauty - beauty of the array $a$ is a number of such positions (indexes) $i < n$, that $a_i \neq a_{i + 1}$, plus $1$. Let's call "joints" places where two adjacent different numbers exist in the array. Now consider the problem from the angle of these joints: if $f(joint)$ is...
[ "combinatorics", "data structures", "implementation", "math" ]
1,700
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <chrono> #include <deque> #include <iomanip> #include <queue> #include <functional> using namespace std; #define int long long int3...
1715
D
2+ doors
The Narrator has an integer array $a$ of length $n$, but he will only tell you the size $n$ and $q$ statements, each of them being three integers $i, j, x$, which means that $a_i \mid a_j = x$, where $|$ denotes the bitwise OR operation. Find the lexicographically smallest array $a$ that satisfies all the statements. ...
The first observation is that we can solve the task separately bit by bit, because of bitwise or operation is "bit-independent": bits of one particular power don't affect other bits to gen a lexicographically minimal solution, we can combine solutions for each bit separately This makes it possible for us to create a so...
[ "2-sat", "bitmasks", "graphs", "greedy" ]
1,900
#include <iostream> #include <vector> using namespace std; inline bool get_bit(uint32_t &x, uint32_t &bt) { return (x >> bt) & 1; } inline void make_one(uint32_t &x, uint32_t &bt) { x |= (1 << bt); } inline void make_null(uint32_t &x, uint32_t &bt) { x &= (~(1 << bt)); } inline bool solve_bit(vector<uint32_t> &an...
1715
E
Long Way Home
Stanley lives in a country that consists of $n$ cities (he lives in city $1$). There are bidirectional roads between some of the cities, and you know how long it takes to ride through each of them. Additionally, there is a flight between each pair of cities, the flight between cities $u$ and $v$ takes $(u - v)^2$ time....
Let's assume we know the shortest distances from the first vertex to each, if we have added no more than $k$ edges (air travels). Let's learn to recalculate the answer for $(k + 1)$ edges. First, let's update the answer for all the paths ending in an air travel. Then we can run Dijkstra to take into account all the pat...
[ "data structures", "divide and conquer", "dp", "geometry", "graphs", "greedy", "shortest paths" ]
2,400
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; #define int long long const int inf = 1e18; const int inf1 = 1e15; struct CHT { struct line { int k, b; line() {} line(int k, int b): k(k), b(b) {} double intersect(line ...
1715
F
Crop Squares
This is an interactive problem. Farmer Stanley grows corn on a rectangular field of size $ n \times m $ meters with corners in points $(0, 0)$, $(0, m)$, $(n, 0)$, $(n, m)$. This year the harvest was plentiful and corn covered the whole field. The night before harvest aliens arrived and poisoned the corn in a single ...
In fact, two queries are enough. The first query is to find out the area of intersection of the polygon with $2n + 2$ vertices at the points with coordinates $(0, m + 1),\:(0, 0),\:(1, m),\:(1, 0),\; \dots ,\;(n - 1, m),\:(n - 1, 0),\:(n, m),\:(n, m + 1)$ with a filled square. Such a polygon is periodic over $x$ axis w...
[ "constructive algorithms", "geometry", "interactive", "math" ]
2,700
#include <iostream> #include <vector> #include <iomanip> using namespace std; using ld = long double; template<typename T1, typename T2> ostream& operator<<(ostream& out, const pair<T1, T2>& x) { return out << x.first << ' ' << x.second; } ld query(const vector<pair<int, int>>& vert) { cout << "? " << ver...
1716
A
2-3 Moves
You are standing at the point $0$ on a coordinate line. Your goal is to reach the point $n$. In one minute, you can move by $2$ or by $3$ to the left or to the right (i. e., if your current coordinate is $x$, it can become $x-3$, $x-2$, $x+2$ or $x+3$). Note that the new coordinate can become negative. Your task is to...
If $n = 1$, the answer is $2$ (we can't get $1$, so we can move by $3$ to the right and by $2$ to the left). If $n = 2$ or $n = 3$, the answer is obviously $1$. Otherwise, the answer is always $\lceil\frac{n}{3}\rceil$. We can't get the answer less than this value (because we need at least $\lceil\frac{n}{3}\rceil$ mov...
[ "greedy", "math" ]
800
for _ in range(int(input())): n = int(input()) print(1 + (n == 1) if n <= 3 else (n + 2) // 3)
1716
B
Permutation Chain
A permutation of length $n$ is a sequence of integers from $1$ to $n$ such that each integer appears in it exactly once. Let the fixedness of a permutation $p$ be the number of fixed points in it — the number of positions $j$ such that $p_j = j$, where $p_j$ is the $j$-th element of the permutation $p$. You are asked...
Ideally, we would want the fixedness values to be $n, n - 1, n - 2, \dots, 0$. That would make a chain of length $n + 1$. However, it's impossible to have fixedness of $n - 1$ after one swap. The first swap always makes a permutation with fixedness $n - 2$. Okay, how about $n, n - 2, n - 3, \dots, 0$ then? That turns o...
[ "constructive algorithms", "math" ]
800
for _ in range(int(input())): n = int(input()) p = [i + 1 for i in range(n)] print(n) for i in range(n): print(*p) if i < n - 1: p[i], p[i + 1] = p[i + 1], p[i]
1716
C
Robot in a Hallway
There is a grid, consisting of $2$ rows and $m$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $m$ from left to right. The robot starts in a cell $(1, 1)$. In one second, it can perform either of two actions: - move into a cell adjacent by a side: up, right, do...
Let's first consider the possible paths across the grid that visit all cells. You can immediately think of two of them. The first one is: go right to the wall, turn into the other row and return. Let's call it a hook. The second one is: go down, go right, go up, go right and so on. Let's call it a snake. Turns out, the...
[ "data structures", "dp", "greedy", "implementation", "ternary search" ]
2,000
INF = 2 * 10**9 for _ in range(int(input())): m = int(input()) a = [[int(x) for x in input().split()] for i in range(2)] su = [[-INF for j in range(m + 1)] for i in range(2)] for i in range(2): for j in range(m - 1, -1, -1): su[i][j] = max(su[i][j + 1] - 1, a[i][j], a[i ^ 1][j] - (2 * (m - j) - 1)) pr = a[0]...
1716
D
Chip Move
There is a chip on the coordinate line. Initially, the chip is located at the point $0$. You can perform any number of moves; each move increases the coordinate of the chip by some positive integer (which is called the length of the move). The length of the first move you make should be divisible by $k$, the length of ...
Let's calculate dynamic programming $dp_{s, i}$ - the number of ways to achieve $i$ in $s$ moves. From the state $(s, i)$, you can make a transition to the states $(s+1, j)$, where $i < j$ and $j - i$ is divisible by $k + s$. Let's try to estimate the maximum number of moves, because it seems that there can't be very m...
[ "brute force", "dp", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int main() { int n, k; cin >> n >> k; vector<int> dp(n + 1), ans(n + 1); dp[0] = 1; for (int mn = 0; mn + k <= n; mn += k++) { vector<int> sum(k); for (int i = mn; i <= n; ++i) { int cur = dp[i]; dp[i] = sum[i % k]...
1716
E
Swap and Maximum Block
You are given an array of length $2^n$. The elements of the array are numbered from $1$ to $2^n$. You have to process $q$ queries to this array. In the $i$-th query, you will be given an integer $k$ ($0 \le k \le n-1$). To process the query, you should do the following: - for every $i \in [1, 2^n-2^k]$ \textbf{in asc...
Let's carefully analyze the operation denoted in the query. Since the length of the array is always divisible by $2^{k+1}$, every element will be swapped with some other element. The elements can be split into two groups - the ones whose positions increase by $2^k$, and the ones whose positions decrease by $2^k$. Let's...
[ "bitmasks", "data structures", "dfs and similar", "divide and conquer", "dp" ]
2,500
#include<bits/stdc++.h> using namespace std; const int K = 18; struct node { long long sum, pref, suff, ans; node(const node& l, const node& r) { sum = l.sum + r.sum; pref = max(l.pref, l.su...
1716
F
Bags with Balls
There are $n$ bags, each bag contains $m$ balls with numbers from $1$ to $m$. For every $i \in [1, m]$, there is exactly one ball with number $i$ in each bag. You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $1$ from the first bag and the ball $2$ from the secon...
The main idea of this problem is to use a technique similar to "contribution to the sum". We will model the value of $F^k$ as the number of tuples $(i_1, i_2, \dots, i_k)$, where each element is an index of a bag from which we have taken an odd ball. Let $G(t)$ be the number of ways to take balls from bags so that all ...
[ "combinatorics", "dp", "math", "number theory" ]
2,500
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 2043; int dp[N][N]; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll ...
1717
A
Madoka and Strange Thoughts
Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $(a, b)$ exist, where $1 \leq a, b \leq n$, for which $\frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3$. In this problem, $\operatorname{gcd}(a, b)$ denotes the greatest common divisor of the numbers $a$ and ...
Notice that only the following pairs of numbers are possible: $(x, x)$, $(x, 2 \cdot x)$, and $(x, 3 \cdot x)$. Proof:Let $d = gcd(a, b)$. Now notice that it's impossible that $a = k \cdot d$ for some $k > 4$, because otherwise $lcm$ will be at least $k \cdot d > 3 \cdot d$. Therefore the only possible cases are the pa...
[ "math", "number theory" ]
800
null
1717
B
Madoka and Underground Competitions
Madoka decided to participate in an underground sports programming competition. And there was exactly one task in it: A square table of size $n \times n$, where \textbf{$n$ is a multiple of $k$}, is called good if only the characters '.' and 'X' are written in it, as well as in any subtable of size $1 \times k$ or $k ...
Notice that the answer to the problem is at least $\frac{n^2}{k}$, because you can split the square into so many non-intersecting rectangles of dimensions $1 \times k$. So let's try to paint exactly so many cells and see if maybe it's always possible. For simplicity, let's first solve the problem without necessarily pa...
[ "constructive algorithms", "implementation" ]
1,100
null
1717
C
Madoka and Formal Statement
Given an array of integer $a_1, a_2, \ldots, a_n$. In one operation you can make $a_i := a_i + 1$ if $i < n$ and $a_i \leq a_{i + 1}$, or $i = n$ and $a_i \leq a_1$. You need to check whether the array $a_1, a_2, \ldots, a_n$ can become equal to the array $b_1, b_2, \ldots, b_n$ in some number of operations (possibly,...
Firstly, we obviously require $a_i \le b_i$ to hold for all $i$. With that out of our way, let's consider non-trivial cases. Also let $a_{n+1} = a_1, b_{n+1} = b_1$ cyclically. For each $i$, we require that either $a_i = b_i$ or $b_i \leq b_{i + 1} + 1$ holds. That's because if we increment $a_i$ at least once, we had ...
[ "greedy" ]
1,300
null
1717
D
Madoka and The Corruption Scheme
Madoka decided to entrust the organization of a major computer game tournament "OSU"! In this tournament, matches are held according to the "Olympic system". In other words, there are $2^n$ participants in the tournament, numbered with integers from $1$ to $2^n$. There are $n$ rounds in total in the tournament. In the...
The problem can be reformulated as follows. We've got a complete binary tree with $2^n$ leaves. There's a marked edge from each intermediate node to one of its children. The winner is the leaf reachable from the root via marked edges. Changes modify the outgoing marked edge of a node. Now it should be fairly obvious th...
[ "combinatorics", "constructive algorithms", "greedy", "math" ]
1,900
null
1717
E
Madoka and The Best University
Madoka wants to enter to "Novosibirsk State University", but in the entrance exam she came across a very difficult task: Given an integer $n$, it is required to calculate $\sum{\operatorname{lcm}(c, \gcd(a, b))}$, for all triples of positive integers $(a, b, c)$, where $a + b + c = n$. In this problem $\gcd(x, y)$ de...
Let's bruteforce $c$, then we have $gcd(a, b) = gcd(a, a + b) = gcd(a, n - c)$. This means that $gcd(a, b)$ divides $n - c$, so let's just go through all divisors of $n - c$. For every factor $d$, the count of pairs $(a, b)$ satisfying $a + b = n - c$ and $gcd(a, b) = d$ is $\phi (\frac{n - c}{d})$, because we need $d$...
[ "math", "number theory" ]
2,200
null
1717
F
Madoka and The First Session
Oh no, on the first exam Madoka got this hard problem: Given integer $n$ and $m$ pairs of integers ($v_i, u_i$). Also there is an array $b_1, b_2, \ldots, b_n$, \textbf{initially filled with zeros}. Then for each index $i$, where $1 \leq i \leq m$, perform either $b_{v_i} := b_{v_i} - 1$ and $b_{u_i} := b_{u_i} + 1$,...
Let's reformulate the problem in terms of graphs. We are given an undirected graph and we are asked to determine edge directions, subject to fixed indegree minus outdegree (hereinafter balance) values for some vertices. It is tempting to think of this as a flow problem: edges indicate pipes with capacity of 1, vertices...
[ "constructive algorithms", "flows", "graph matchings", "graphs", "implementation" ]
2,500
null
1718
A2
Burenka and Traditions (hard version)
\textbf{This is the hard version of this problem. The difference between easy and hard versions is only the constraints on $a_i$ and on $n$. You can make hacks only if both versions of the problem are solved.} Burenka is the crown princess of Buryatia, and soon she will become the $n$-th queen of the country. There is...
Segments of length greater than 2 are not needed. For A1 you can use dynamic programming Dynamic programming where dp[i][v] means the minimum time to make $a_j = 0$ for $j < i$ and $a_i = v$. (Notice that v can be any number from 0 to 8191) There is an answer in which segments of length $2$ does not intersect with segm...
[ "data structures", "dp", "greedy" ]
1,900
t = int(input()) for i in range(t): n = int(input()) lst = list(map(int, input().split())) res = n for i in range(1, n): lst[i] ^= lst[i - 1] st = set() st.add(0) for i in lst: if i in st: res -= 1 st.clear() st.add(i) print(res)
1718
B
Fibonacci Strings
In all schools in Buryatia, in the $1$ class, everyone is told the theory of Fibonacci strings. "A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci strin...
Try to express $n$(the sum of all $c_i$) as $F_1 + F_2 + \ldots + F_m = n$. Let, $n = F_1 + F_2 + \ldots + F_m$, then try to find the minimum $x$ starting from which if there is $c_i=x$ there is no answer. $x$ is (the maximum sum of the Fibonacci numbers, among which there are no neighbors) + 1. $x$ is $F_1 + F_3 + F_5...
[ "greedy", "implementation", "math", "number theory" ]
2,000
null
1718
C
Tonya and Burenka-179
Tonya was given an array of $a$ of length $n$ written on a postcard for his birthday. For some reason, the postcard turned out to be a \textbf{cyclic array}, so the index of the element located strictly to the right of the $n$-th is $1$. Tonya wanted to study it better, so he bought a robot "Burenka-179". A program fo...
The answer for $k=x$ and $k=\gcd(x,n)$ is the same. In this problem, a general statement is useful: for any array $c$ of length $m$, $m\cdot\operatorname{max}(c_1, c_2, \ldots, c_m) \geq c_1 +c_2 +\ldots+c_m$ is true. Try applying the second hint for $k_1$ and $k_2$ divisible by $k_1$, where $k_1, k_2$ are divisors of ...
[ "data structures", "greedy", "math", "number theory" ]
2,400
null
1718
D
Permutation for Burenka
We call an array $a$ pure if all elements in it are pairwise distinct. For example, an array $[1, 7, 9]$ is pure, $[1, 3, 3, 7]$ isn't, because $3$ occurs twice in it. A pure array $b$ is similar to a pure array $c$ if their lengths $n$ are the same and for all pairs of indices $l$, $r$, such that $1 \le l \le r \le n...
Try to reduce the task to a single array and tree. Try to reduce the tree to a match of bipartite graph. The first part: For each $a_i=0$, a segment of suitable values. The second part: The set $S$ and the number $d$. There exist $L$ and $R$ such that the answer to the query is ''YES'' if and only if $L \le d \le R$. L...
[ "data structures", "graph matchings", "greedy", "math", "trees" ]
3,300
null
1718
E
Impressionism
Burenka has two pictures $a$ and $b$, which are tables of the same size $n \times m$. Each cell of each painting has a color — a number from $0$ to $2 \cdot 10^5$, and there are no repeating colors in any row or column of each of the two paintings, except color $0$. Burenka wants to get a picture $b$ from the picture ...
you can notice that a pair of operations $1\, i\, j$, $2\, k\, t$ and $2\, k\, t$, $1\, i\, j$ lead to the same result, what does this mean? This means that operations can be represented as two permutations describing which swaps will occur with rows and which swaps will occur with columns. Try to reduce this problem t...
[ "constructive algorithms", "graphs", "implementation", "math" ]
3,500
#include <iostream> #include "vector" #include "algorithm" #include "numeric" #include "climits" #include "iomanip" #include "bitset" #include "cmath" #include "map" #include "deque" #include "array" #include "set" #include "random" #define all(x) x.begin(), x.end() using namespace std; int swp = 0; vector<vector<pair<...
1718
F
Burenka, an Array and Queries
Eugene got Burenka an array $a$ of length $n$ of integers from $1$ to $m$ for her birthday. Burenka knows that Eugene really likes coprime integers (integers $x$ and $y$ such that they have only one common factor (equal to $1$)) so she wants to to ask Eugene $q$ questions about the present. Each time Burenka will choo...
The only one hint to this problem is don't try to solve, it's not worth it. In order to find the number of numbers from $1$ to $C$ that are mutually prime with $x$, we write out its prime divisors (various). Let these be prime numbers $a_{1}, a_{2}, \ldots, a_{k}$. Then you can find the answer for $2^{k}$ using the inc...
[ "data structures", "math", "number theory" ]
3,300
null
1719
A
Chip Game
Burenka and Tonya are playing an old Buryat game with a chip on a board of $n \times m$ cells. At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any \textbf{odd} number of cells (but you cannot move the chip both to ...
Try to look at the parity of $n, m$. The player who wins does not depend on player's strategy. The only thing that the winning player depends on is the parity of $n, m$. Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, ...
[ "games", "math" ]
800
null
1719
B
Mathematical Circus
A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $n$ and $k$, \textbf{where $n$ is even}. Next, he takes all the integers from $1$ to $n$, and splits them all into pairs $(a, b)$ (each integer must be in exactly one pair) so that for each pair the in...
Instead of $k$, we can consider the remainder of dividing $k$ by 4. There is no answer for the remainder 0. For all other remainders, there is an answer. Note that from the number $k$ we only need the remainder modulo $4$, so we take $k$ modulo and assume that $0 \leq k \leq 3$. If $k = 0$, then there is no answer, bec...
[ "constructive algorithms", "math" ]
800
null
1719
C
Fighting Tournament
Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya. $n$ athletes participate in the tournament, numbered from $1$ to $n$. Burenka determined the strength of the $i$-th athlete as an integer $a_i$, where $1 \leq a_i \leq n$. All the strength v...
Who would win duels if the strongest athlete was the first in queue? After what number of rounds is the strongest athlete guaranteed to be at the front of the queue? Simulate the first $n$ rounds and write down their winners so that for each person you can quickly find out the number of wins in rounds with numbers no m...
[ "binary search", "data structures", "implementation", "two pointers" ]
1,400
null
1720
A
Burenka Plays with Fractions
Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($\frac{a}{b}$ and $\frac{c}{d}$) with integer numerators and denominators. Then children are commanded to play with their fractions. Burenka is a clever kid, so she noticed that when she claps once, she can mult...
Note that we always can make fractions equal in two operations: Multiply first fraction's enumerator by $bc$, the first fraction is equal to $\frac{abc}{b} = ac$, Multiply second fraction's enumerator by $ad$, the second fraction is equal to $\frac{acd}{d} = ac$. That means that the answer does not exceed 2. If fractio...
[ "math", "number theory" ]
900
#include <bits/extc++.h> using namespace std; using namespace __gnu_cxx; using namespace __gnu_pbds; #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define sfor(i, l, r) for (int i = l; i <= r; ++i) #define bfor(i, r, l) for (int i = r; i >= l; --i) #define all(a) a.begin(), a.end() using ll = long...
1720
B
Interesting Sum
You are given an array $a$ that contains $n$ integers. You can choose any proper subsegment $a_l, a_{l + 1}, \ldots, a_r$ of this array, meaning you can choose any two integers $1 \le l \le r \le n$, where $r - l + 1 < n$. We define the beauty of a given subsegment as the value of the following expression: $$\max(a_{1...
Obviously, answer does not exceed $max_{1} + max_{2} - min_{1} - min_{2}$, where $max_{1}, max_{2}$ are two maximum values in the array, and $min_{1}, min_{2}$ are two minimum values. Let's find a segment, such as this is true. For that we will look at all positions containing $max_{1}$ or $max_{2}$ ($S_{1}$) and all p...
[ "brute force", "data structures", "greedy", "math", "sortings" ]
800
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long ll; typedef long double ld; #define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); vector<ll> vec; ll n; int main() { fastInp; ll t; cin >> t; while (t--) { cin >> n; vec.resize(n); for (a...
1720
C
Corners
You are given a matrix consisting of $n$ rows and $m$ columns. Each cell of this matrix contains $0$ or $1$. Let's call a square of size $2 \times 2$ without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing $1$ and replace all numbers in it with zer...
Let's say that $cnt_1$ is the number of ones in the table. Note that if there is a connected area of zeros in the table of size at least 2, then we can add one $0$ to this area by replacing only one 1 in the table. That means that if we have such area we can fill the table with zeros in $cnt_1$ operations (we can't mak...
[ "greedy", "implementation" ]
1,200
#include <iostream> #include <vector> #include <algorithm> #include <array> #include <cassert> #include <map> #include <set> #include <cmath> #include <deque> #include <random> #include <iomanip> #include <chrono> #include <bitset> #include <queue> #include <complex> #include <functional> using namespace std; const i...
1720
D1
Xor-Subsequence (easy version)
\textbf{It is the easy version of the problem. The only difference is that in this version $a_i \le 200$.} You are given an array of $n$ integers $a_0, a_1, a_2, \ldots a_{n - 1}$. Bryap wants to find the longest \textbf{beautiful} subsequence in the array. An array $b = [b_0, b_1, \ldots, b_{m-1}]$, where $0 \le b_0...
Let's use dynamic programming to solve this task. $dp_i$ -- maximum length of good subsequence, that ends int $i$-th element of $a$, than naive solution is $dp_i = \max_{\substack{j = 0 \\ a_j \oplus i < a_i \oplus j}}^i dp_j + 1$ Let's observe that $a_j \oplus i$ changes $i$ not more than by $200$. This way we can rel...
[ "bitmasks", "brute force", "dp", "strings", "trees", "two pointers" ]
1,800
#include <iostream> #include <vector> using namespace std; typedef long long ll; typedef long double ld; #define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); vector<ll> vec; ll n; const ll CHECK = 512; int solve() { cin >> n; vec.resize(n); for (auto& c : vec) cin >> c; vector<ll> dp(1); ...
1720
D2
Xor-Subsequence (hard version)
\textbf{It is the hard version of the problem. The only difference is that in this version $a_i \le 10^9$.} You are given an array of $n$ integers $a_0, a_1, a_2, \ldots a_{n - 1}$. Bryap wants to find the longest \textbf{beautiful} subsequence in the array. An array $b = [b_0, b_1, \ldots, b_{m-1}]$, where $0 \le b_...
Let's calculate answer for each prefix. Let's find answer if the last number in our subsequence is number with index $i$. Let there be such $j$ that $a[j] \oplus i < a[i] \oplus j$. That means that there are $k$ bits in numbers $a[j] \oplus i$ and $a[i] \oplus j$ which are the same, and after that $a[j] \oplus i$ has d...
[ "bitmasks", "data structures", "dp", "strings", "trees" ]
2,400
#include <iostream> #include <vector> #include <algorithm> using namespace std; const int maxlog = 30; const int maxn = 300000; int nodes[maxn * maxlog + maxlog][2]; int nodev[maxn * maxlog + maxlog][2]; int last; inline int f() { nodes[last][0] = 0; nodes[last][1] = 0; nodev[last][0] = 0; nodev[las...
1720
E
Misha and Paintings
Misha has a \textbf{square} $n \times n$ matrix, where the number in row $i$ and column $j$ is equal to $a_{i, j}$. Misha wants to modify the matrix to contain \textbf{exactly} $k$ distinct integers. To achieve this goal, Misha can perform the following operation zero or more times: - choose any \textbf{square} submat...
If $k$ is greater than the number of different numbers in the matrix, then the answer is $k$ minus the number of different elements. Otherwise the answer does not exceed 2. Let's proof that: choose the maximum square (let its side be equal to $L$), containing the top left corner of the matrix, such as recolouring it to...
[ "constructive algorithms", "data structures", "greedy", "implementation", "math" ]
2,700
#include <iostream> #include <vector> #include <cmath> #include <array> using namespace std; const int INF = 1e9; inline int min(int a, int b) { if (a < b) return a; return b; } inline int max(int a, int b) { if (a > b) return a; return b; } inline void solve1() { int n, k, cnt = 0; cin >> n...
1721
A
Image
You have an image file of size $2 \times 2$, consisting of $4$ pixels. Each pixel can have one of $26$ different colors, denoted by lowercase Latin letters. You want to recolor some of the pixels of the image \textbf{so that all $4$ pixels have the same color}. In one move, you can choose \textbf{no more than two} pix...
There are some solutions based on case analysis, but in my opinion, the most elegant one is the following: Let's pick a color with the maximum possible number of pixels and repaint all other pixels into it. We will try to pick all pixels of some other color and repaint them in one operation, and we can ignore the const...
[ "greedy", "implementation" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { string s1, s2; cin >> s1 >> s2; s1 += s2; cout << set<char>(s1.begin(), s1.end()).size() - 1 << endl; } }
1721
B
Deadly Laser
The robot is placed in the top left corner of a grid, consisting of $n$ rows and $m$ columns, in a cell $(1, 1)$. In one step, it can move into a cell, adjacent by a side to the current one: - $(x, y) \rightarrow (x, y + 1)$; - $(x, y) \rightarrow (x + 1, y)$; - $(x, y) \rightarrow (x, y - 1)$; - $(x, y) \rightarrow ...
First, let's determine if it's possible to reach the end at all. If the laser's field doesn't span until any wall, then it's surely possible - just stick to the wall yourself. If it touches at most one wall, it's still possible. If it's the bottom wall or the left wall, then take the path close to the top and the right...
[ "implementation" ]
1,000
for _ in range(int(input())): n, m, sx, sy, d = map(int, input().split()) if min(sx - 1, m - sy) <= d and min(n - sx, sy - 1) <= d: print(-1) else: print(n + m - 2)
1721
C
Min-Max Array Transformation
You are given an array $a_1, a_2, \dots, a_n$, which is sorted in non-descending order. You decided to perform the following steps to create array $b_1, b_2, \dots, b_n$: - Create an array $d$ consisting of $n$ arbitrary \textbf{non-negative} integers. - Set $b_i = a_i + d_i$ for each $b_i$. - Sort the array $b$ in no...
For the start, let's note that $a_i \le b_i$ for each $i$. Otherwise, there is no way to get $b$ from $a$. Firstly, let's calculate $d_i^{min}$ for each $i$. Since all $d_i \ge 0$ then $b_j$ is always greater or equal than $a_i$ you get it from. So, the minimum $d_i$ would come from lowest $b_j$ that still $\ge a_i$. S...
[ "binary search", "greedy", "two pointers" ]
1,400
fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() } val b = readLine()!!.split(' ').map { it.toInt() } val indices = (0 until n).sortedBy { a[it] } val mn = Array(n) { 0 } val mx = Array(n) { 0 }...
1721
D
Maximum AND
You are given two arrays $a$ and $b$, consisting of $n$ integers each. Let's define a function $f(a, b)$ as follows: - let's define an array $c$ of size $n$, where $c_i = a_i \oplus b_i$ ($\oplus$ denotes bitwise XOR); - the value of the function is $c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$ (i.e. bi...
We will build the answer greedily, from the highest significant bit to the lowest one. Let's analyze how to check if the answer can have the highest bit equal to $1$. It means that every value in $c$ should have its highest bit equal to $1$, so for every $i$, exactly one of the numbers $\{a_i, b_i\}$ should have this b...
[ "bitmasks", "dfs and similar", "divide and conquer", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n), b(n); for (int& x : a) cin >> x; for (int& x : b) cin >> x; auto check = [&](int ans) { map<int, int> cnt; ...
1721
E
Prefix Function Queries
You are given a string $s$, consisting of lowercase Latin letters. You are asked $q$ queries about it: given another string $t$, consisting of lowercase Latin letters, perform the following steps: - concatenate $s$ and $t$; - calculate the prefix function of the resulting string $s+t$; - print the values of the prefi...
What's the issue with calculating the prefix function on the string $s$ and then appending the string $t$ with an extra $|t|$ recalculations? Calculating prefix function is linear anyway. Well, it's linear, but it's also amortized. So while it will make $O(n)$ operations for a string in total, it can take up to $O(n)$ ...
[ "dfs and similar", "dp", "hashing", "string suffix structures", "strings", "trees" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int AL = 26; vector<int> prefix_function(const string &s){ int n = s.size(); vector<int> p(n); for (int i = 1; i < n; ++i){ int k = p[i - 1]; while (k > 0 && s[i] != s[k]) k = p[k - 1]; k += (s[i] == ...
1721
F
Matching Reduction
You are given a bipartite graph with $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges. The maximum matching in this graph is the maximum possible (by size) subset of edges of this graph such that no vertex is incident to more than one chosen edge. You have to process two types of quer...
Let's start by finding the maximum matching in the given graph. Since the constraints are pretty big, you need something fast. The model solution converts the matching problem into a flow network and uses Dinic to find the matching in $O(m^{1.5})$, but something like heavily optimized Kuhn's algorithm can also work. Ok...
[ "brute force", "constructive algorithms", "dfs and similar", "flows", "graph matchings", "graphs", "interactive" ]
2,800
#include<bits/stdc++.h> using namespace std; const int N = 400043; const int INF = int(1e9); struct edge { int y, c, f; edge() {}; edge(int y, int c, int f) : y(y), c(c), f(f) {}; }; vector<edge> e; vector<int> g[N]; int S, T, V; int d[N], lst[N]; int n1, n2, m, q; map<pair<int, int>, int> es; void add...
1722
A
Spell Check
Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters. Today he wrote string $s$ of length ...
Check if the string has length 5 and if it has the characters $\texttt{T}, \texttt{i}, \texttt{m}, \texttt{u}, \texttt{r}$. The complexity is $\mathcal{O}(n)$. You can also sort the string, and check if it is $\texttt{Timur}$ when sorted (which is $\texttt{Timru}$).
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { string name = "Timur"; sort(name.begin(), name.end()); int n; cin >> n; forn(i, n) { int m; cin >> m; string s; cin >> s; sort(s.begin(), s.end()...
1722
B
Colourblindness
Vasya has a grid with $2$ rows and $n$ columns. He colours each cell red, green, or blue. Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.
Here are two solutions. Solution 1. Iterate through the string character by character. If $s_i=\texttt{R}$, then $t_i=\texttt{R}$; otherwise, if $s_i=\texttt{G}$ or $\texttt{B}$, then $t_i=\texttt{G}$ or $\texttt{B}$. If the statement is false for any $i$, the answer is NO. Otherwise it is YES. Solution 2. Replace all ...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s, t; cin >> s >> t; for (int i = 0; i < n; i++) { if (s[i] == 'R') { if (t[i] != 'R') {cout << "NO\n"; return;} } else { if (t[i] == 'R') {cout << "NO\n"; return;...
1722
C
Word Game
Three guys play a game: first, each person writes down $n$ distinct words of length $3$. Then, they total up the number of points as follows: - if a word was written by one person — that person gets 3 points, - if a word was written by two people — each of the two gets 1 point, - if a word was written by all — nobody ...
You need to implement what is written in the statement. To quickly check if a word is written by another guy, you should store some map<string, int> or Python dictionary, and increment every time you see a new string in the input. Then, you should iterate through each guy, find the number of times their word appears, a...
[ "data structures", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; map<string, int> mp; string a[3][n]; for (int i = 0; i < 3; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; mp[a[i][j]]++; } } for (int i = 0; i < 3; i++) { int to...
1722
D
Line
There are $n$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The \textbf{value} of the line is the sum of each person's count. For example, in the arrangement LRRLL, where L stands for a person looking left and R sta...
For each person, let's calculate how much the value will change if they turn around. For example, in the line LRRLL, if the $i$-th person turns around, then the value of the line will change by $+4$, $-2$, $0$, $-2$, $-4$, respectively. (For instance, if the second person turns around, they see $3$ people before and $1...
[ "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s; cin >> s; long long tot = 0; vector<long long> v; for (int i = 0; i < n; i++) { if (s[i] == 'L') { v.push_back((n - 1 - i) - i); tot += i; } else { v.push_...
1722
E
Counting Rectangles
You have $n$ rectangles, the $i$-th rectangle has height $h_i$ and width $w_i$. You are asked $q$ queries of the form $h_s \ w_s \ h_b \ w_b$. For each query output, the total area of rectangles you own that \textbf{can fit}a rectangle of height $h_s$ and width $w_s$ while also \textbf{fitting in} a rectangle of heig...
Consider the 2D array with $a[x][y]=0$ for all $x,y$. Increase $a[h][w]$ by $h \times w$ if there is an $h \times w$ rectangle in the input. Now for each query, we need to find the sum of all $a[x][y]$ in a rectangle with lower-left corner at $a[h_s+1][w_s+1]$ and upper-right corner at $a[h_b-1][w_b-1]$. This is the st...
[ "brute force", "data structures", "dp", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; long long a[1005][1005]; long long pref[1005][1005]; void solve() { long long n, q; cin >> n >> q; for(int i = 0; i <= 1001; i++) { for(int j = 0; j <= 1001; j++) { a[i][j] = pref[i][j] = 0; } } for(int i = 0; i...
1722
F
L-shapes
An L-shape is a figure on gridded paper that looks like the first four pictures below. An L-shape contains exactly three shaded cells (denoted by *), which can be rotated in any way. You are given a rectangular grid. Determine if it contains L-shapes only, where L-shapes can't touch an edge or corner. More formally: ...
The problem is mainly a tricky implementation problem. Let's denote the elbow of an L-shape as the square in the middle (the one that is side-adjacent to two other squares). Every elbow is part of exactly one L-shape, and every L-shape has exactly one elbow. Iterate through the grid and count the number of side-adjacen...
[ "dfs and similar", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; const int dx[3] = {-1, 0, 1}, dy[3] = {-1, 0, 1}; void solve() { int n, m; cin >> n >> m; char g[n][m]; int id[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> g[i][j]; id[i][j] = ...
1722
G
Even-Odd XOR
Given an integer $n$, find any array $a$ of $n$ \textbf{distinct} nonnegative integers less than $2^{31}$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.
There are a lot of solutions to this problem. Here I will describe one of them. First, we observe that having the XOR of even indexed numbers and odd indexed numbers equal is equivalent to having the XOR of all the elements equal to 0. Let's note with $a$ the XOR of all odd indexed numbers and $b$ the xor of all even i...
[ "bitmasks", "constructive algorithms", "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int case1 = 0; int case2 = 0; for(int i = 0; i < n-2; i++) { case1^=i; case2^=(i+1); } long long addLast = ((long long)1<<31)-1; if(case1 != 0) { for(int i = 0; i < n-2; i++) ...
1725
A
Accumulation of Dominoes
Pak Chanek has a grid that has $N$ rows and $M$ columns. Each row is numbered from $1$ to $N$ from top to bottom. Each column is numbered from $1$ to $M$ from left to right. Each tile in the grid contains a number. The numbers are arranged as follows: - Row $1$ contains integers from $1$ to $M$ from left to right. - ...
We can divide the dominoes into two types: Horizontal dominoes. A domino is horizontal if and only if it consists of tiles that are on the same row. Vertical dominoes. A domino is vertical if and only if it consists of tiles that are on the same column. For an arbitrary tile in the grid that is not on the rightmost col...
[ "math" ]
800
null
1725
B
Basketball Together
A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $5$ players in one team for each match). There are $N$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $i$-th candidate player...
For a team of $c$ players with a biggest power of $b$, the total power of the team is $b \times c$. So for a team with a biggest power of $b$ to win, it needs to have at least $\lceil \frac{D+1}{b} \rceil$ players. For each player $i$, we can calculate a value $f(i)$ which means a team that has player $i$ as its bigges...
[ "binary search", "greedy", "sortings" ]
1,000
null
1725
C
Circular Mirror
Pak Chanek has a mirror in the shape of a circle. There are $N$ lamps on the circumference numbered from $1$ to $N$ in clockwise order. The length of the arc from lamp $i$ to lamp $i+1$ is $D_i$ for $1 \leq i \leq N-1$. Meanwhile, the length of the arc between lamp $N$ and lamp $1$ is $D_N$. Pak Chanek wants to colour...
Let's represent the mirror as a circle with $N$ points at the circumference. First, one should notice that a circumscribed triangle (triangle whose vertices lie on the circumference of a circle) is a right triangle if only if one side of the triangle is the diameter of the circle. That means, for a single colour, there...
[ "binary search", "combinatorics", "geometry", "math", "two pointers" ]
2,000
null
1725
D
Deducing Sortability
Let's say Pak Chanek has an array $A$ consisting of $N$ positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following: - Choose an index $p$ ($1 \leq p \leq N$). - Let $c$ be the number of operations that have been done \textbf{on index $p$} before this operation. - ...
Define an array as distinctable if and only if Pak Chanek can do zero or more operations to make the elements of the array different from each other. Finding a sortable array $A$ of size $N$ with the minimum possible sum of elements is the same as finding a distinctable array $A$ of size $N$ with the minimum possible s...
[ "binary search", "bitmasks", "math" ]
2,900
null
1725
E
Electrical Efficiency
In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other...
Note that $\sum_x \sum_y \sum_z f(x,y,z) \times g(x,y,z)$ can be alternatively expressed as the following: Iterate through every edge $e$ and every prime $p$. In each iteration, consider the set of vertices $S = \{x \mid A_x \text{ is divisible by } p\}$. Count how many triplets $a,b,c \in S$ such that each of the two ...
[ "combinatorics", "data structures", "dp", "math", "number theory", "trees" ]
2,500
null
1725
E
Electrical Efficiency
In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other...
Special thanks to Um_nik for sharing this solution! Let's call $(i)$ as type $1$ cycles, $(i,j)$ as type $2$ cycles and $(i,j,i+1,j+1)$ as type $3$ cycles. What we will do, is we will fix the number of type $3$ and type $2$ cycles and come up with a formula. Let's say there are $s$ type $3$ cycles. We need to pick $2s$...
[ "combinatorics", "data structures", "dp", "math", "number theory", "trees" ]
2,500
#include<bits/stdc++.h> using namespace std; #define ll long long const int MAXN = 300005; /* PARTS OF CODE for fft taken from https://cp-algorithms.com/algebra/fft.html */ const ll mod = 998244353; const ll root = 15311432; // which is basically 3 ^ 119 const ll root_1 = 469870224; const ll root_pw = (1 << 23); ...
1725
F
Field Photography
Pak Chanek is traveling to Manado. It turns out that OSN (Indonesian National Scientific Olympiad) 2019 is being held. The contestants of OSN 2019 are currently lining up in a field to be photographed. The field is shaped like a grid of size $N \times 10^{100}$ with $N$ rows and $10^{100}$ columns. The rows are numbere...
Let's consider some value of $W_j$. Let $b$ be the LSB (Least Significant Bit) of $W_j$. Which means $b$ is the minimum number such that the bit in index $b$ in the binary representation of $W_j$ is active. Note: the bits are indexed from $0$ from the right. For a sequence of operations, define $\text{dis}(i)$ as how m...
[ "bitmasks", "data structures", "sortings" ]
2,100
null
1725
G
Garage
Pak Chanek plans to build a garage. He wants the garage to consist of a square and a right triangle that are arranged like the following illustration. Define $a$ and $b$ as the lengths of two of the sides in the right triangle as shown in the illustration. An integer $x$ is suitable if and only if we can construct a g...
Let $c$ be the bottom side of the right triangle (the side that is not $a$ or $b$). From Pythagorean theorem, we know that $a^2+c^2 = b^2$, so $c^2 =b^2-a^2$. We can see that the area of the square at the bottom is $c^2$. So an integer is suitable if and only if it can be expressed as $b^2-a^2$ for some positive intege...
[ "binary search", "geometry", "math" ]
1,500
null
1725
H
Hot Black Hot White
One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones. Dr. Chanek has $N$ magical stones with $N$ being an even number. Those magical stones are numbered from $1$ to $N$. Magical stone $i$ has a strength of $A_i$. A magical sto...
Notice that $10 \equiv 1 \mod 3$. Hence, if $k$ denotes the number of digits in $A_j$, $\text{concat}(A_i, A_j) \mod 3= (A_i \times 10^k + A_j) \mod 3 = (A_i \times 1^k + A_j) \mod 3 = (A_i + A_j) \mod 3$. Then one can simplify the equation that determines the reaction of stone $i$ and stone $j$ as follows. $\begin{ali...
[ "constructive algorithms", "math" ]
1,800
null
1725
I
Imitating the Key Tree
Pak Chanek has a tree called the key tree. This tree consists of $N$ vertices and $N-1$ edges. The edges of the tree are numbered from $1$ to $N-1$ with edge $i$ connecting vertices $U_i$ and $V_i$. Initially, each edge of the key tree does not have a weight. Formally, a path with length $k$ in a graph is a sequence $...
Let's say we have two graphs, each having $N$ vertices. Initially, there are no edges. We want to make the first graph into a graph that satisfies the condition of the problem and make the second graph into the key tree with a weight assignment that corresponds to the first graph. Sequentially for each $k$ from $1$ to ...
[ "combinatorics", "dsu", "trees" ]
2,800
null
1725
J
Journey
One day, Pak Chanek who is already bored of being alone at home decided to go traveling. While looking for an appropriate place, he found that Londonesia has an interesting structure. According to the information gathered by Pak Chanek, there are $N$ cities numbered from $1$ to $N$. The cities are connected to each ot...
For a journey, define $\text{cnt}(i)$ as a non-negative integer representing the number of times Pak Chanek traverses road $i$ throughout the journey. First, let's solve the simpler problem where we cannot teleport. It can be obtained that the configuration of $\text{cnt}(i)$ for an optimal journey in this version of t...
[ "dp", "trees" ]
2,500
null
1725
K
Kingdom of Criticism
Pak Chanek is visiting a kingdom that earned a nickname "Kingdom of Criticism" because of how often its residents criticise each aspect of the kingdom. One aspect that is often criticised is the heights of the buildings. The kingdom has $N$ buildings. Initially, building $i$ has a height of $A_i$ units. At any point i...
We can see that the changes in height for a single query of type $3$ are as follows: Each building with height $x$ such that $l \leq x \leq \frac{l+r}{2}$ is changed to have a height of $l-1$. Each building with height $x$ such that $\frac{l+r}{2} \leq x \leq r$ is changed to have a height of $r+1$. Note: since $r-l$ i...
[ "data structures", "dsu" ]
2,500
null
1725
L
Lemper Cooking Competition
Pak Chanek is participating in a lemper cooking competition. In the competition, Pak Chanek has to cook lempers with $N$ stoves that are arranged sequentially from stove $1$ to stove $N$. Initially, stove $i$ has a temperature of $A_i$ degrees. A stove can have a negative temperature. Pak Chanek realises that, in orde...
Note that an operation is identical to choosing an index $p$ ($1 < p < N$) and doing the following things simultaneously: Increase $A_{p-1}$ by $A_p$. Increase $A_p$ by $-2 A_p$. Increase $A_{p+1}$ by $A_p$. Let's maintain array $A$ using its prefix sum $B_0, B_1, B_2, \ldots, B_N$. Formally, define $B_i = A_1 + A_2 + ...
[ "data structures" ]
2,400
null
1725
M
Moving Both Hands
Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $N$ vertices and $M$ edges. In the graph, edge $i$ connects two different vertices $U_i$ and $V_i$ with a length of $W_i$. By using the $i$-th edge, something can move from $U_i$ to $V_i$, but not from $V_i$ to $U_i$. T...
Suppose we are trying to find out the minimum time to get the hands from vertices $1$ and $k$ to the same vertex. If both hands end up on some vertex $v$, then the time required is $d(1,v) + d(k,v)$, with $d(x,y)$ being the minimum distance to go from vertex $x$ to $y$. Suppose $d'(x,y)$ is the minimum distance to go f...
[ "dp", "graphs", "shortest paths" ]
1,800
null
1726
A
Mainak and Array
Mainak has an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. He will do the following operation to this array \textbf{exactly once}: - Pick a subsegment of this array and cyclically rotate it by any amount. Formally, he can do the following exactly once: - Pick two integers $l$ and $r$, such that $1 \le l \...
There are four candidates of the maximum value of $a_n - a_1$ achievable, each of which can be found in $\mathcal O(n)$ time. No subarray is chosen: Answer would be $a_n - a_1$ in this case. Chosen subarray contains $a_n$ and $a_1$ : Answer would be $\max\limits_{i = 1}^n\{ a_{(i - 1)} - a_i\}$ where $a_0$ is same as $...
[ "greedy", "math" ]
900
t=int(input()) for _ in range(t): n=int(input()) a=[int(x) for x in input().split()] ans=max(a[-1]-min(a),max(a)-a[0]) for i in range(n): ans=max(ans,a[i-1]-a[i]) print(ans)
1726
B
Mainak and Interesting Sequence
Mainak has two positive integers $n$ and $m$. Mainak finds a sequence $a_1, a_2, \ldots, a_n$ of $n$ positive integers interesting, if \textbf{for all} integers $i$ ($1 \le i \le n$), the bitwise XOR of all elements in $a$ which are \textbf{strictly less} than $a_i$ is $0$. Formally if $p_i$ is the bitwise XOR of all ...
Lemma: In an interesting sequence $a_1, a_2, \ldots, a_n$, every element other than the largest must have even occurrences. Proof: For the sake of contradiction, assume that for some $x$ ($x > 0$), such than $x \ne \max\limits_{i = 1}^n\{a_i\}$, $x$ appears an odd number of times. Let $P(z)$ denote the bitwise XOR of a...
[ "bitmasks", "constructive algorithms", "math" ]
1,100
import sys input = sys.stdin.readline t=int(input()) for _ in range(t): n,m=map(int,input().split()) if n>m or (n%2==0 and m%2==1): print("NO") else: print("YES") ans=[] if n%2==1: ans.extend([1]*(n-1)+[m-n+1]) else: ans.extend([1]*(n-2)+[(m-n...
1726
C
Jatayu's Balanced Bracket Sequence
Last summer, Feluda gifted Lalmohan-Babu a \textbf{balanced} bracket sequence $s$ of length $2 n$. Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $2 n$ vertices using the \underline{balanced bracket sequence} $s$. For any two distinct vertices $i$ and $j$ ($1 \le i < ...
Claim: The answer is one more than the number of occurrences of the substring "((" in the balanced bracket sequence given (considering overlapping occurrences as well). Proof: Observe the behavior of the lowest index $k$ of any connected component. The properties that would hold true are: $s_k =$ '('. This is because f...
[ "data structures", "dsu", "graphs", "greedy" ]
1,300
t=int(input()) for _ in range(t): n=int(input()) s=input() print(1+s.count("(")-s.count("()"))
1726
D
Edge Split
You are given a connected, undirected and unweighted graph with $n$ vertices and $m$ edges. Notice \textbf{the limit on the number of edges}: $m \le n + 2$. Let's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. ...
Let's say for convenience that the set of red edges is called $R$ and the set of blue edges is called $B$. Fact: In at least one optimal configuration, $R$ or $B$ forms a spanning tree. Proof: Let's say that $R$ is not a spanning tree in some optimal configuration. If we move an edge connecting two disconnected vertice...
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs", "probabilities", "trees" ]
2,000
#include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" void dfs(int u,const vector<vector<pair<int,int>>>& g,vector<bool>& vis,vector<int>& dep,vector<int>& par,string& s) { vis[u]=true; for(auto [v,idx]:g[u]) { if(vis[v]) continue; dep[v]=dep[u]+1; ...
1726
F
Late For Work (submissions are not allowed)
\textbf{This problem was copied by the author from another online platform. Codeforces strongly condemns this action and therefore further submissions to this problem are not accepted.} Debajyoti has a very important meeting to attend and he is already very late. Harsh, his driver, needs to take Debajyoti to the desti...
The $d_i$ are irrelevant. Take partial sums and add them to each $c_i$ modulo $T$. If your start time is fixed, it is never beneficial to wait at a green light. Drive whenever you can. Visualise the problem as $n$ parallel lines, each coloured with a red and green interval. Now imagine the car moving up (and looping ba...
[ "data structures", "greedy", "schedules", "shortest paths" ]
2,900
#include<bits/stdc++.h> using namespace std; using lol=long long int; const lol inf=1e18+8; struct IntervalUnion{ set<int> lf,ri; map<int,int> lr,rl; void add(int l,int r) { if(!ri.empty()) { auto it=ri.lower_bound(r); if(it!=ri.end() && rl[*it]<=l) return; ...
1726
G
A Certain Magical Party
There are $n$ people at a party. The $i$-th person has an amount of happiness $a_i$. Every person has a certain kind of personality which can be represented as a binary integer $b$. If $b = 0$, it means the happiness of the person will increase if he tells the story to someone \textbf{strictly less} happy than them. I...
First of all, if there is only $1$ distinct value of happiness, any ordering is fine since no one has strictly greater or lesser happiness, and the answer is $n!$. From here on, we assume that there are at least $2$ distinct values of happiness. Note: The notation $<u,v>$ refers to elements with happiness $u$ and behav...
[ "combinatorics", "data structures", "greedy", "sortings" ]
3,300
#include<bits/stdc++.h> #define ll long long #define pb push_back #define mp make_pair #define pii pair<int, int> #define pll pair<ll, ll> #define ff first #define ss second #define vi vector<int> #define vl vector<ll> #define vii vector<pii> #define vll vector<pll> #define FOR(i,N) for(i=0;i<(N);++i) #define FORe(i,...
1726
H
Mainak and the Bleeding Polygon
Mainak has a convex polygon $\mathcal P$ with $n$ vertices labelled as $A_1, A_2, \ldots, A_n$ in a counter-clockwise fashion. The coordinates of the $i$-th point $A_i$ are given by $(x_i, y_i)$, where $x_i$ and $y_i$ are both integers. Further, it is known that the interior angle at $A_i$ is either a right angle or a...
Clearly, the unsafe area is bounded by the envelope of the curve you get if you slide a rod of length $1$ around the interior of the polygon and pressed against the edges at all times. Observation 1: The length of each side of the polygon is $\geq 1$. This one is obvious. Further, it implies that (almost always) we onl...
[ "binary search", "geometry", "implementation", "math" ]
3,500
#include<bits/stdc++.h> using namespace std; using lol=long long int; using ldd=long double; #define endl "\n" const ldd PI=acos(-1.0); const int ITERATIONS = 60; const int PRECISION = 11; struct Point{ lol x,y; Point& operator-=(const Point& rhs){ x-=rhs.x,y-=rhs.y; return *this; } fri...
1728
A
Colored Balls: Revisited
The title is a reference to the very first Educational Round from our writers team, Educational Round 18. There is a bag, containing colored balls. There are $n$ different colors of balls, numbered from $1$ to $n$. There are $\mathit{cnt}_i$ balls of color $i$ in the bag. The total amount of balls in the bag is odd (e...
Let's prove that the color with the maximum value of $cnt$ is one of the possible answers. Let the color $x$ have the maximum value of $cnt$; if there are several such colors, choose any of them. Let's keep taking the balls of two different colors out of the bag without touching the balls of color $x$ for as long as po...
[ "brute force", "greedy", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; cout << max_element(a.begin(), a.end()) - a.begin() + 1 << '\n'; } }
1728
B
Best Permutation
Let's define the value of the permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once) as follows: - initially, an integer variable $x$ is equal to $0$; - if $x < p_1$, then add $p_1$ to $x$ (set $x = x + p_1$), otherwise assign $0$ to $x$; -...
Let $x_i$ be the value of the variable $x$ after $i$ steps. Note that $x_{n-1}$ should be less than $p_n$ for $x_n$ to be not equal to $0$. It means that $x_n$ does not exceed $2p_n - 1$. It turns out that for $n \ge 4$ there is always a permutation such that $x_n$ is equal to $2n - 1$. The only thing left is to find o...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> p(n); iota(p.begin(), p.end(), 1); for (int i = n & 1; i < n - 2; i += 2) swap(p[i], p[i + 1]); for (int &x : p) cout << x << ' '; cout << '\n'; } }
1728
C
Digital Logarithm
Let's define $f(x)$ for a positive integer $x$ as the length of the base-10 representation of $x$ without leading zeros. I like to call it a digital logarithm. Similar to a digital root, if you are familiar with that. You are given two arrays $a$ and $b$, each containing $n$ positive integers. In one operation, you do...
First, why can you always make the arrays similar? Applying a digital logarithm to any number will eventually make it equal to $1$. Thus, you can at least make all numbers into $1$s in both arrays. Then notice the most improtant thing - applying the digital logarithm to a number greater than $1$ always makes this numbe...
[ "data structures", "greedy", "sortings" ]
1,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int t; scanf("%d", &t); forn(_, t){ int n; scanf("%d", &n); vector<int> a(n), b(n); forn(i, n) scanf("%d", &a[i]); forn(i, n) scanf("%d", &b[i]); priority_queue<int> qa(a.begin(), a.end()); ...
1728
D
Letter Picking
Alice and Bob are playing a game. Initially, they are given a non-empty string $s$, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty. Alice starts, then they alternate moves. In one move, a player takes either the first or the last let...
What do we do, when the array loses elements only from the left or from the right and the constraints obviously imply some quadratic solution? Well, apply dynamic programming, of course. The classic $dp[l][r]$ - what is the outcome if only the letters from positions $l$ to $r$ (non-inclusive) are left. $dp[0][n]$ is th...
[ "constructive algorithms", "dp", "games", "two pointers" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int comp(char c, char d){ return c < d ? -1 : (c > d ? 1 : 0); } int main() { int t; cin >> t; forn(_, t){ string s; cin >> s; int n = s.size(); vector<vector<int>> dp(n + 1, vector<int>(n + 1)); for (int...
1728
E
Red-Black Pepper
Monocarp is going to host a party for his friends. He prepared $n$ dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless. The $i$-th dish has two values $a_i$ and $b_i$ — its tastiness with red pepper added or black pepper added, r...
Let's start by learning how to answer a query $(1, 1)$ - all red pepper and black pepper options are available. Let's iterate over all options to put the peppers and choose the maximum of them. First, let's use the red pepper for all dishes. Now we want to select some $k$ of them to use black pepper instead of red pepp...
[ "brute force", "data structures", "greedy", "math", "number theory" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; long long gcd(long long a, long long b, long long& x, long long& y) { if (b == 0) { x = 1; y = 0; return a; } long long x1, y1; long long d = gcd(b, a % b, x1, y1); x = y1; y = x1 - y1 * (a / b); return d; ...
1728
F
Fishermen
There are $n$ fishermen who have just returned from a fishing trip. The $i$-th fisherman has caught a fish of size $a_i$. The fishermen will choose some order in which they are going to tell the size of the fish they caught (the order is just a permutation of size $n$). However, they are not entirely honest, and they ...
Suppose we have fixed some order of fishermen and calculated the values of $b_i$. Then, we have the following constraints on $b_i$: all values of $b_i$ are pairwise distinct; for every $i$, $a_i$ divides $b_i$. Not every possible array $b$ meeting these constraints can be achieved with some order of fishermen, but we c...
[ "flows", "graph matchings", "greedy" ]
3,100
#include <bits/stdc++.h> using namespace std; const int N = 1003; int n; int a[N]; vector<int> g[N * N]; int mt[N]; bool used[N * N]; vector<int> val; bool kuhn(int x) { if(used[x]) return false; used[x] = true; for(auto y : g[x]) if(mt[y] == -1 || kuhn(mt[y])) { mt[y] =...
1728
G
Illumination
Consider a segment $[0, d]$ of the coordinate line. There are $n$ lanterns and $m$ points of interest in this segment. For each lantern, you can choose its power — an integer between $0$ and $d$ (inclusive). A lantern with coordinate $x$ illuminates the point of interest with coordinate $y$ if $|x - y|$ is less than o...
Let's start without the queries. How to calculate the number of ways for the given $n$ lanterns? First, it's much easier to calculate the number of bad ways - some point of interest is not illuminated. If at least one point of interest is not illuminated, then all lanterns have power lower than the distance from them t...
[ "binary search", "bitmasks", "brute force", "combinatorics", "dp", "math", "two pointers" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int binpow(int a, int b){ int res = 1; ...
1729
A
Two Elevators
Vlad went into his appartment house entrance, now he is on the $1$-th floor. He was going to call the elevator to go up to his apartment. There are only two elevators in his house. Vlad knows for sure that: - the first elevator is currently on the floor $a$ (it is currently motionless), - the second elevator is locat...
You had to to calculate the time that each elevator would need and compare them. Let the time required by the first elevator be $d_1 = |a - 1|$, and the time required by the second one be $d_2 = |b - c| + |c - 1|$. Then the answer is $1$ if $d_1 < d_2$, $2$ if $d_1 > d_2$ and $3$ if $d_1 = d_2$
[ "math" ]
800
t = int(input()) for _ in range(t): a, b, c = map(int, input().split()) d1 = a - 1 d2 = abs(b - c) + c - 1 ans = 0 if d1 <= d2: ans += 1 if d1 >= d2: ans += 2 print(ans)
1729
B
Decode String
Polycarp has a string $s$ consisting of lowercase Latin letters. He encodes it using the following algorithm. He goes through the letters of the string $s$ from left to right and for each letter Polycarp considers its number in the alphabet: - if the letter number is single-digit number (less than $10$), then just w...
The idea is as follows: we will go from the end of the string $t$ and get the original string $s$. Note that if the current digit is $0$, then a letter with a two-digit number has been encoded. Then we take a substring of length three from the end, discard $0$ and get the number of the original letter. Otherwise, the c...
[ "greedy", "strings" ]
800
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <queue> using namespace std; char get(int i) { return 'a' + i - 1; } void solve() { int n; string s; cin >> n >> s; int i = n - 1; string res; while (i >= 0) { if (s[i] != '0') { res += ...
1729
C
Jumping on Tiles
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $s$. In other words, you are given a string $s$ consisting of lowercase Latin letters. Initially, Polycarp is on the \textbf{first} tile of the row and wants to get to the \t...
It's worth knowing that ways like ('a' -> 'e') and ('a' -> 'c' -> 'e') have the same cost. That is, first you need to understand the letter on the first tile and the last one (conditionally, the letters $first$ and $last$). Then you just need to find all such tiles on which the letters are between the letters $first$ a...
[ "constructive algorithms", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) void solve() { string s; cin >> s; int n = s.size(); map<char, vector<int>> let_to_ind; for (int i = 0; i < n; ++i) { let_to_ind[s[i]].push_back(i); } int d...
1729
D
Friends and the Restaurant
A group of $n$ friends decide to go to a restaurant. Each of the friends plans to order meals for $x_i$ burles and has a total of $y_i$ burles ($1 \le i \le n$). The friends decide to split their visit to the restaurant into several days. Each day, some group of \textbf{at least two} friends goes to the restaurant. Ea...
First, we sort the friends in descending order of $y_i - x_i$. Now for each friend we know the amount of money he lacks, or vice versa, which he has in excess. In order to maximize the number of days, it is most advantageous for friends to break into pairs. It is the number of groups that matters, not the number of peo...
[ "greedy", "sortings", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve(){ int n; cin >> n; vector<ll>x(n), y(n); vector<pair<ll, int>>dif(n); for(auto &i : x) cin >> i; for(auto &i: y) cin >> i; for(int i = 0; i < n; i++){ dif[i].first = y[i] - x[i]; dif[i].second =...
1729
E
Guess the Cycle Size
\textbf{This is an interactive problem}. I want to play a game with you... We hid from you a cyclic graph of $n$ vertices ($3 \le n \le 10^{18}$). A cyclic graph is an undirected graph of $n$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is ex...
The implication was that the solution works correctly with some high probability. So we tried to give such constraints so that the solution probability is very high. The idea: we will output queries of the form $(1, n)$ and $(n, 1)$, gradually increasing $n$ from $2$. If we get an answer to query $-1$ the first time, t...
[ "interactive", "probabilities" ]
1,800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back long long ask(int a, int b) { cout << "? " << a << ' ' << b << endl; long long x; cin >> x; return x; } long long solve()...
1729
F
Kirei and the Linear Function
Given the string $s$ of decimal digits (0-9) of length $n$. A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($l, r$), where $1 \le l \le r \le n$, corresponds to a substring of the str...
Note that the remainder of dividing a number by $9$ is equal to the remainder of dividing its sum of digits by $9$. This is easy to check, because the number $a$ of $n$ digits is representable as a polynomial $a_0 + a_1\cdot 10 + a_2\cdot 100 + \dots + a_{n-1}\cdot 10^{n-1} + a_n\cdot 10^n$, and $10^k$ gives a remainde...
[ "hashing", "math" ]
1,900
#include <bits/stdc++.h> #define endl '\n' using namespace std; typedef pair<int, int> ipair; const int MAXSZ = 200200; const int INF = 2e9; inline int add(int a, int b) { return (a + b >= 9 ? a + b - 9 : a + b); } inline int sub(int a, int b) { return (a < b ? a + 9 - b : a - b); } inline int mul(int a, int b...
1729
G
Cut Substrings
You are given two non-empty strings $s$ and $t$, consisting of Latin letters. In one move, you can choose an occurrence of the string $t$ in the string $s$ and replace it with dots. Your task is to remove all occurrences of the string $t$ in the string $s$ in the minimum number of moves, and also calculate how many \...
First, find all occurrences of $t$ in $s$ as substrings. This can be done using the prefix function. To find the minimum number of times we need to cut substrings, consider all indexes of occurrences. Having considered the index of the occurrence, we cut out the rightmost occurrence that intersects with it. After that,...
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
2,100
#include<cstdio> #include<cstring> const int N=505; const int Mod=1e9+7; char s[N],t[N]; int n,m; int f[N],g[N]; int p[N],tot; inline void Init(){ scanf("%s",s+1); scanf("%s",t+1); n=strlen(s+1); m=strlen(t+1); tot=0; for(int i=1;i+m-1<=n;i++){ bool flg=1; for(int j=1;j<=m;j++) if(s[i+j-1]!=t[j]) flg=0; ...
1730
A
Planets
One day, Vogons wanted to build a new hyperspace highway through a distant system with $n$ planets. The $i$-th planet is on the orbit $a_i$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed. Vogons have two machines to do that. - The first ma...
To solve the problem, it was enough to count the number of planets with the same orbits $cnt_i$ and sum up the answers for the orbits separately. For one orbit, it is advantageous either to use the second machine once and get the cost $c$, or to use only the first one and get the cost equal to $cnt_i$.
[ "data structures", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n, c; cin >> n >> c; vector<int> a(n); map<int, int> mp; int ans = 0; for(int i = 0; i < n; i++){ cin >> a[i]; mp[a[i]]++; if(mp[a[i]] <= c){ ans++; } } cout << ans << endl;...
1730
B
Meeting on the Line
$n$ people live on the coordinate line, the $i$-th one lives at the point $x_i$ ($1 \le i \le n$). They want to choose a position $x_0$ to meet. The $i$-th person will spend $|x_i - x_0|$ minutes to get to the meeting place. Also, the $i$-th person needs $t_i$ minutes to get dressed, so in total he or she needs $t_i + ...
There are many solutions to this problem, here are 2 of them. 1) Let people be able to meet in time $T$, then they could meet in time $T + \varepsilon$, where $\varepsilon > 0$. So we can find $T$ by binary search. It remains to learn how to check whether people can meet for a specific time $T$. To do this, for the $i$...
[ "binary search", "geometry", "greedy", "implementation", "math", "ternary search" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> x(n), t(n); for(int i = 0; i < n; i++) cin >> x[i]; for(int i = 0; i < n; i++) cin >> t[i]; vector<int> a; for(int i = 0; i < n; i++) { a.push_back(x[i] + t[i]); ...
1730
C
Minimum Notation
You have a string $s$ consisting of digits from $0$ to $9$ inclusive. You can perform the following operation any (possibly zero) number of times: - You can choose a position $i$ and delete a digit $d$ on the $i$-th position. Then insert the digit $\min{(d + 1, 9)}$ on any position (at the beginning, at the end or in ...
We leave all suffix minimums by the digits $mn_i$ (digits less than or equal to the minimum among the digits to the right of them), remove the rest and replace them with $\min{(d + 1, 9)}$ (using the described operations) and add to lexicographically minimum order on the right (due to the appropriate order of operation...
[ "data structures", "greedy", "math", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve(){ string s; cin >> s; int n = s.size(); vector<int> a(n); vector<int> mn(n + 1, 9); for(int i = 0; i < n; i++){ a[i] = int(s[i] - '0'); } for(int i = n - 1; i >= 0; i--){ mn[i] = min(mn[i + 1], a[i]); } ...
1730
D
Prefixes and Suffixes
You have two strings $s_1$ and $s_2$ of length $n$, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times: - Choose a positive integer $1 \leq k \leq n$. - Swap the prefix of the string $s_1$ and the suffix of the string $s_2$ of length $k$. Is it possibl...
If you reflect the second string and see what happens, it is easy to see that the elements at the same positions in both strings after any action remain at the same positions relative to each other. Let's combine them into unsorted pairs and treat these pairs as single objects. Now we need to compose a palindrome from ...
[ "constructive algorithms", "strings", "two pointers" ]
2,200
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; string s1, s2; cin >> s1 >> s2; map<pair<int, int>, int> mp; set<pair<int, int>> st; int cnt_odd_simmetric = 0; int cnt_odd = 0; for(int i = 0; i < n; i++){ pair<int, int> p = {s1[i], s2[n - i - ...
1730
E
Maximums and Minimums
You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. Find the number of pairs of indices $(l, r)$, where $1 \le l \le r \le n$, that pass the check. The check is performed in the following manner: - The minimum and maximum numbers are found among $a_l, a_{l+1}, \ldots, a_r$. - The check is passed if t...
Let's introduce some new variables: $lge_i$ - the position of the nearest left greater or equal than $a_i$($-1$ if there is none). $rg_i$ - position of the nearest right greater than $a_i$($n$ if there is none). $ll_i$ - position of the nearest left lower than $a_i$($-1$ if there is none). $rl_i$ - position of the near...
[ "combinatorics", "data structures", "divide and conquer", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 5e5 + 13; const int A = 1e6 + 13; vector<int> divs[A]; int a[N]; int gr_lf[N], gr_rg[N]; int less_lf[N], less_rg[N]; vector<int> pos[A]; int ind[A]; void solve() { int n; cin >> n; for(int i = 0; i < n; i++) { cin >> a[i]; ...
1730
F
Almost Sorted
You are given a permutation $p$ of length $n$ and a positive integer $k$. Consider a permutation $q$ of length $n$ such that for any integers $i$ and $j$, where $1 \le i < j \le n$, we have $$p_{q_i} \le p_{q_j} + k.$$ Find the minimum possible number of inversions in a permutation $q$. A permutation is an array cons...
Let's build a permutation $q$ from left to right. If the current prefix contains the number $i$, let's call the element $p_i$ used, otherwise - unused. Consider the smallest unused element $mn = p_j$. All elements greater than $mn + k$ must also be unused, and all elements less than $mn$ must be used. Then the current ...
[ "bitmasks", "data structures", "dp" ]
2,700
#include <bits/stdc++.h> //#define int long long #define ld long double #define x first #define y second #define pb push_back using namespace std; const int N = 5005; const int K = 8; int n, k, p[N], pos[N], dp[N][1 << K], t[N]; int sum(int r) { int ans = 0; for(; r >= 0; r = (r & r + 1) - 1) an...
1731
A
Joey Takes Money
Joey is low on money. His friend Chandler wants to lend Joey some money, but can't give him directly, as Joey is too proud of himself to accept it. So, in order to trick him, Chandler asks Joey to play a game. In this game, Chandler gives Joey an array $a_1, a_2, \dots, a_n$ ($n \geq 2$) of positive integers ($a_i \ge...
If we take two elements $a_1$ and $a_2$ and do the operation on it as $a_1 \cdot a_2 = x \cdot y$, then it is easy to observe that $x + y$ will attain its maximum value when one of them is equal to $1$. So, the solution for this is $x = 1$ and $y = a_1 \cdot a_2$. Let $n$ be the total number of elements and $P$ ($P = a...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; #define endl '\n' int main(){ ios_base::sync_with_stdio...
1731
B
Kill Demodogs
Demodogs from the Upside-down have attacked Hawkins again. El wants to reach Mike and also kill as many Demodogs in the way as possible. Hawkins can be represented as an $n \times n$ grid. The number of Demodogs in a cell at the $i$-th row and the $j$-th column is $i \cdot j$. El is at position $(1, 1)$ of the grid, a...
To kill the maximum number of demodogs, El can travel in zigzag fashion, i.e. from $(1,1)$ to $(1,2)$ to $(2,2)$ and so on. Thus the answer would be the sum of elements at $(1,1)$, $(1,2)$, $(2,2)$ $\dots$ $(n,n)$. i.e. the answer is $$\sum_{i = 1}^n{i \cdot i} + \sum_{i = 1}^{n-1}{i (i + 1)} = \frac{n(n + 1)(4n - 1)}{...
[ "greedy", "math" ]
1,100
#include<bits/stdc++.h> #define ll long long const int n1=1e9+7; using namespace std; int solve() { ll n; cin>>n; ll ans=((((n*(n+1))%n1)*(4*n-1))%n1*337)%n1; cout<<ans<<endl; } int main() { int t; cin>>t; while(t--) { solve(); } }
1731
C
Even Subarrays
You are given an integer array $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). Find the number of subarrays of $a$ whose $\operatorname{XOR}$ has an even number of divisors. In other words, find all pairs of indices $(i, j)$ ($i \le j$) such that $a_i \oplus a_{i + 1} \oplus \dots \oplus a_j$ has an even number of divisor...
Let's calculate the number of subarrays whose $\operatorname{XOR}$ sum has an odd number of divisors and subtract them from total no of subarrays. Note: A number has an odd number of divisors only if it is a perfect square. So we have to calculate number of subarray having $\operatorname{XOR}$ sum a perfect square. For...
[ "bitmasks", "brute force", "hashing", "math", "number theory" ]
1,700
sq_list=[] p=int(0) while p*p<=400000: sq_list.append(p*p) p+=1 for t in range(int(input())): n=int(input()) a=list(map(int,input().split())) val=int(2*n) z=int(0) m=[z]*val cnt=int(0) curr=int(0) m[curr]+=1 j=0 while j<n: curr^=a[j] for i in sq_list: ...
1731
D
Valiant's New Map
Game studio "DbZ Games" wants to introduce another map in their popular game "Valiant". This time, the map named "Panvel" will be based on the city of Mumbai. Mumbai can be represented as $n \times m$ cellular grid. Each cell $(i, j)$ ($1 \le i \le n$; $1 \le j \le m$) of the grid is occupied by a cuboid building of h...
The basic brute force solution for this problem was to just iterate through all the values of sides possible. Note that the value of sides can range only from $1$ to $1000$ as product of $n \cdot m$ can't exceed $10^6$, so there can't be a cube having all sides greater than $1000$. After setting side length (let's say ...
[ "binary search", "brute force", "data structures", "dp", "two pointers" ]
1,700
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; #define endl '\n' int main(){ ios_base::sync_with_stdio...
1731
E
Graph Cost
You are given an initially empty undirected graph with $n$ nodes, numbered from $1$ to $n$ (i. e. $n$ nodes and $0$ edges). You want to add $m$ edges to the graph, so the graph won't contain any self-loop or multiple edges. If an edge connecting two nodes $u$ and $v$ is added, its weight must be equal to the greatest ...
In each step, adding $e$ edges to the graph with weights $e + 1$ costs one more than the number of edges added. So, the total cost of adding $m$ edges in $s$ steps will be $m + s$. Since the number of edges is given, i. e. fixed, to find the minimum cost, we need to minimize the number of steps. Firstly, let's calculat...
[ "dp", "greedy", "math", "number theory" ]
2,000
#include <bits/stdc++.h> typedef long long ll; using namespace std; #define endl '\n' int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--){ ll n,m; cin>>n>>m; vector<ll> dp(n+1); for(ll i=n;i>=1;i--){ dp[i]=(n/i)*((n/i)-...
1731
F
Function Sum
Suppose you have an integer array $a_1, a_2, \dots, a_n$. Let $\operatorname{lsl}(i)$ be the number of indices $j$ ($1 \le j < i$) such that $a_j < a_i$. Analogically, let $\operatorname{grr}(i)$ be the number of indices $j$ ($i < j \le n$) such that $a_j > a_i$. Let's name position $i$ good in the array $a$ if $\op...
Let's try to write a brute force solution of this using combinatorics. Let's say that $a[i]=t$ now we will try to see that in how many permutations this is contributing towards the answer. Using combinatorics, it can be calculated as $$F(t) = t \cdot {\sum_{i=1}^n \sum_{x=0}^{i-1} \sum_{y = x+1}^{n-i} \left( \binom{i-1...
[ "brute force", "combinatorics", "dp", "fft", "math" ]
2,500
#include <bits/stdc++.h> #define ll long long #define pb push_back #define pii pair<int,int> #define pll pair<ll,ll> #define pcc pair<char,char> #define vi vector <int> #define vl vector <ll> using namespace std; ll powmod(ll base,ll exponent,ll mod){ ll ans=1; if(base<0) base+=mod; while(exponent){ if(exponent&1)...