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
1338
D
Nested Rubber Bands
You have a tree of $n$ vertices. You are going to convert this tree into $n$ rubber bands on infinitely large plane. Conversion rule follows: - For every pair of vertices $a$ and $b$, rubber bands $a$ and $b$ should intersect if and only if there is an edge exists between $a$ and $b$ in the tree. - Shape of rubber ban...
Observation 1. You have to generate optimal sequence which is subsequence of path between some two vertices. Neighbors of vertices in optimal sequence will be used as nested rubber bands. This is an example of conversion. Red vertices are picked sequence, and blue vertices are neighbor of red vertices which are used as...
[ "constructive algorithms", "dfs and similar", "dp", "math", "trees" ]
2,700
null
1338
E
JYPnation
Due to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram. The new nation consists of $n$ cities and some roads between ...
The solution contains several tricky observations, but its not hard to prove each of them seperately, so I will mention only the key points of the solution and proof. Firstly, we should repeatedly remove points that have no in-degree. We can calculate their contribution easily. For a node $x$, define $in(x)$ to be the ...
[ "graphs" ]
3,500
null
1339
A
Filling Diamonds
You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $2$ coverings are different if some $2$ triangles are covered by the same diamond sha...
The key observation of this problem is, wherever you put vertical diamond at some point, all other places are uniquely placed by horizontal diamonds like picture below. There are $n$ places you can put vertical diamond, so answer is $n$ for each test case.
[ "brute force", "dp", "implementation", "math" ]
900
null
1339
B
Sorted Adjacent Differences
You have array of $n$ numbers $a_{1}, a_{2}, \ldots, a_{n}$. Rearrange these numbers to satisfy $|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$, where $|x|$ denotes absolute value of $x$. It's always possible to find such rearrangement. Note that all numbers in $a$ are not necessarily different...
Sort the list, and make an oscillation centered on middle element like picture below. In this way, you will always achieve to make $|a_{i} - a_{i+1}| \le |a_{i+1} - a_{i+2}|$ for all $i$. Time complexity is $O(n \log n)$.
[ "constructive algorithms", "sortings" ]
1,200
null
1340
A
Nastya and Strange Generator
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his...
Consider the initial moment of time. Note that the array is $r = [1, 2, \ldots, n]$, $count = [1, 1, \ldots, 1]$. So the generator will choose a random position from the entire array - let it be the position $i_1$. In the next step, $r = [1, 2, \ldots i_1 + 1, i_1 + 1, i + 2, \ldots, n]$, $count = [1, 1, \ldots, 0, 2, ...
[ "brute force", "data structures", "greedy", "implementation" ]
1,500
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> p(n); for (int& i : p) cin >> i; vector<int> pos(n); for (int i = 0; i < n; ++i) pos[--p[i]] = i; vector<bool> was(n); for (int i = 0; i < n; ++i) { if (was[i]) ...
1340
B
Nastya and Scoreboard
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He wa...
Let $dp[i][j] = true$, if at the suffix $i \ldots n$ you can turn on exactly $j$ sticks and get the correct sequence of digits and $false$ otherwise. It is easy to recalculate this dynamics: we will make transitions to all possible digits (the mask at position $i$ should be a submask of the digit). Asymptotic calculate...
[ "bitmasks", "dp", "graphs", "greedy" ]
1,700
/** * author: tourist * created: 23.04.2020 17:45:43 **/ #include <bits/stdc++.h> using namespace std; vector<string> digits = {"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"}; int main() { ios::sync_with_stdio(false); cin.tie(0); ...
1340
C
Nastya and Unexpected Guest
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place ...
Notice the fact: if we somehow came to safety island and time $i \bmod g$ ($\bmod$ - is a remainder after dividing $i$ by $g$), we don't need anymore to come to this island at time $j$ where $i<j$ and $i\bmod g = j\bmod g$, because this will form a cycle. So that we can rephrase our task like this: we have some vertice...
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
2,400
#include<bits/stdc++.h> using namespace std; using ll = long long int; vector<vector<int>> dist; vector<vector<bool>> was; int main() { int n, m; cin >> n >> m; vector<int> arr(m + 2); for (int i = 0; i < m; ++i) cin >> arr[i + 1]; m += 2; arr.back() = n; sort(arr.begin(), arr....
1340
D
Nastya and Time Machine
Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There ...
Lemma: The maximum time that Denis will visit will be at least $\max\limits_{v = 1}^{n} \deg v = T$ Proof: consider an arbitrary vertex $v$. We will visit her $\deg v - 1$ times when we will bypass all her neighbors and another $1$ when we return to her ancestor. But we can't go to vertex at 0 time. So, we need $\deg v...
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,600
#pragma GCC optimize("unroll-loops") #pragma GCC optimize("O3") #pragma optimize("SEX_ON_THE_BEACH") #include<bits/stdc++.h> using ll = long long int; using ull = unsigned long long int; using dd = double; using ldd = long double; namespace Hashes { const int mod197 = 1e9 + 7; const int mod199 = 1e9 + 9; ...
1340
F
Nastya and CBS
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it? A string $s$ is given. It consists of $k$ k...
We will call the string exactly the wrong bracket sequence if we go through it with a stack and it will not be of the form $close + open$, where $close$ is the sequence of closing brackets, and $open$ is opening. Claim: if $s = a + b$ and $a$ is exactly not CBS or $b$ is exactly not CBS, then $s$ is also exactly not CB...
[ "brute force", "data structures", "hashing" ]
3,300
#include <bits/stdc++.h> #define fi first #define se second #define ll long long using namespace std; mt19937 rnd(13'06'2019); const int N = 4e5 + 1; const int LN = 2e6 + 1; const int mod = 1e9 + 7; const long long div1 = 100'001; struct dek { int l, r, sz, key; long long hesh; }; int top = 0; dek m...
1341
A
Nastya and Rice
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped $n$ grains. Nastya read that each grain weighs some integer number of grams from $a - b$ to $a + b$, inclusive (numbers $a$ and $b$ are known), ...
We can get any weight of all grains from $n(a - b)$ to $n(a + b)$, so we need to check that the segments $[n(a - b); n(a + b)]$ and $[c - d; c + d]$ intersect.
[ "math" ]
900
#include <iostream> using namespace std; int main() { int q; cin >> q; while (q--) { int n, a, b, c, d; cin >> n >> a >> b >> c >> d; int L = n * (a - b), R = n * (a + b); if (R < c - d || c + d < L) cout << "No\n"; else cout << "Yes\n"; } }
1341
B
Nastya and Door
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $k$ ($k \ge 3$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains. Mountains are described by a sequence of h...
Let's make an array consisting of $0$ and $1$, such that it shows whether the position $i$ is a peak on the whole segment. To do this, we will go through the indices from $2$ to $n - 1$, and if the conditions $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$ are true, then we write $1$ in a new array at position $i$. After that,...
[ "greedy", "implementation" ]
1,300
#define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #include <iostream> #include <algorithm> #include <vector> #include <string> #include <set> #include <map> #include <unordered_map> #include <unordered_set> #include <fstream> #include <iomanip> #include <bitset> #include <random> #include <queue> #include <cs...
1342
A
Road To Zero
You are given two integers $x$ and $y$. You can perform two types of operations: - Pay $a$ dollars and increase or decrease any of these integers by $1$. For example, if $x = 0$ and $y = 7$ there are four possible outcomes after this operation: - $x = 0$, $y = 6$; - $x = 0$, $y = 8$; - $x = -1$, $y = 7$; - $x = 1$, $...
Let's presume that $x \ge y$. Then there are two cases in the problem: If $a + a \le b$ then we have to $x + y$ times perform the first operation. So the answer is $(x + y) \cdot a$; If $a + a > b$ then we have to $y$ times perform the second operation and pass the remaining distance by performing the first operation. ...
[ "greedy", "math" ]
1,000
for _ in range(int(input())): x, y = map(int, input().split()) a, b = map(int, input().split()) b = min(b, a + a) if x < y: x, y= y, x print(y * b + (x - y) * a)
1342
B
Binary Period
Let's say string $s$ has period $k$ if $s_i = s_{i + k}$ for all $i$ from $1$ to $|s| - k$ ($|s|$ means length of string $s$) and $k$ is the minimum positive integer with this property. Some examples of a period: for $s$="0101" the period is $k=2$, for $s$="0000" the period is $k=1$, for $s$="010" the period is $k=2$,...
Let's see how strings with periods $k = 1$ and $k = 2$ look. There are two types of strings with a period equal to $1$: 0000... and 1111.... And there are two types of strings with a period equal to $2$: 01010... and 10101.... It's easy to see if $t$ consists only of 0's (1's) then the string itself is an answer since ...
[ "constructive algorithms", "strings" ]
1,100
fun main() { val T = readLine()!!.toInt() for (tc in 1..T) { val t = readLine()!! val s = t.toCharArray().distinct().joinToString("").repeat(t.length) println(s) } }
1342
C
Yet Another Counting Problem
You are given two integers $a$ and $b$, and $q$ queries. The $i$-th query consists of two numbers $l_i$ and $r_i$, and the answer to it is the number of integers $x$ such that $l_i \le x \le r_i$, and $((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$. Calculate the answer for each query. Recall that $y \bmod z$ is the...
It's quite easy to see that $((ab + x) \bmod a) \bmod b = (x \bmod a) \bmod b$. What does it mean? The property given in the statement holds for $x$ if and only if it holds for $x \bmod ab$. It allows us to answer each testcase in $O(ab + q)$ as follows: for each number from $0$ to $ab - 1$, we may check the given prop...
[ "math", "number theory" ]
1,600
#include<bits/stdc++.h> using namespace std; const int N = 40043; int len; int p[N]; void build(int a, int b) { len = a * b; p[0] = 0; for(int i = 1; i <= len; i++) { p[i] = p[i - 1]; if((i % a) % b != (i % b) % a) p[i]++; } } long long query(long long l) { long long cnt = l / len; int rem = l % len;...
1342
D
Multiple Testcases
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem! Initially, each test in that problem is just an array. The maximum size of an array...
Let's estimate the smallest possible achievable answer. Let the number of the arrays of size greater than or equal to $i$ be $g_i$. The answer is maximum $\lceil \frac{g_i}{c_i} \rceil$ over all $i$ from $1$ to $k$. You can prove that you can't fit $g_i$ arrays in less than $\lceil \frac{g_i}{c_i} \rceil$ testcases wit...
[ "binary search", "constructive algorithms", "data structures", "greedy", "sortings", "two pointers" ]
1,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n, k; scanf("%d%d", &n, &k); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); vector<int> c(k + 1); forn(i, k) scanf("%d", &c[i + 1]); sort(a.begin(), a.end(), greater<int>()); int ans = 0; ...
1342
E
Placing Rooks
Calculate the number of ways to place $n$ rooks on $n \times n$ chessboard so that both following conditions are met: - each empty cell is under attack; - exactly $k$ pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. ...
If we want to place $n$ rooks on an $n \times n$ chessboard so all empty cells are under attack, then either each row or each column should contain at least one rook. Let's suppose that each row contains at least one rook, and multiply the answer by $2$ in the end. How to ensure that there are exactly $k$ pairs of rook...
[ "combinatorics", "fft", "math" ]
2,300
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 200043; int add(int x, int y) { return (x + y) % MOD; } int sub(int x, int y) { return add(x, MOD - y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y > 0) { if(y % ...
1342
F
Make It Ascending
You are given an array $a$ consisting of $n$ elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices $i$ and $j$ ($1 \le i, j \le n$; $i \ne j$), increase $a_j$ by $a_i$, and remove the $i$-th element from the array (so the indices of all elements to the right to...
Suppose we don't have any constraints on the order of elements, the resulting array just should not contain any duplicates. Let's build the result one element after another in ascending order, so each element we create is strictly greater than the previous. To create an element, just use some subset of elements and mer...
[ "bitmasks", "brute force", "dp" ]
3,000
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) typedef pair<int, int> pt; const int INF = 1e9; const int N = 15; int n; int a[N]; int sum[1 << N]; int dp[N + 1...
1343
A
Candies
Recently Vova found $n$ candy wrappers. He remembers that he bought $x$ candies during the first day, $2x$ candies during the second day, $4x$ candies during the third day, $\dots$, $2^{k-1} x$ candies during the $k$-th day. But there is an issue: Vova remembers neither $x$ nor $k$ but he is sure that $x$ and $k$ are p...
Notice that $\sum\limits_{i=0}^{k-1} 2^i = 2^k - 1$. Thus we can replace the initial equation with the following: $(2^k - 1) x = n$. So we can iterate over all possible $k$ in range $[2; 29]$ (because $2^{30} - 1 > 10^9$) and check if $n$ is divisible by $2^k-1$. If it is then we can print $x = \frac{n}{2^k-1}$. P.S. I...
[ "brute force", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; for (int pw = 2; pw < 30; ++pw) { int val = (1 << pw) - 1; if (n % val == 0) { cerr << val << e...
1343
B
Balanced Array
You are given a positive integer $n$, it is guaranteed that $n$ is even (i.e. divisible by $2$). You want to construct the array $a$ of length $n$ such that: - The first $\frac{n}{2}$ elements of $a$ are even (divisible by $2$); - the second $\frac{n}{2}$ elements of $a$ are odd (not divisible by $2$); - \textbf{all ...
Firstly, if $n$ is not divisible by $4$ then the answer is "NO" because the parities of halves won't match. Otherwise, the answer is always "YES". Let's construct it as follows: firstly, let's create the array $[2, 4, 6, \dots, n, 1, 3, 5, \dots, n - 1]$. This array is almost good except one thing: the sum in the right...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; n /= 2; if (n & 1) { cout << "NO" << endl; continue; } cout << "YES" << endl; for (int i = ...
1343
C
Alternating Subsequence
Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not...
Firstly, let's extract maximum by inclusion segments of the array that consists of the numbers with the same sign. For example, if the array is $[1, 1, 2, -1, -5, 2, 1, -3]$ then these segments are $[1, 1, 2]$, $[-1, -5]$, $[2, 1]$ and $[-3]$. We can do it with any "two pointers"-like algorithm. The number of these seg...
[ "dp", "greedy", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif auto sgn = [&](int x) { if (x > 0) return 1; else return -1; }; int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto &it ...
1343
D
Constant Palindrome Sum
You are given an array $a$ consisting of $n$ integers (it is guaranteed that $n$ is even, i.e. divisible by $2$). All $a_i$ does not exceed some integer $k$. Your task is to replace the \textbf{minimum} number of elements (replacement is the following operation: choose some index $i$ from $1$ to $n$ and replace $a_i$ ...
It is obvious that if we fix the value of $x$ then there are three cases for the pair of elements: We don't need to change anything in this pair; we can replace one element to fix this pair; we need to replace both elements to fix this pair. The first part can be calculated easily in $O(n+k)$, we just need to create th...
[ "brute force", "data structures", "greedy", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &it : a) cin >> it; vector<int> cnt(2 * k + 1); for (int i = 0;...
1343
E
Weights Distributing
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) $a$ to the vertex (d...
If we distribute costs optimally, then this pair of paths ($a \rightarrow b$ and $b \rightarrow c$) can look like just a straight path that doesn't visit the same vertex twice or like three straight paths with one intersection point $x$. The first case is basically a subcase of the second one (with the intersection poi...
[ "brute force", "graphs", "greedy", "shortest paths", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; vector<vector<int>> g; void bfs(int s, vector<int> &d) { d[s] = 0; queue<int> q; q.push(s); while (!q.empty()) { int v = q.front(); q.pop(); for (auto to : g[v]) { if (d[to] == INF) { d[to] = d[v] + 1; q.push(to); } } } } ...
1343
F
Restore the Permutation by Sorted Segments
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you. For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p...
Let's fix the first element and then try to restore permutation using this information. One interesting fact: if such permutation exists (with this first element) then it can be restored uniquely. Let's remove the first element from all segments containing it (we can use some logarithmic data structure for it). Then we...
[ "brute force", "constructive algorithms", "data structures", "greedy", "implementation" ]
2,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; vector<set<int>> segs; for (int i = 0; i < n - 1; ++i) { set<int> cur; int k; cin >> k; for...
1344
A
Hilbert's Hotel
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, \textbf{including zero and negative integers}. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert...
Suppose that $i+a_i\equiv j+a_j\pmod{n}$ for some $0\le i<j<n$. Then $i+a_i=j+a_j+kn$ for some integer $k$, so the guest in room $i$ is assigned the same room as guest $j+kn$. Similarly, suppose that two different guests $k$ and $m$ are assigned the same room. Then we have $i+a_i\equiv j+a_j\pmod{n}$ for $i=k\bmod n$ a...
[ "math", "number theory", "sortings" ]
1,600
null
1344
B
Monopole Magnets
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an $n\times m$ grid. Initially, you may place some north magnets and some south magnets into the cells. You are...
Suppose two cells $A$ and $B$ are colored black in the same row. Since there must be a south magnet in every row, there are segments of black cells from $A$ and $B$ to the cell with the south magnet. The same result holds for columns. Therefore, for a solution to exist, every row and every column has exactly one segmen...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,000
null
1344
C
Quantifier Question
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. \textbf{The set of real numbers includes zero and negatives.} There are two kinds of quantifiers: universal ($\forall$) and existential ($\exists$). You can read more about...
Build a directed graph of variables, where an edge $x_i\to x_j$ corresponds to an inequality $x_i<x_j.$ Say that two variables are comparable if there is a directed path from one variable to the other. Suppose $x_i$ and $x_j$ are comparable with $i<j$. Then $x_j$ cannot be universal since $x_i$ is determined before $x_...
[ "dfs and similar", "dp", "graphs", "math" ]
2,600
null
1344
D
Résumé Review
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly $n$ types of programming projects, and you ...
If we increment some $b_i$ to $x$, the value of $f$ changes by $\Delta_i (x):=\left[x(a_i-x^2)\right]-\left[(x-1)(a_i-(x-1)^2)\right]=a_i-3x^2+3x-1,$ which decreases for $x\ge 1.$ If we initially set all $b_i$ to $0$, then greedily incrementing the best index gives an optimal solution. Since $k$ is large, we cannot aff...
[ "binary search", "greedy", "math" ]
2,700
null
1344
E
Train Tracks
That's right. I'm a Purdue student, and I shamelessly wrote a problem about trains. There are $n$ stations and $m$ trains. The stations are connected by $n-1$ one-directional railroads that form a tree rooted at station $1$. All railroads are pointed in the direction from the root station $1$ to the leaves. A railroad...
First, observe that a train can never pass one that enters earlier. So let's consider the trains independently. For a train $i$, look at the path from $1$ to $s_i$. We may need to change the switches of several stations on this path. We must make each switch within a time interval $(L, R]$, where $L$ is the most recent...
[ "data structures", "trees" ]
3,100
null
1344
F
Piet's Palette
Piet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color! \begin{center} A ...
Equate an empty cell with the color white, and let's represent the colors as 0/1 vectors: $W=\begin{bmatrix}0\\0\end{bmatrix},\ R=\begin{bmatrix}1\\0\end{bmatrix},\ Y=\begin{bmatrix}0\\1\end{bmatrix},\ B=\begin{bmatrix}1\\1\end{bmatrix}.$ Under this representation, mixing becomes addition $\pmod{2}$. And the operations...
[ "matrices" ]
3,200
null
1345
A
Puzzle Pieces
You are given a special jigsaw puzzle consisting of $n\cdot m$ identical pieces. Every piece has three tabs and one blank, as pictured below. The jigsaw puzzle is considered solved if the following conditions hold: - The pieces are arranged into a grid with $n$ rows and $m$ columns. - For any two pieces that share an...
If $n=1$ or $m=1$, then we can chain the pieces together to form a solution. If $n=m=2$, we can make the following solution: Any other potential solution would contain a $2\times 3$ or a $3\times 2$ solution, which we can show is impossible. A $2\times 3$ grid has $7$ shared edges between the pieces, and each shared ed...
[ "math" ]
800
null
1345
B
Card Constructions
A card pyramid of height $1$ is constructed by resting two cards against each other. For $h>1$, a card pyramid of height $h$ is constructed by placing a card pyramid of height $h-1$ onto a base. A base consists of $h$ pyramids of height $1$, and $h-1$ cards on top. For example, card pyramids of heights $1$, $2$, and $3...
Let's count the number of cards in a pyramid of height $h$. There are $2(1+2+3+\cdots+h)$ cards standing up, and there are $0+1+2+\cdots+(h-1)$ horizontal cards. So, there are $2\frac{h(h+1)}{2}+\frac{(h-1)h}{2}=\frac{3}{2}h^2+\frac12 h$ cards total. Using this formula, we can quickly find the largest height $h$ that u...
[ "binary search", "brute force", "dp", "math" ]
1,100
null
1348
A
Phoenix and Balance
Phoenix has $n$ coins with weights $2^1, 2^2, \dots, 2^n$. He knows that $n$ is even. He wants to split the coins into two piles such that each pile has exactly $\frac{n}{2}$ coins and the difference of weights between the two piles is \textbf{minimized}. Formally, let $a$ denote the sum of weights in the first pile, ...
We observe that the coin with the weight $2^n$ is greater than the sum of all the other weights combined. This is true because $\sum\limits_{i = 1}^{n-1}2^i=2^n-2$. Therefore, the pile that has the heaviest coin will always weigh more. To minimize the weight differences, we put the $n/2-1$ lightest coins into the pile ...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve(){ int N; cin>>N; //note: 1<<X means 2^X //we put largest coin in first pile int sum1=(1<<N), sum2=0; //we put n/2-1 smallest coins in first pile for (int i=1;i<N/2;i++) sum1+=(1<<i); //we put remaining n/2 coins in second pile for (int i=N...
1348
B
Phoenix and Beauty
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $k$ have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array $a$ of length $n$. He wants to insert some number of integers, possibly zero, into his array such that it becomes be...
For an array to be beautiful for some $k$, the array must be periodic with period $k$. If there exists more than $k$ distinct numbers in the array $a$, there is no answer and we print -1 (because the array cannot be periodic with period $k$). Otherwise, we propose the following construction. Consider a list of all the ...
[ "constructive algorithms", "data structures", "greedy", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve(){ int N,K; cin>>N>>K; set<int>s; for (int i=0;i<N;i++){ int a; cin>>a; s.insert(a); } //if more than K distinct numbers, print -1 if (s.size()>K){ cout<<-1<<endl; return; } cout<<N*K<<endl; for (int i=0;i<N;i++){ //pr...
1348
C
Phoenix and Distribution
Phoenix has a string $s$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $k$ \textbf{non-empty} strings $a_1, a_2, \dots, a_k$ such that every letter of $s$ goes to exactly one of the strings $a_i$. The strings $a_i$ \textbf{do not} need to be substrings of $s$. Phoenix ...
We first try to assign one letter to each string $a_i$. Let's denote the smallest letter in $s$ as $c$. If there exists at least $k$ occurrences of $c$ in $s$, we will assign $c$ as the first letter of each string $a_i$. Otherwise, the minimal solution is the $k$th smallest letter in $s$. For example, if $s=$aabbb and ...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve(){ int n,k; cin>>n>>k; string s; cin>>s; sort(s.begin(),s.end()); //if smallest k letters are not all the same, answer is kth smallest letter if (s[0]!=s[k-1]){ cout<<s[k-1]<<endl; return; } cout<<s[0]; //if remaining letters aren't t...
1348
D
Phoenix and Science
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria. Initially, on day $1$, there is one bacterium with mass $1$. Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $m$ splits, it becomes two bacteria of mass $\frac{m}{2}$ each. F...
There exists many constructive solutions, here is one I think is very elegant. We will try to approach the problem by considering how much the total mass increases every night. If there are $x$ bacteria some day before the splitting, that night can have a mass increase between $x$ and $2x$ inclusive (depending on how m...
[ "binary search", "constructive algorithms", "greedy", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; void solve(){ vector<int>inc; int N; cin>>N; //construct sequence 1, 2, 4, ... while sum <= N for (int i=1;i<=N;i*=2){ inc.push_back(i); N-=i; } //if sum is not N, we insert and sort if (N>0){ inc.push_back(N); sort(inc.begin(),inc.end())...
1348
E
Phoenix and Berries
Phoenix is picking berries in his backyard. There are $n$ shrubs, and each shrub has $a_i$ red berries and $b_i$ blue berries. Each basket can contain $k$ berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berr...
Solution 1: There is no obvious greedy solution, so we will try dynamic programming. Let $dp[i][j]$ be a boolean array that denotes whether we can have $j$ extra red berries after considering the first $i$ shrubs. A berry is extra if it is not placed into a full basket (of any kind). Note that if we know that there are...
[ "brute force", "dp", "greedy", "math" ]
2,400
//Solution 1 #include <bits/stdc++.h> using namespace std; int N,K; int a[505],b[505]; bool dp[505][505]; //number of shrubs considered, "extra" red berries int main(){ cin>>N>>K; long long totA=0,totB=0; for (int i=1;i<=N;i++){ cin>>a[i]>>b[i]; totA+=a[i]; totB+=b[i]; } dp[0][0]=true; for (i...
1348
F
Phoenix and Memory
Phoenix is trying to take a photo of his $n$ friends with labels $1, 2, \dots, n$ who are lined up in a row in a special order. But before he can take the photo, his friends get distracted by a duck and mess up their order. Now, Phoenix must restore the order but he doesn't remember completely! He only remembers that ...
There are many many many solutions to this problem (which is cool!). I describe two of them below. Both solutions first find an arbitrary valid ordering. This can be done in $O(n\log{n})$ with a greedy algorithm. We can sort the intervals $(a_i,b_i)$ and sweep from left to right. To see which position that we can assig...
[ "data structures", "dfs and similar", "graphs", "greedy" ]
2,600
#include <bits/stdc++.h> using namespace std; int N; int a[200005],b[200005]; int label[200005]; //the label of the person at i-th position in our perfect matching int label2[200005]; //which position the i-th person is at void perfectMatch(){ //finds a perfect matching deque<pair<pair<int,int>,int>>v; for (int i...
1349
A
Orac and LCM
For the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow: - $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$. - $\textrm{lcm}(s)$ is the minimum positive integer $x$, that ...
In this tutorial $p$ stands for a prime, $v$ stands for the maximum of $a_i$ and $ans$ stands for the answer. Observation. $p^k\ \mid\ ans$ if and only if there are at least $n-1$ integers in $a$ that $\mathrm{s.t. }\ p^k\mid\ a_i$. Proof. if there are at most $n-2$ integers in $a$ that $\mathrm{s.t. }\ p^k\mid\ a_i$, ...
[ "data structures", "math", "number theory" ]
1,600
#include <iostream> #include <cstdio> using namespace std; typedef long long ll; const int maxn=100005; int n; ll a[maxn]; ll pre[maxn],suf[maxn]; ll gcd(ll x, ll y) { if(y==0) return x; else return gcd(y,x%y); } ll ga,ans; int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lld",&a[i]); pre[1]=a[1];...
1349
B
Orac and Medians
Slime has a sequence of positive integers $a_1, a_2, \ldots, a_n$. In one operation Orac can choose an arbitrary subsegment $[l \ldots r]$ of this sequence and replace all values $a_l, a_{l + 1}, \ldots, a_r$ to the value of median of $\{a_l, a_{l + 1}, \ldots, a_r\}$. In this problem, for the integer multiset $s$, t...
Let $B_i=\left\{\begin{aligned} 0,A_i<k\\1,A_i=k\\2,A_i>k\end{aligned} \right.$,then just consider whether it can be done to make all elements in $B$ become $1$ in a finite number of operations. It can be proved that a solution exists if and only if $\exists 1\le i\le n,\mathrm{s.t.}B_i=1$ and $\exists 1\le i<j\le n,\m...
[ "constructive algorithms", "greedy", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define x first #define y second #define mp make_pair #define pb push_back template <typename TYPE> inline void chkmax(TYPE &x,TYPE y){x<y?x=y:TYPE();} template <typename TYPE> inline void chkm...
1349
C
Orac and Game of Life
\textbf{Please notice the unusual memory limit of this problem.} Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white. For each iteration of the game (the initial iteration is $0$...
A cell $(i,j)$ is said to be good if and only if there is a cell $(i',j')$ adjacent to $(i,j)$ which has the same color to $(i,j)$ . If a cell $(i,j)$ is not good, it is said to be bad. Therefore, the color of a cell changes after a turn if and only if the cell is good. According to the definition, any cell never chang...
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
2,000
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #define pii pair<int,int> #define mp make_pair #define fi first #define se second using namespace std; typedef long long ll; const int MAXN = 1005; inline ll readint() { ll res = 0, f = 1; char c = 0; while(!isdigit(c))...
1349
D
Slime and Biscuits
Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a ...
Let $E_x$ be the sum of probability times time when the game end up with all biscuits are owned by the x-th person (At here, the sum of probability is not 1, though the sum of probability in all $E_x$ is 1). So the answer is $\sum\limits_{i=1}^nE_i$ Let $E'_x$ be the expectation of time when the game only ends when the...
[ "math", "probabilities" ]
3,200
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;} template <typena...
1349
E
Slime and Hats
Slime and Orac are holding a turn-based game. In a big room, there are $n$ players sitting on the chairs, looking forward to a column and each of them is given a number: player $1$ sits in the front of the column, player $2$ sits directly behind him; player $3$ sits directly behind player $2$, and so on; player $n$ sit...
First, let's renumber the players for convenience. Number the player at the front as $n$ ,the player sitting behind him as $n-1$ , and so on. Let $c_i$ be the color of player $i$'s hat. Consider how to calculate ${t_i}$ if we have already known $c_1,c_2,\dots,c_n$. If $c_1=c_2=\dots=c_n=0$, then $t_1=t_2=\dots=t_n=1$. ...
[ "constructive algorithms", "dp", "greedy" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,ll> pii; #define x first #define y second #define pb push_back const int MAXN=200005; int n,m,cnt; pii a[MAXN]; bool avis[MAXN]; struct Range { int l,r,type; ll val; Range(){} Range(int l,int r,int type,ll val):l(l),r(r),type(type...
1349
F1
Slime and Sequences (Easy Version)
\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.} Slime is interested in sequences. He defined \textbf{good} positive integer sequences $p$ of length $n$ as follows: - For each $k>1$ that presents i...
First we can make a bijection between all the good sequences and permutations. Let a permutation of length $n$ be $a_1,a_2,\cdots , a_n$ , and we fill '>' or '<' sign between each $a_i$ and $a_{i+1}$ , so the value of $p_{a_i}$ is the number of '<' sign between $a_1,a_2,\cdots, a_i$ plus one, it's easy to proof that th...
[ "dp", "fft", "math" ]
3,100
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;} template <typena...
1349
F2
Slime and Sequences (Hard Version)
\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.} Slime is interested in sequences. He defined \textbf{good} positive integer sequences $p$ of length $n$ as follows: - For each $k>1$ that presents i...
Now we consider how to get these values in less than $O(n^2)$ time. $\sum\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}=\sum\limits_{x=y+1}^n[z^x](e^z-1)^{x-y}$ $=[z^y]\sum\limits_{x=y+1}^n(\frac{e^z-1}z)^{x-y}=[z^y]\sum\limits_{x=1}^{n-y}(\frac{e^z-1}z)^x$ Let $F=\frac{e^z-1}z$ , so now we just want to find $[z^i]\sum\li...
[ "dp", "fft", "math" ]
3,500
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<ll> vi; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:f...
1350
A
Orac and Factors
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers $a$ and $b$, $a$ is a divisor of $b$ if and only if there exists an integer $c$, such that $a\cdot c=b$. For $n \ge 2$, we will denote as $f(n)$ the smallest positive divisor of $n$, except $1$. For example,...
If we simulate the whole process we will get TLE because $k$ is too large. So we need some trivial observations: If $n$ is even, then for each operation $n$ will be added by $2$ and keep being even. If $n$ is odd, then for the first time $n$ will be added by an odd number and then become even. So it's easy to see that ...
[ "math" ]
900
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; int main() { int T; cin >> T; while(T--) { int n,k; cin >> n >> k; if(n%2==0) { cout << n+2*k << endl; continue; } int p = 0; for(int i = n; i>=2; i--) if(n%i==0) p =...
1350
B
Orac and Models
There are $n$ models in the shop numbered from $1$ to $n$, with sizes $s_1, s_2, \ldots, s_n$. Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes). Orac thinks that the obtained arrangement is \textbf{beatiful}, if for any two adjacent models with in...
Considering DP, we can design DP statuses as follow: $f_i$ stands for the length of the longest beautiful sequence end up with index $i$. We can find the transformation easily: $f_i = \max\limits_{j\mid i, s_j<s_i} \{f_j + 1\}$ Then, the length of answer sequence is the maximum value among $f_1,f_2,\cdots,f_n$. About t...
[ "dp", "math", "number theory" ]
1,400
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 500005; inline int readint() { int res = 0; char c = 0; while(!isdigit(c)) c = getchar(); while(isdigit(c)) res = res*10+c-'0', c = getchar(); return res; } int n,a[MAXN],f[M...
1352
A
Sum of Round Numbers
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $1$ to $9$ (inclusive) are round. For example, the following numbers are ...
Firstly, we need to understand the minimum amount of round numbers we need to represent $n$. It equals the number of non-zero digits in $n$. Why? Because we can "remove" exactly one non-zero digit in $n$ using exactly one round number (so we need at most this amount of round numbers) and, on the other hand, the sum of ...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> ans; int power = 1; while (n > 0) { if (n % 10 > 0) { ans.push_back((n % 10) * power); } n /= 10; power *= 10; } cout << ans.size() << endl; for (auto number : ans)...
1352
B
Same Parity Summands
You are given two positive integers $n$ ($1 \le n \le 10^9$) and $k$ ($1 \le k \le 100$). Represent the number $n$ as the sum of $k$ positive integers of the same parity (have the same remainder when divided by $2$). In other words, find $a_1, a_2, \ldots, a_k$ such that all $a_i>0$, $n = a_1 + a_2 + \ldots + a_k$ and...
Consider two cases: when we choose all odd numbers and all even numbers. In both cases let's try to maximize the maximum. So, if we choose odd numbers, let's try to take $k-1$ ones and the remainder $n-(k-1)$. But we need to sure that $n-k+1$ is greater than zero and odd. And in case of even numbers, let's try to take ...
[ "constructive algorithms", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int n1 = n - (k - 1); if (n1 > 0 && n1 % 2 == 1) { cout << "YES" << endl; for (int i = 0; i < k - 1; ++i) cout << "1 "; cout << n1 << endl; continue; } int n2 = n - 2 * (k - 1)...
1352
C
K-th Not Divisible by n
You are given two positive integers $n$ and $k$. Print the $k$-th positive integer that is not divisible by $n$. For example, if $n=3$, and $k=7$, then all numbers that are not divisible by $3$ are: $1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$. The $7$-th number among them is $10$.
Suppose the answer is just $k$-th positive integer which we should "shift right" by some number. Each multiplier of $n$ shifts our answer by $1$. The number of such multipliers is $need = \lfloor\frac{k-1}{n-1}\rfloor$, where $\lfloor \frac{x}{y} \rfloor$ is $x$ divided by $y$ rounded down. So the final answer is $k + ...
[ "binary search", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int need = (k - 1) / (n - 1); cout << k + need << endl; } }
1352
D
Alice, Bob and Candies
There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy \textbf{from left to right}, and Bob — \textbf{from right to left}. The game ends if all the candies are ea...
This is just an implementation problem and it can be solved in $O(n)$ time but we didn't ask for such solutions so you could solve it in $O(n^2)$ or maybe even in $O(n^2 log n)$. I'll describe $O(n)$ solution anyway. Firstly, we need to maintain several variables: $cnt$ (initially $0$, the number of moves passed), $l$ ...
[ "implementation" ]
1,300
// Author: Ivan Kazmenko (gassa@mail.ru) import std.algorithm; import std.conv; import std.range; import std.stdio; import std.string; void main () { auto tests = readln.strip.to !(int); foreach (test; 0..tests) { auto n = readln.strip.to !(int); auto a = readln.splitter.map !(to !(int)).array; int [2] total;...
1352
E
Special Elements
Pay attention to the non-standard memory limit in this problem. In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut...
The intended solution for this problem uses $O(n^2)$ time and $O(n)$ memory. Firstly, let's calculate $cnt_i$ for each $i$ from $1$ to $n$, where $cnt_i$ is the number of occurrences of $i$ in $a$. This part can be done in $O(n)$. Then let's iterate over all segments of $a$ of length at least $2$ maintaining the sum of...
[ "brute force", "implementation", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); vector<int> cnt(n + 1); int ans = 0; for (auto &it : a) { cin >> it; ++cnt[it]; } for (int l = 0; l < n; ++l) { int sum = 0; for (int r = l; r < n; ++r) { sum...
1352
F
Binary String Reconstruction
For some binary string $s$ (i.e. each character $s_i$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $2$ were written. For each pair (substring of length $2$), the number of '1' (ones) in it was calculated. You are given three numbers: - $n...
Consider case $n_1 = 0$ separately and print the sting of $n_0 + 1$ zeros or $n_2 + 1$ ones correspondingly. Now our string has at least one pair "10" or "01". Let's form the pattern "101010 ... 10" of length $n_1 + 1$. So, all substrings with the sum $1$ are satisfied. Now let's insert $n_0$ zeros before the first zer...
[ "constructive algorithms", "dfs and similar", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n0, n1, n2; cin >> n0 >> n1 >> n2; if (n1 == 0) { if (n0 != 0) { cout << string(n0 + 1, '0') << endl; } else { cout << string(n2 + 1, '1') << endl; } continue; } string ans; for (int i = 0...
1352
G
Special Permutation
A permutation of length $n$ is an array $p=[p_1,p_2,\dots,p_n]$, which contains every integer from $1$ to $n$ (inclusive) and, moreover, each number appears exactly once. For example, $p=[3,1,4,2,5]$ is a permutation of length $5$. For a given number $n$ ($n \ge 2$), find a permutation $p$ in which absolute difference...
If $n < 4$ then there is no answer. You can do some handwork to be sure. Otherwise, the answer exists and there is one simple way to construct it: firstly, let's put all odd integers into the answer in decreasing order, then put $4$, $2$, and all other even numbers in increasing order. To test that it always works, you...
[ "constructive algorithms" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; if (n < 4) { cout << -1 << endl; continue; } for (int i = n; i >= 1; --i) { if (i & 1) cout << i << " "; } cout << 4 << " " << 2 << " "; for (int i = 6; i <= n; i += 2) { cout << i...
1353
A
Most Unstable Array
You are given two integers $n$ and $m$. You have to construct the array $a$ of length $n$ consisting of \textbf{non-negative integers} (i.e. integers greater than or equal to zero) such that the sum of elements of this array is \textbf{exactly} $m$ and the value $\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$ is the maximum ...
If $n=1$ then the answer is $0$. Otherwise, the best way is to construct the array $[0, m, 0, \dots, 0]$. For $n=2$ we can't reach answer more than $m$ and for $n > 2$ we can't reach the answer more than $2m$ because each unit can't be used more than twice. So the answer can be represented as $min(2, n - 1) \cdot m$.
[ "constructive algorithms", "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; cin >> n >> m; cout << min(2, n - 1) * m << endl; } return 0; }
1353
B
Two Arrays And Swaps
You are given two arrays $a$ and $b$ both consisting of $n$ positive (greater than zero) integers. You are also given an integer $k$. In one move, you can choose two indices $i$ and $j$ ($1 \le i, j \le n$) and swap $a_i$ and $b_j$ (i.e. $a_i$ becomes $b_j$ and vice versa). Note that $i$ and $j$ can be equal or differ...
Each move we can choose the minimum element in $a$, the maximum element in $b$ and swap them (if the minimum in $a$ is less than maximum in $b$). If we repeat this operation $k$ times, we get the answer. This can be done in $O(n^3)$, $O(n^2)$ but authors solution is $O(n \log n)$.
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &it : a) cin >> it; vector<int> b(n); for (auto &it : b) cin >>...
1353
C
Board Moves
You are given a board of size $n \times n$, where $n$ is \textbf{odd} (not divisible by $2$). Initially, each cell of the board contains one figure. In one move, you can select \textbf{exactly one figure} presented in some cell and move it to one of the cells \textbf{sharing a side or a corner with the current cell}, ...
It is intuitive (and provable) that the best strategy is to move each figure to the center cell $(\frac{n+1}{2}, \frac{n+1}{2})$. Now, with some paperwork or easy observations, we can notice that we have exactly $8$ cells with the shortest distance $1$, $16$ cells with the shortest distance $2$, $24$ cells with the sho...
[ "math" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; long long ans = 0; for (int i = 1; i <= n / 2; ++i) { ans += i * 1ll * i; } cout << ans * 8 << e...
1353
D
Constructing the Array
You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears: - Choose the maximum by length subarray (\textbf{continuous subsegment}) consisting \textbf{only} of zeros, among all such segments choose the \...
This is just an implementation problem. We can use some kind of heap or ordered set to store all segments we need in order we need. To solve this problem on C++ with std::set, we can just rewrite the comparator for std::set like this: And then just write the std::set like this: Now the minimum element of the set will b...
[ "constructive algorithms", "data structures", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; struct cmp { bool operator() (const pair<int, int> &a, const pair<int, int> &b) const { int lena = a.second - a.first + 1; int lenb = b.second - b.first + 1; if (lena == lenb) return a.first < b.first; return lena > lenb; } }; int main() { #ifdef _DEBUG freope...
1353
E
K-periodic Garland
You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$. In one move, you can choose \text...
Let $t_i$ be the string containing all characters of $s$ that have indices $i, i + k, i + 2k$ and so on (i.e. all such positions that have the remainder $i$ modulo $k$). Suppose we choose that all turned on lamps will have remainder $i$ modulo $k$. Then we need to remove all ones at the positions that do not belong to ...
[ "brute force", "dp", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif auto solve = [](const string &s) { int n = s.size(); int all = count(s.begin(), s.end(), '1'); int ans = all; vector<int> res(n); int pref = 0; for (...
1353
F
Decreasing Heights
You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size $n \times m$, where the height of the cell $(i, j)$ is $a_{i, j}$. You are in the cell $(1, 1)$ right now and want to get in the cell $(n, m)$. You can move only down (from the cell $(i...
Firstly, consider the field in $0$-indexation. Suppose that the cell $(0, 0)$ has some fixed height. Let it be $b_{0, 0}$. Then we can determine what should be the height of the cell $(i, j)$ as $b_{i, j} = b_{0, 0} + i + j$. In fact, it does not matter which way we choose, we actually need only the number of moves to ...
[ "brute force", "dp" ]
2,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) const long long INF64 = 1e18; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<vector...
1354
A
Alarm Clock
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $a$ minutes to feel refreshed. \textbf{Polycarp can only wake up by hearing the sound of his alarm.} So he has just fallen asleep and his first alarm goes off in $b$ minutes. Every time Polycarp wakes up, he decides if he w...
Let's handle some cases. Firstly, if $b \ge a$ then Polycarp wakes up rested enough immediately, so $b$ is the answer. Otherwise, what does Polycarp do? He sets alarm to go off in $c$ minutes and falls asleep in $d$ minutes. Thus, he spends $c-d$ minutes sleeping. Notice that if $c-d$ is non-positive, then Polycarp alw...
[ "math" ]
900
t = int(input()) for _ in range(t): a, b, c, d = map(int, input().split()) if b >= a: print(b) continue if c <= d: print(-1) continue a -= b dif = c - d print(b + (a + dif - 1) // dif * c)
1354
B
Ternary String
You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once. A contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) c...
There are multiple solutions involving advanced methods such as binary search or two pointers, but I'll try to describe a simpler one. The main idea of my solution is that the answer should look like abb...bbbbbc: one character of type $a$, a block of characters of type $b$, and one character of type $c$. If we find al...
[ "binary search", "dp", "implementation", "two pointers" ]
1,200
#include<bits/stdc++.h> using namespace std; char buf[200043]; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { scanf("%s", buf); string s = buf; int ans = int(1e9); int n = s.size(); vector<pair<char, int> > c; for(auto x : s) { if(c.empty() || c.back().first != x) c.push_b...
1354
C1
Simple Polygon Embedding
\textbf{The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.} You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$...
It's not hard to come up with a solution if you just imagine how $2n$-gon looks when $n$ is even. The solution is to rotate $2n$-gon in such way that several its sides are parallel to sides of the square. And the answer is equal to the distance from center to any side multiplied by two, or: $ans = \frac{1}{\tan{\frac{\...
[ "binary search", "geometry", "math", "ternary search" ]
1,400
null
1354
C2
Not So Simple Polygon Embedding
\textbf{The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.} You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$...
At first, lets place $2n$-gon in such way that the lowest side of $2n$-gon is horizontal. Now we can, without loss of generality, think that the square has horizontal and vertical sides and we just rotate $2n$-gon around its center. If we rotate the $2n$-gon at angle $\frac{\pi}{n}$ then it will move on itself. Moreove...
[ "binary search", "brute force", "geometry", "math" ]
2,000
import kotlin.math.* fun main() { val PI = acos(-1.0) val T = readLine()!!.toInt() for (tc in 1..T) { val n = readLine()!!.toInt() var ans : Double if (n % 2 == 0) { ans = 1.0 / tan(PI / (2 * n)) } else { ans = cos(PI / (4 * n)) / sin(PI / (2 * n)) ...
1354
D
Multiset
\textbf{Note that the memory limit is unusual.} You are given a multiset consisting of $n$ integers. You have to process queries of two types: - add integer $k$ into the multiset; - find the $k$-th order statistics in the multiset and remove it. $k$-th order statistics in the multiset is the $k$-th element in the so...
First solution: write some data structure that would simulate the operations as they are given, for example, a segment tree or a Fenwick tree. Probably will require optimization since the limits are strict. Second solution: notice that we have to find only one number belonging to the multiset. For example, let's find t...
[ "binary search", "data structures" ]
1,900
#include<bits/stdc++.h> using namespace std; int n, q; vector<int> a, k; int count_le(int x) { int cnt = 0; for(auto y : a) if(y <= x) cnt++; for(auto y : k) { if(y > 0 && y <= x) cnt++; if(y < 0 && abs(y) <= cnt) cnt--; } return cnt; } int main() { scanf("%d %d", &n, &q); a.resize(n); k.res...
1354
E
Graph Coloring
You are given an undirected graph without self-loops or multiple edges which consists of $n$ vertices and $m$ edges. Also you are given three integers $n_1$, $n_2$ and $n_3$. Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: - Each vertex should be labeled by exactly one number 1, 2 or ...
Let's rephrase the fifth condition. Each edge should connect two vertices with the numbers of different parity (either $1$ to $2$ or $3$ to $2$). So the graph should actually be bipartite and the first partition should have only the odd numbers ($1$ or $3$) and the second partition should have only the even numbers (on...
[ "dfs and similar", "dp", "graphs" ]
2,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define all(a) a.begin(), a.end() #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, l, r) for(int i = int(l); i < int(r); i+...
1354
F
Summoning Minions
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon $n$ different minions. The initial power level of the $i$-th minion is $a_i$, and when it is summoned, all previously summoned minions' power levels are increased by $b_i$. The m...
First of all, let's try to find the best strategy to play minions. All minions should be summoned (if someone is not summoned, summoning and deleting it won't make the answer worse), the resulting number of minions should be exactly $k$ (if it is less, then we didn't need to delete the last deleted minion). Furthermore...
[ "constructive algorithms", "dp", "flows", "graph matchings", "greedy", "sortings" ]
2,500
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define all(a) a.begin(), a.end() #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, l, r) for(int i = int(l); i < int(r); ...
1354
G
Find a Gift
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages. There are $n$ gift boxes in a row, numbered from $1$ to $n$ from left to right. It's known that exactly $k$ of them contain valuable gifts...
The solution consists of several steps. The first step. Let's find out "does the first box contain stone or valuable gift" using random. Let's make $30$ queries to compare the weight of the first box with the weight of another random box. If the first box is lighter than we found an answer, otherwise the probability of...
[ "binary search", "interactive", "probabilities" ]
2,600
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int MAG = 30; int lst; int n, k; inline bool read() { if(!(cin >> n >> k)) return false;...
1355
A
Sequence with Digits
Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$ Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes. Your task is calculate $a_{K}$ for given $a_{1}$ and $K$...
Let's calculate the sequence for fixed $a_{1} = 1$: $1, 2, 6, 42, 50, 50, 50, \ldots$ We got lucky and the minimal digit has become 0, after that the element has stopped changing because we always add 0. Actually it is not luck and that will always happen. Note that we add no more than $9 \cdot 9 = 81$ every time, so t...
[ "brute force", "implementation", "math" ]
1,200
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> ...
1355
B
Young Explorers
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
Let's sort all the explorers by non-decreasing inexperience. Suppose we have formed some group, how can we check is this group is valid? Inexperience of all the explorers in the group should be not greater than the group size. But we have sorted all the explorers, so the last explorer from the group has the largest ine...
[ "dp", "greedy", "sortings" ]
1,200
#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 i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); int ans = 0, cur = 0; for ...
1355
C
Count Triangles
Like any unknown mathematician, Yuri has favourite numbers: $A$, $B$, $C$, and $D$, where $A \leq B \leq C \leq D$. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides $x$, $y$, and $z$ exist, such that $A \leq x \leq B \leq y \leq C \leq z \leq D$ holds? Yuri is prepari...
Since $x \le y \le z$ to be a non-degenerate triangle for given triple it is necessary and sufficient to satisfy $z < x + y$. Let's calculate for all $s = x + y$ how many ways there are to choose $(x, y)$. To do that we will try all $x$ and add 1 on segment $[x + B; x + C]$ offline using prefix sums. Let's calculate pr...
[ "binary search", "implementation", "math", "two pointers" ]
1,800
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> ...
1355
D
Game With Array
Petya and Vasya are competing with each other in a new interesting game as they always do. At the beginning of the game Petya has to come up with an array of $N$ positive integers. Sum of all elements in his array should be equal to $S$. Then Petya has to select an integer $K$ such that $0 \leq K \leq S$. In order to...
For $S \ge 2N$ Petya wins: let's take array $[2, 2, \ldots, 2, S - 2(N - 1)]$ and $K = 1$. All the elements are strictly greater than 1, so there are no segment with sum 1 or $S - 1$. Let's prove that for $S < 2N$ Petya will lose. Suppose it is not true and there exist an array and $K > 0$ (it is obvious that $K = 0$ i...
[ "constructive algorithms", "math" ]
1,400
#include <iostream> using namespace std; int main() { int n, s; cin >> n >> s; if (2 * n <= s) { cout << "YES\n"; for (int i = 0; i < n - 1; i++) { cout << 2 << ' '; s -= 2; } cout << s << '\n' << 1; } else { cout << "NO"; } return 0; }
1355
E
Restorer Distance
You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights. You are allowed the following operations: - put a brick on top of on...
First of all let's do $M = \min(M, A + R)$ - this is true since we can emulate moving by adding+removing. After that it is never profitable to add and remove in one solution, since we can always move instead. Suppose we have fixed $H$ - the resulting height for all pillars. How can we calculate the minimal cost for giv...
[ "binary search", "greedy", "math", "sortings", "ternary search" ]
2,100
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> ...
1355
F
Guess Divisors Count
This is an interactive problem. We have hidden an integer $1 \le X \le 10^{9}$. You \textbf{don't have to} guess this number. You have to \textbf{find the number of divisors} of this number, and you \textbf{don't even have to find the exact number}: your answer will be considered correct if its absolute error is not g...
If $X = p_{1}^{\alpha_{1}} \cdot p_{2}^{\alpha_{2}} \cdot \ldots \cdot p_{k}^{\alpha_{k}}$ then $d(X) = (\alpha_{1} + 1) \cdot (\alpha_{2} + 1) \cdot \ldots \cdot (\alpha_{k} + 1)$. If $X$ has prime $p$ in power $\alpha$ and $Q$ has $p$ in power $\beta$ then $gcd(X, Q)$ will have $p$ in power $\gamma = \min (\alpha, \b...
[ "constructive algorithms", "interactive", "number theory" ]
2,600
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> ...
1358
A
Park Lighting
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with $n$ rows and $m$ columns, where the cells of...
Note that if at least one of the sides is even, the square can be divided into pairs of neighbors and the answer is $\frac{nm}{2}$. If both sides are odd, we can first light up a $(n - 1) \times m$ part of the park. Then we'll still have the part $m \times 1$. We can light it up with $\frac{m + 1}{2}$ lanterns. Then th...
[ "greedy", "math" ]
800
#include <iostream> using namespace std; int main() { int t, n, m; cin >> t; while (t--) { cin >> n >> m; cout << (n * m + 1) / 2 << '\n'; } }
1358
B
Maria Breaks the Self-isolation
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has $n$ friends who are also grannies (Maria is not included in this number). The $i$-th granny is ready to attend the ceremony, provided that at the time of her appearance ...
Let $x$ be the maximum number of grannies that can go out to the yard. Then if Maria Ivanovna calls them all at the same time, then everyone will see $x$ grannies. Since $x$ is the maximum answer, then each granny of them satisfy $a_i \le x$ (otherwise there's no way for these grannies to gather in the yard), that is, ...
[ "greedy", "sortings" ]
1,000
#include <iostream> #include <vector> #include <algorithm> using namespace std; void solve() { int n; cin >> n; vector<int> arr(n); for (int &el : arr) cin >> el; sort(arr.begin(), arr.end()); for (int i = n - 1; i >= 0; i--) { if (arr[i] <= i + 1) { cout << i + 2 <...
1358
C
Celex Update
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: The cell with coordinates $(x, y)$ is at the intersection of $x$-th row and ...
Let's look at the way with the minimum sum (first we go $y_2-y_1$ steps right, and then $x_2-x_1$ steps down). Let's look at such a change in the "bends" of the way: After each step, the sum on the way will increase by $1$. We're going to bend like this until we get to the maximum sum. We're not going to miss any possi...
[ "math" ]
1,600
#include <iostream> using namespace std; int main() { int t; cin >> t; while (t--) { long long a, b, c, d; cin >> a >> b >> c >> d; cout << (c - a) * (d - b) + 1 << '\n'; } }
1358
D
The Best Vacation
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of ...
We will double the array of days and solve the problem when the day vacation starts and the day it ends is always in the same year. Then $a$ is an array of number of days in each of the months. Consider array $B = [1, 2, ..., a_1] + [1, 2, ..., a_2] + ... [1, 2, ..., a_n] + [1, 2, ..., a_n]$. Our task is to find a subs...
[ "binary search", "brute force", "greedy", "implementation", "two pointers" ]
1,900
#include <iostream> #include <algorithm> #include <vector> #define int long long using namespace std; signed main() { int n, len; cin >> n >> len; vector<int> A(2 * n); for (int i = 0; i < n; i++) { cin >> A[i]; A[n + i] = A[i]; } n *= 2; vector<int> B = {0}, C = {0}; for (int i = 0; i < n...
1358
E
Are You Fired?
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the $n$ consecutive months — in the $i$-th month the company had income equal to $a_i$ (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation,...
Let's call the value of all elements in the second half of the array $x$. Let $s_i = a_i + a_{i+1} + \ldots + a_{i+k-1}$ - the reported incomes. Pretend there exists such a $k$ that $k\le\tfrac{n}{2}$. Consider the following reported incomes: $s_i$ and $s_{i+k}$. Notice that if we double $k$, the $i$-th reported income...
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
2,400
#include <iostream> #include <vector> using namespace std; #define int long long signed main() { int n; cin >> n; int N = (n + 1) / 2; vector<int> a(N); for (int &el : a) cin >> el; int Ax; cin >> Ax; vector<int> m(N + 1, 0); int Pprefsm = 0; for (int i = 1; i < N + 1; ++i) { Pprefsm += A...
1358
F
Tasty Cookie
Oh, no! The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem. You are given two arrays $A$ and $B$ of ...
Let's define a few operations and constants: $pref$ - replace an array with its prefix sums array $reverse$ - reverse an array $rollback$ - restore the original array from a prefix sums array $C$ - the array values upper bound - $10^{12}$ First, we can prove that $rollback$ is unambiguosly defined for strictly increasi...
[ "binary search", "constructive algorithms", "greedy", "implementation" ]
2,700
#include <bits/stdc++.h> using namespace std; #define int long long signed main() { int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) cin >> b[i]; if (n == 1) { if (a[0] == b[0]) cout << "SMALL\n" << 0; else cout << "IMPOSSIBLE"; retu...
1359
A
Berland Poker
The game of Berland poker is played with a deck of $n$ cards, $m$ of which are jokers. $k$ players play this game ($n$ is divisible by $k$). At the beginning of the game, each player takes $\frac{n}{k}$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers i...
There are many different ways to solve this problem. The easiest one, in my opinion, is to iterate on the number of jokers the winner has (let it be $a_1$) and the number of jokers the runner-up has (let it be $a_2$). Then the following conditions should be met: $a_1 \ge a_2$ (the winner doesn't have less jokers than t...
[ "brute force", "greedy", "math" ]
1,000
t = int(input()) for i in range(t): n, m, k = map(int, input().split()) ans = 0 d = n // k for a1 in range(m + 1): for a2 in range(a1 + 1): if(a1 > d): continue if(a1 + a2 > m): continue if(a1 + (k - 1) * a2 < m): ...
1359
B
New Theatre Square
You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved. The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement. You are given the picture of...
Notice that rows can be solved completely separately of each other. Each tile takes either one or two squares but it's always in the same row. So let's take a look at a single row. There are sequences of dot characters separated by some asterisks. Once again each of these sequences can be solved independently of the ot...
[ "brute force", "dp", "greedy", "implementation", "two pointers" ]
1,000
t = int(input()) for _ in range(t): n, m, x, y = map(int, input().split()) ans = 0 y = min(y, 2 * x) for __ in range(n): s = input() i = 0 while i < m: if s[i] == '*': i += 1 continue j = i while j + 1 < m and s[j + 1] == '.': j += 1 l = j - i + 1 ans += l % 2 * x + l // 2 * y i ...
1359
C
Mixing Water
There are two infinite sources of water: - hot water of temperature $h$; - cold water of temperature $c$ ($c < h$). You perform the following procedure of alternating moves: - take \textbf{one} cup of the \textbf{hot} water and pour it into an infinitely deep barrel; - take \textbf{one} cup of the \textbf{cold} wate...
Idea: adedalic So there are two kinds of stops to consider: $k$ hot and $k$ cold cup and $(k + 1)$ hot and $k$ cold cups. The first case is trivial: the temperature is always $\frac{h + c}{2}$. In the second case the temperature is always strictly greater than $\frac{h + c}{2}$. Thus, if $t \le \frac{h + c}{2}$, then t...
[ "binary search", "math" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int tc; scanf("%d", &tc); forn(_, tc){ int h, c, t; scanf("%d%d%d", &h, &c, &t); if (h + c - 2 * t >= 0) puts("2"); else{ int a = h - t; int b = 2 * t - c - h; int k = 2 * (a / b) + ...
1359
D
Yet Another Yet Another Task
Alice and Bob are playing yet another card game. This time the rules are the following. There are $n$ cards lying in a row in front of them. The $i$-th card has value $a_i$. First, Alice chooses a non-empty consecutive segment of cards $[l; r]$ ($l \le r$). After that Bob removes a single card $j$ from that segment $(...
Alice wants to choose such a segment $[l; r]$ that $\sum \limits_{l \le i \le r} a_i - \max \limits_{l \le i \le r} a_i$ is maximum possible. There is a well-known problem where you have to find a segment with maximum $\sum \limits_{l \le i \le r} a_i$. That problem is solved with Kadane algorithm. Let's learn how to r...
[ "data structures", "dp", "implementation", "two pointers" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; int main() { int n; scanf("%d", &n); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); long long ans = 0; forn(mx, 31){ long long cur = 0; long long best = 0; forn(i, n){ int val = (a...
1359
E
Modular Stability
We define $x \bmod y$ as the remainder of division of $x$ by $y$ ($\%$ operator in C++ or Java, mod operator in Pascal). Let's call an array of positive integers $[a_1, a_2, \dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is ...
We claim that the array is stable if and only if all elements are divisible by its minimum. The proof of this fact will be at the end of the editorial. To calculate the number of stable arrays now, we need to iterate on the minimum in the array and choose the remaining elements so that they are multiples of it. If the ...
[ "combinatorics", "math", "number theory" ]
2,000
#include<bits/stdc++.h> using namespace std; const int N = 500043; const int MOD = 998244353; int fact[N]; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y > 0) {...
1359
F
RC Kaboom Show
You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event "Remote Control Kaboom Show" and stream everything online. ...
Let $f(t)$ be true if it's possible to have a collision before time $t$. That function is monotonous, thus let's binary search for $t$. For some fixed $t$ car $i$ can end up in any point from $(x_i, y_i)$ to $s_i \cdot t$ units along the ray $((x_i, y_i), (x_i + dx_i, y_i + dy_i))$. That makes it a segment. So the coll...
[ "binary search", "brute force", "data structures", "geometry", "math" ]
2,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define x first #define y second using namespace std; const double INF = 1e13; struct line{ int A, B, C; line(){} line(int x1, int y1, int x2, int y2){ A = y1 - y2; B = x2 - x1; C = -A * x1 - B * y1; // A is guaranteed to be non...
1360
A
Minimal Square
Find the minimum area of a \textbf{square} land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, - You are given two identical rectangles with side lengths $a$ and $b$ ($1 \le a, b \le 100$) — positive i...
Obviously that both rectangles should completely touch by one of the sides. Otherwise, you can move them closer to each other so that the total height or total width decreases, and the other dimension does not change. Thus, there are only two options: The rectangles touch by width, we get the side of the square equal t...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int solve(int a, int b) { int side = min(max(a * 2, b), max(a, b * 2)); return side * side; } int main(int argc, char* argv[]) { int t; cin >> t; forn(tt, t) { int a, b; cin >> a >> ...
1360
B
Honest Coach
There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team....
Let's found two athletes with numbers $a$ and $b$ (the strength of $a$ is not greater than the strength of $b$), which have the minimal modulus of the difference of their strength. Obviously, we cannot get an answer less than this. Let's show how to get the partition with exactly this answer. Sort all athletes by stren...
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; for (int tt = 0; tt < test; tt++) { int n; cin >> n; vector<int> a(n); for (int &x : a) { cin >> x; } sort(a.begin(), a.end()); int result = a[n - 1] - a[0]; for (int i = 0; i < n; i++) { for (int j = i + 1...
1360
C
Similar Pairs
We call two numbers $x$ and $y$ similar if they have the same parity (the same remainder when divided by $2$), or if $|x-y|=1$. For example, in each of the pairs $(2, 6)$, $(4, 3)$, $(11, 7)$, the numbers are similar to each other, and in the pairs $(1, 4)$, $(3, 12)$, they are not. You are given an array $a$ of $n$ (...
Let $e$ - be the number of even numbers in the array, and $o$ - be the number of odd numbers in the array. Note that if the parities of $e$ and of $o$ do not equal, then the answer does not exist. Otherwise, we consider two cases: $e$ and $o$ - are even numbers. Then all numbers can be combined into pairs of equal pari...
[ "constructive algorithms", "graph matchings", "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n; cin >> n; vector<int> v(n); int a = 0, b = 0; for (int &e : v) { cin >> e; if (e % 2 == 0) { a++; } else { b++; } } if (...
1360
D
Buying Shovels
Polycarp wants to buy \textbf{exactly} $n$ shovels. The shop sells packages with shovels. The store has $k$ types of packages: the package of the $i$-th type consists of exactly $i$ shovels ($1 \le i \le k$). The store has an infinite number of packages of each type. Polycarp wants to choose \textbf{one} type of packa...
If Polycarp buys $a$ packages of $b$ shovels and gets exactly $n$ shovels in total, then $a \cdot b = n$, that is, $a$ and $b$ are divisors of $n$. Then the problem reduces to the following, you need to find the maximum divisor of the number $n$ not greater than $k$. To do this, iterate over all the numbers $x$ from $1...
[ "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; for (int tt = 0; tt < test; tt++) { int n, k; cin >> n >> k; int ans = n; for (int j = 1; j * j <= n; j++) { if (n % j == 0) { if (j <= k) { ans = min(ans, n / j); } if (n / j <= k) { ans = min(ans...
1360
E
Polygon
Polygon is not only the best platform for developing problems but also a square matrix with side $n$, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly...
Let's see how the matrix looks like after some sequence of shoots: The matrix consists of 0, or There is at least one 1 at position ($n, i$) or ($i, n$), and any 1 not at position ($n, j$) or ($j, n$) must have 1 below or right. If the second condition is violated, then the 1 in the corresponding cell would continue it...
[ "dp", "graphs", "implementation", "shortest paths" ]
1,300
#include <bits/stdc++.h> using namespace std; bool a[50][50]; int main() { int tests; cin >> tests; while (tests--) { int n; cin >> n; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { char c; cin >> c; a[i][j] = c - '0'; } } bool ans = true; ...
1360
F
Spy-string
You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters. Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one...
Consider all strings that differ from the first one in no more than one position (this is either the first string or the first string with one character changed). We will go through all such strings and see if they can be the answer. To do this, go through all the strings and calculate the number of positions where the...
[ "bitmasks", "brute force", "constructive algorithms", "dp", "hashing", "strings" ]
1,700
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n, m; cin >> n >> m; vector<string> v(n); for (int i = 0; i < n; i++) { cin >> v[i]; } string ans = v[0]; for (int j = 0; j < m; j++) { char save = ans[j]; ...
1360
G
A/B Matrix
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions: - each row of the matrix contains exactly $a$ ones; - each column of the matrix contains exactly $b$ ones; - al...
Let's see how the desired matrix looks like. Since each row should have exactly $a$ ones, and each column should have exactly $b$ ones, the number of ones in all rows $a \cdot n$ should be equal to the number of ones in all columns $b \cdot m$. Thus, the desired matrix exists iff $a \cdot n = b \cdot m$ or $\frac{n}{m}...
[ "constructive algorithms", "greedy", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; for (int tt = 0; tt < test; tt++) { int h, w, a, b; cin >> h >> w >> a >> b; if (h * a != w * b) { cout << "NO" << endl; continue; } vector<vector<int>> result(h, vector<int>(w, 0)); int shif...
1360
H
Binary Median
Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total. The string $s$ is lexicographically smaller than the string $t$ (bot...
If we did not delete the strings, then the median would be equal to the binary notation of $2^{(m-1)}$. After deleting $n$ strings, the median cannot change (numerically) by more than $2 \cdot n$. Let's start with the median $2^{(m-1)}$ and each time decrease it by one if there are fewer not deleted smaller numbers tha...
[ "binary search", "bitmasks", "brute force", "constructive algorithms" ]
2,100
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { ll m, n; cin >> n >> m; vector<ll> v(n); for (int i = 0; i < n; i++) { string s; cin >> s; for (char c : s) { v[i] *= 2; v[i] += c - '0'; } } ll need = ((1ll << m) - n - 1) / 2 + 1; ll cur =...
1361
A
Johnny and Contribution
Today Johnny wants to increase his contribution. His plan assumes writing $n$ blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the reader...
We can view blogs as a graph, references as edges, and topics as colors. Now we can reformulate our problem as finding a permutation of vertices such that given in the statement greedy coloring algorithm returns coloring as described in the input. Let us start with two observations: Observation 1: If there is an edge b...
[ "constructive algorithms", "graphs", "greedy", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 7; int n, m; int ans[N]; int last[N]; vector <int> G[N]; vector <int> in[N]; int main(){ scanf("%d %d", &n, &m); for(int i = 1; i <= m; ++i){ int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } for(int i = 1; i...
1361
B
Johnny and Grandmaster
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. H...
The solution for the case $p = 1$ is trivial, the answer is $1$ for odd $n$ and $0$ for even $n$. From now on, I will assume that $p > 1$. Instead of partitioning the elements into two sets, I will think of placing plus and minus signs before them to minimize the absolute value of the resulting expression. We will proc...
[ "greedy", "implementation", "math", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll INF = 1e6+100; const ll mod = ll(1e9)+7; ll fexp (ll a, int e) { ll ret = 1LL; while (e>0) { if (e%2==1) ret = ret * a % mod; a = a*a % mod; e/=2; } return ret; } int main () { int t; scanf ("%d", &t); for (int test = 0; test ...
1361
C
Johnny and Megan's Necklace
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue. The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic...
Say that we want to check if it is possible to construct a necklace with beauty at least $b$. To this end, we will construct a graph of $2^{b}$ vertices. For a necklace part with pearls in colors $u$ and $v$ there will be an edge in this graph between vertices with zero-based indices $v\text{ & }(2^b-1)$ and $u\text{ &...
[ "binary search", "bitmasks", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,500
#include <bits/stdc++.h> using namespace std; #define st first #define nd second #define PII pair <int, int> const int N = 1 << 20; int n; int part[N][2]; bool vis[N]; vector <int> ans; vector <PII> G[N]; //mark whole component as visited void dfs(int u){ vis[u] = true; for(auto v: G[u]) if(!vis[v.st]) dfs...
1361
D
Johnny and James
James Bond, Johnny's favorite secret agent, has a new mission. There are $n$ enemy bases, each of them is described by its coordinates so that we can think about them as points in the Cartesian plane. The bases can communicate with each other, sending a signal, which is the ray directed from the chosen point to the or...
We can easily model the way of calculating distances from the problem statement as a tree with $n$ vertices, each corresponding to a base. This tree has the following structure: there is only one vertex which can have degree bigger than $2$ (the one corresponding to the central base), I will call it the center of the t...
[ "greedy", "implementation", "math", "trees" ]
2,900
#include <bits/stdc++.h> using namespace std; typedef long double T; #define st first #define nd second #define PII pair <int, int> const int N = 1e6 + 7; int n, m, k; vector <T> arms[N]; void read(){ map <PII, int> M; scanf("%d %d", &n, &k); for(int i = 1; i <= n; ++i){ int x, y; scanf("%d %d", &x, &y);...
1361
E
James and the Chase
James Bond has a new plan for catching his enemy. There are some cities and \textbf{directed} roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there. T...
First, let us describe an algorithm for checking if a vertex is interesting. Let $v$ be the vertex we want to check. Find any DFS tree rooted in that vertex. We can see that $v$ is interesting if and only if that tree is unique. The tree is unique iff every non-tree edge leads from some vertex $u$ to $u$'s ancestor. Th...
[ "dfs and similar", "graphs", "probabilities", "trees" ]
3,000
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7; int n, m; bool bad[N]; vector <int> G[N]; int vis[N]; bool interesting; int lvl[N]; int best[N]; int balance[N]; void clear(){ for(int i = 1; i <= n; ++i){ lvl[i] = 0; best[i] = 0; balance[i] = 0; G[i].clear(); bad[i] = false; } }...
1361
F
Johnny and New Toy
Johnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation $P$ of numbers from $1$ to $n$, written in one row next to each other. For each $i$ from $1$ to $n - 1$ between $P_i$ and $P_{i + 1}$ there is a weight $W_i$ written, and those weights form a permutation of numbers from ...
Let us start with an analysis of good subsegments for the fixed permutation. The whole permutation is a good subsegment itself, as $W_0 = W_n = 0 < W_k$ for any $k \in [1, 2, \ldots, n - 1]$. If we denote the minimal weight in $W_1, \ldots, W_{n - 1}$ as $W_m$, then we can notice that subsegments $[1, m]$ and $[m + 1, ...
[ "data structures", "implementation", "math" ]
3,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef tree < int, null_type, less <int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; const int N = 2e5 + 7; //cartesian tr...
1362
A
Johnny and Ancient Computer
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it \textbf{cuts off some ones}. So, in fact, in one operation, ...
Let us write $a$ as $r_a \cdot 2^x$ and $b$ as $r_b \cdot 2^y$, where $r_a$ and $r_b$ are odd. The only operation we have changes $x$ by $\{-3, -2, -1, 1, 2, 3\}$ so $r_a$ must be equal to $r_b$, otherwise the answer is $-1$. It is easy to notice that we can greedily move $x$ toward $y$ so the answer is equal to $\lcei...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; typedef long long LL; LL getR(LL a){ while(a % 2 == 0) a /= 2; return a; } void solve(){ LL a, b; scanf("%lld %lld", &a, &b); if(a > b) swap(a, b); LL r = getR(a); if(getR(b) != r){ puts("-1"); return; } int ans = 0; b /= a; while(b >= 8) b /= 8...