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
1677
E
Tokitsukaze and Beautiful Subsegments
Tokitsukaze has a permutation $p$ of length $n$. Let's call a segment $[l,r]$ beautiful if there exist $i$ and $j$ satisfying $p_i \cdot p_j = \max\{p_l, p_{l+1}, \ldots, p_r \}$, where $l \leq i < j \leq r$. Now Tokitsukaze has $q$ queries, in the $i$-th query she wants to know how many beautiful subsegments $[x,y]$...
Let's sort the queries $[l,r]$ with $r$ in ascending order. Let's move $R$ from $1$ to $n$, and answer queries $[l,r]$ when $r=R$. Use segment tree to solve this problem, each leaf node $[ul,ul]$ in the segment tree maintenance the number that how many intervals $[ul,R]$ are beautiful, then answering queries is to get ...
[ "data structures" ]
2,900
#include<bits/stdc++.h> using namespace std; const int N=2e5+5; typedef pair<int,int> pp; int n,m,ti,top,a[N],d[N],p[N],bz[N],bo[N]; long long ans[1000005]; vector<pp>q[1000005]; vector<int>w[N]; struct dd { long long x,y,tg,len; }tr[N*4]; void make(int x,int l,int r) { tr[x].len=r-l+1; if (l==r) return; int mid=l+...
1677
F
Tokitsukaze and Gems
Tokitsukaze has a sequence with length of $n$. She likes gems very much. There are $n$ kinds of gems. The gems of the $i$-th kind are on the $i$-th position, and there are $a_i$ gems of the same kind on that position. Define $G(l,r)$ as the multiset containing all gems on the segment $[l,r]$ (inclusive). A multiset of...
First, consider how to calculate the contribution of a legal path. It can be found that the contribution of a legal path is equivalent to the following formula, where $b_i$ indicates the number of the $i$-th gems on the path. $\sum_{i_1=0}^{b_1}\sum_{i_2=0}^{b_2}\ldots \sum_{i_n=0}^{b_n}(\sum_{j=1}^n (P^{i_j}i_j^k)\tim...
[ "dp", "math" ]
3,500
#include<cmath> #include<queue> #include<cstdio> #include<cstring> #include<assert.h> #include<iostream> #include<algorithm> using namespace std; #define LL long long #define int long long const int MAXN=4e5+5; const int MAXNN=1e5+5; int n,k,P,fac[MAXN],ifac[MAXN],Inv[MAXN],rev[MAXN],x[MAXN],y[MAXN],K[MAXN],B[MAXN],g[M...
1678
A
Tokitsukaze and All Zero Sequence
Tokitsukaze has a sequence $a$ of length $n$. For each operation, she selects two numbers $a_i$ and $a_j$ ($i \ne j$; $1 \leq i,j \leq n$). - If $a_i = a_j$, change one of them to $0$. - Otherwise change both of them to $\min(a_i, a_j)$. Tokitsukaze wants to know the minimum number of operations to change all numbers...
We observe that when there is $0$ in the sequence, it is optimal to choose $0$ and any number other than $0$ for each operation. Therefore, when there is $0$ in the sequence, let $cnt$ be the number of $0$s, the answer is $n - cnt$. Otherwise, when $0$ does not exist in the sequence, there are two situations: When ther...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int t; scanf("%i",&t); while(t--){ int n; scanf("%i",&n); vector<int> a(n); for(int i=0;i<n;i++) scanf("%i",&a[i]); sort(a.begin(),a.end()); int zero=count(a.begin(),a.end(),0); if(zero>0) printf("%i\n",n-zero); else{ bool same=fals...
1678
B2
Tokitsukaze and Good 01-String (hard version)
This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments. Tokitsukaze has a binary string $s$ of length $n$, consisting only of zeros and ones, $n$ is \textbf{even}. Now Tokitsukaze divides $s$ into \textbf{t...
Obviously, the operation is, for each pair of adjacent and unequal characters, change both of them to $0$ or $1$. In other words, the string is divided into many adjacent binaries with length of $2$. If the binary is "01" or "10", it needs $1$ operation, otherwise the operation is not required. If you want to minimize ...
[ "dp", "greedy", "implementation" ]
1,800
#include<bits/stdc++.h> #define fre(z) freopen(z".in","r",stdin),freopen(z".out","w",stdout) #define lowit(x) (x&-x) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define sto \ std::ios::sync_with_stdio(false); \ std::cin.tie(nullptr); ...
1679
A
AvtoBus
Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses. You own a small bus service business and you have just received an order to replace $n$ tires. You know that the bus fleet owns two types of buses: with two axles (these buses have $...
Let the number of buses with two axles is $x$ and the number of buses with three axles is $y$. Then the equality $4x + 6y = n$ must be true. If $n$ is odd, there is no answer, because the left part of the equality is always even. Now we can divide each part of the equality by two: $2x + 3y = \frac{n}{2}$. Let's maximiz...
[ "brute force", "greedy", "math", "number theory" ]
900
null
1679
B
Stone Age Problem
Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an ...
As we want to perform queries fast, we will store some variables: current sum of all elements in the array $sum$, index of the last query of the second type $lastSecondQuery$ and its value $lastSecondQueryValue$. For each element of the array we will also store index of the last query of the first type that changed thi...
[ "data structures", "implementation" ]
1,200
null
1679
C
Rooks Defenders
You have a square chessboard of size $n \times n$. Rows are numbered from top to bottom with numbers from $1$ to $n$, and columns — from left to right with numbers from $1$ to $n$. So, each cell is denoted with pair of integers $(x, y)$ ($1 \le x, y \le n$), where $x$ is a row number and $y$ is a column number. You ha...
Consider some subrectangle. Note that each its cell is attacked by some rook if and only if there is at least one rook in each row $x$ ($x_1 \le x \le x_2$) or in each column $y$ ($y_1 \le y \le y_2$). Now we will solve the problem using this criterium. Let's create a set $freeRows$ where we will store indices of rows ...
[ "data structures", "implementation" ]
1,400
null
1679
D
Toss a Coin to Your Graph...
One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem... Masha has an oriented graph which $i$-th vertex contains some positive integer $a_i$. Initially Masha can put a coin at some vertex. ...
Note that the function of existence of the answer relatively to the minimum value of the maximum in the path is monotonous. If we were able to construct the path with maximum, not greater than $x$, we are able to construct the path with maximum, not greater than $x + 1$. This leads to the idea of binary search the answ...
[ "binary search", "dfs and similar", "dp", "graphs" ]
1,900
null
1679
E
Typical Party in Dorm
Today is a holiday in the residence hall — Oleh arrived, in honor of which the girls gave him a string. Oleh liked the gift a lot, so he immediately thought up and offered you, his best friend, the following problem. You are given a string $s$ of length $n$, which consists of the first $17$ lowercase Latin letters {$a...
We are given a string $s$, we need to count the number of palindromes in all possible versions of it if the characters "$?$" can be replaced by some letters of the English alphabet, which are set by queries. Let us solve the problem initially for a $1$ query. First, we can see that instead of counting the number of pal...
[ "bitmasks", "combinatorics", "dp", "strings" ]
2,400
null
1679
F
Formalism for Formalism
Yura is a mathematician, and his cognition of the world is so absolute as if he have been solving formal problems a hundred of trillions of billions of years. This problem is just that! Consider all non-negative integers from the interval $[0, 10^{n})$. For convenience we complement all numbers with leading zeros in s...
If you carefully read the problem statement, it becomes clear that we can do some transformations some numbers into others and we have to calculate the number of equivalence classes of all numbers consisting of $n$ digits. Let's say that the representative of some equivalence class is the lexicographically minimal numb...
[ "bitmasks", "dp", "math" ]
2,600
null
1680
A
Minimums and Maximums
An array is beautiful if both of the following two conditions meet: - there are \textbf{at least} $l_1$ and \textbf{at most} $r_1$ elements in the array equal to its minimum; - there are \textbf{at least} $l_2$ and \textbf{at most} $r_2$ elements in the array equal to its maximum. For example, the array $[2, 3, 2, 4,...
Firstly, since we are interested in minimum possible size of the array, we don't need any elements other than minimums and maximums. So, the array has at most $2$ distinct elements. Now there are many possible solutions. The simplest one is to iterate on the number of minimums (let this be $i$) and maximums (let this b...
[ "brute force", "math" ]
800
t = int(input()) for i in range(t): l1, r1, l2, r2 = map(int, input().split()) if max(l1, l2) <= min(r1, r2): print(max(l1, l2)) else: print(l1 + l2)
1680
B
Robots
There is a field divided into $n$ rows and $m$ columns. Some cells are empty (denoted as E), other cells contain robots (denoted as R). You can send a command to \textbf{all robots} at the same time. The command can be of one of the four types: - move up; - move right; - move down; - move left. When you send a comma...
Let's assume that the rows are numbered from $0$ to $n-1$ from top to bottom, and columns are numbered from $0$ to $m-1$ from left to right. If there is no robot in the cell $(0, 0)$ initially, we have to perform several moves up and/or left. If the first row with at least one robot is the $i$-th row, then we can make ...
[ "implementation" ]
800
t = int(input()) for i in range(t): n, m = map(int, input().split()) s = [] for j in range(n): s.append(input()) minx = 10 ** 9 miny = 10 ** 9 for x in range(n): for y in range(m): if s[x][y] == 'R': minx = min(minx, x) miny = min(miny,...
1680
C
Binary String
You are given a string $s$ consisting of characters 0 and/or 1. You have to remove several (possibly zero) characters from the beginning of the string, and then several (possibly zero) characters from the end of the string. \textbf{The string may become empty after the removals}. The cost of the removal is the \textbf...
There are many different approaches to this problem: dynamic programming, binary search, greedy, two pointers, anything you want. The model solution uses an approach based on binary search, so I'll describe it. First of all, why does binary search work? Let's say that the number of 1's is $c$. If the cost of deletion i...
[ "binary search", "greedy", "strings", "two pointers" ]
1,600
def can(pos, m): k = len(pos) x = k - m for i in range(m + 1): l = pos[i] r = pos[i + x - 1] if r - l + 1 - x <= m: return True return False t = int(input()) for i in range(t): s = input() pos = [] n = len(s) for i in range(n): if s[i] ==...
1680
D
Dog Walking
You are walking with your dog, and now you are at the promenade. The promenade can be represented as an infinite line. Initially, you are in the point $0$ with your dog. You decided to give some freedom to your dog, so you untied her and let her run for a while. Also, you watched what your dog is doing, so you have so...
Consider every cyclic shift of the array $a$. Suppose that now the array $a$ starts from the position $i$ (the first element is $a[i]$ and the last element is $a[(i + n - 1) \% n]$). Assume that before the position $i$ our dog reached her minimum possible position and now the minimum position will not change. So our pr...
[ "brute force", "greedy", "math" ]
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 n; long long k; cin >> n >> k; vector<long long> a(n); for (auto &it : a) { cin >> it; } long long ans = 0; ...
1680
E
Moving Chips
You are given a board of size $2 \times n$ ($2$ rows, $n$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board. In one move, you can choose \textbf{any} chip and move it to any adjacent (...
Firstly, I want to say a few words about the difficulty of this problem. Till the last moment, we didn't know easy to prove (and easy to write) solutions, so we decided that this is a good problem E. But now we realized it is a lot easier than we expected. Now, let's talk about the solution. At the beginning, let's rem...
[ "bitmasks", "dp", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int tc; cin >> tc; while (tc--) { int n; string s[2]; cin >> n >> s[0] >> s[1]; ...
1680
F
Lenient Vertex Cover
You are given a simple connected undirected graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$. A vertex cover of a graph is a set of vertices such that each edge has at least one of its endpoints in the set. Let's call a lenient vertex cover such a vertex cover that \textbf{at...
Let's think about why we can't always make a perfect vertex cover - such a vertex cover that each edge has exactly one endpoint in it. Or why the answer can not exist at all. Consider a bamboo. It's always possible to find a perfect vertex cover. Just choose every other vertex in it and account for parity. Make a bambo...
[ "dfs and similar", "divide and conquer", "dsu", "graphs", "trees" ]
2,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; vector<vector<int>> g, h; vector<int> tin, tout, clr; vector<vector<int>> sum(2); int T; int flip; int cnt; bool isp(int v, int u){ return tin[v] <= tin[u] && tout[v] >= tout[u]; } void init(int v){ tin[v] = ...
1681
A
Game with Cards
Alice and Bob play a game. Alice has $n$ cards, the $i$-th of them has the integer $a_i$ written on it. Bob has $m$ cards, the $j$-th of them has the integer $b_j$ written on it. On the first turn of the game, \textbf{the first player} chooses one of his/her cards and puts it on the table (plays it). On the second tur...
Let the maximum card among all $n + m$ cards be $x$. If only one player has a card of value of $x$, then he/she can win by playing it on the first turn or on the second turn; the opponent won't be able to respond with any of their cards. Otherwise (if both players have a card with value $x$), the player who plays this ...
[ "games", "greedy" ]
800
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) m = int(input()) b = list(map(int, input().split())) print('Alice' if max(a) >= max(b) else 'Bob') print('Alice' if max(a) > max(b) else 'Bob')
1681
B
Card Trick
Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $n$ cards. You see that the values of cards from the topmost to the bottommost are integers $a_1, a_2, \dots, a_n$, and all values are different. Then he asks you to shuffle the deck $m$ times. With the $j$...
The easiest way to solve to problem is probably to see the resemblense of a shuffle operation to an std::rotate function. So you can obtain the final deck by applying cyclic shifts of the deck by $b_1$, then $b_2$ and so on. Since the shifts are cyclic, it doesn't matter if you shift by $x$ or by $x + n$ or by $x + k \...
[ "implementation", "math" ]
800
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) m = int(input()) print(a[sum(map(int, input().split())) % n])
1681
C
Double Sort
You are given two arrays $a$ and $b$, both consisting of $n$ integers. In one move, you can choose two indices $i$ and $j$ ($1 \le i, j \le n$; $i \neq j$) and swap $a_i$ with $a_j$ and $b_i$ with $b_j$. You have to perform the swap in both arrays. You are allowed to perform at most $10^4$ moves (possibly, zero). Can...
Imagine that all elements of $a$ are distinct. This way, sorting $a$ in increasing order will fix the order of $b$. If $b$ turns out sorted in a non-decreasing order, then the answer exists. Otherwise, it doesn't. To obtain the sequence of swaps, you can sort $a$ with any comparison-based sorting algorithm you want: ev...
[ "implementation", "sortings" ]
1,200
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) tmp = [i for i in range(n)] tmp.sort(key=lambda i: [a[i], b[i]]) for i in range(n - 1): if a[tmp[i]] > a[tmp[i + 1]] or b[tmp[i]] > b[tmp[i + 1]]: print("-1") break else: ans = [] fo...
1681
D
Required Length
You are given two integer numbers, $n$ and $x$. You may perform several operations with the integer $x$. Each operation you perform is the following one: choose any digit $y$ that occurs in the decimal representation of $x$ at least once, and replace $x$ by $x \cdot y$. You want to make the length of decimal represen...
One of the possible approaches to this problem is to try multiplying $x$ only by the largest digit in it. Unfortunately, this doesn't work quite well, since it gives WA on one of the examples. That example is too big to consider, but a smaller version of it can prove that this is an incorrect solution: let $n = 5$, $x ...
[ "brute force", "dfs and similar", "dp", "hashing", "shortest paths" ]
1,700
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long v; cin >> v; queue<long long> q; map<long long, int> dist; dist[v] = 0; q.push(v); while(!q.empty()) { long long k = q.front(); q.pop(); string s = to_string(k); ...
1681
E
Labyrinth Adventures
You found a map of a weirdly shaped labyrinth. The map is a grid, consisting of $n$ rows and $n$ columns. The rows of the grid are numbered from $1$ to $n$ from bottom to top. The columns of the grid are numbered from $1$ to $n$ from left to right. The labyrinth has $n$ layers. The first layer is the bottom left corne...
WLOG, assume all queries ask to move from a lower layer to a higher layer. The first thing to notice in the problem is that it is always optimal to never go down a layer. You have an optimal path that is going down some layers, and then returning to the same layer. So it leaves a layer in some its cell and returns to i...
[ "data structures", "dp", "matrices", "shortest paths" ]
2,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const long long INF64 = 1e18; typedef pair<int, int> pt; #define x first #define y second int main() { int n; scanf("%d", &n); vector<vector<pt>> d(n - 1, vector<pt>(2)); forn(i, n - 1) forn(j, 2){ scanf("%d%d",...
1681
F
Unique Occurrences
You are given a tree, consisting of $n$ vertices. Each edge has an integer value written on it. Let $f(v, u)$ be the number of values that appear \textbf{exactly once} on the edges of a simple path between vertices $v$ and $u$. Calculate the sum of $f(v, u)$ over all pairs of vertices $v$ and $u$ such that $1 \le v <...
Let's use contribution to the sum technique to simplify the problem. Instead of counting the number of colors that occure only once for each path, let's, for each color, count the number of paths that contain this color exactly once. Now we can solve the problem independently for each color, and sum up the answers. The...
[ "data structures", "dfs and similar", "divide and conquer", "dp", "dsu", "trees" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct edge{ int v, u, w; }; vector<vector<edge>> t; void add(int v, int l, int r, int L, int R, const edge &e){ if (L >= R) return; if (l == L && r == R){ t[v].push_back(e); return; } int m = (l + r) / 2; ...
1682
A
Palindromic Indices
You are given a \textbf{palindromic} string $s$ of length $n$. You have to count the number of indices $i$ $(1 \le i \le n)$ such that the string after removing $s_i$ from $s$ still remains a palindrome. For example, consider $s$ = "aba" - If we remove $s_1$ from $s$, the string becomes "ba" which is not a palindrom...
Read the statement carefully!! The given string is a palindrome. Let's remove some index $i$ from the first half of $s$ and check whether the resulting string is a palindrome or not, the other half has the same approach. The prefix of length $i-1$ already matches with the suffix of the same length because the initial s...
[ "greedy", "strings" ]
800
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...
1682
B
AND Sorting
You are given a permutation $p$ of integers from $0$ to $n-1$ (each of them occurs exactly once). Initially, the permutation is \textbf{not sorted} (that is, $p_i>p_{i+1}$ for at least one $1 \le i \le n - 1$). The permutation is called $X$-sortable for some non-negative integer $X$ if it is possible to sort the permu...
You must have to make at least one swap on the elements which are not at their correct positions initially. So $X$ must be a submask of all elements which are not at their correct positions. What is the maximum possible value of $X$ from Hint $1$? It is the bitwise AND of all elements which are not at their correct pos...
[ "bitmasks", "constructive algorithms", "sortings" ]
1,100
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...
1682
C
LIS or Reverse LIS?
You are given an array $a$ of $n$ positive integers. Let $\text{LIS}(a)$ denote the length of longest strictly increasing subsequence of $a$. For example, - $\text{LIS}([2, \underline{1}, 1, \underline{3}])$ = $2$. - $\text{LIS}([\underline{3}, \underline{5}, \underline{10}, \underline{20}])$ = $4$. - $\text{LIS}([3,...
Let $\text{LDS}(a)$ be the longest strictly decreasing subsequence of $a$, then $\text{LIS}(a')$ = $\text{LDS}(a)$. There can be at most one index common between $\text{LIS}(a)$ and $\text{LDS}(a)$. Let's make a small observation: There can be at most one index common to both $\text{LIS}(a)$ and $\text{LDS}(a)$. If som...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,400
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...
1682
D
Circular Spanning Tree
There are $n$ nodes arranged in a circle numbered from $1$ to $n$ in the clockwise order. You are also given a binary string $s$ of length $n$. Your task is to construct a tree on the given $n$ nodes satisfying the two conditions below or report that such tree does not exist: - For each node $i$ $(1 \le i \le n)$, th...
What are the mandatory conditions on string $s$ for a tree to be possible? If there are no odd degree vertices or the count of odd degree vertices is odd, then it is impossible to construct any tree. It turns out that these conditions are sufficient too. Let's check some cases when it is not possible to construct the a...
[ "constructive algorithms", "implementation", "trees" ]
2,000
#include<bits/stdc++.h> using namespace std; #define all(v) v.begin(),v.end() #define endl "\n" int solve(){ int n; cin >> n; string s; cin >> s; auto cnt = count(all(s),'1'); if(cnt == 0 or cnt & 1){ cout << "NO" << endl; return 0; } auto inc = [&](int j){ return (j ...
1682
E
Unordered Swaps
Alice had a permutation $p$ of numbers from $1$ to $n$. Alice can swap a pair $(x, y)$ which means swapping elements at positions $x$ and $y$ in $p$ (i.e. swap $p_x$ and $p_y$). Alice recently learned her first sorting algorithm, so she decided to sort her permutation in the \textbf{minimum} number of swaps possible. S...
One way of solving permutation problems is to look at permutation cycles. Let's decompose our permutation into cycles, then it's easy to see that each cycle can be solved independently because we have to sort the permutation in a minimum number of moves which isn't possible if two cycles are merged at any instant. Let'...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "math", "sortings", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...
1682
F
MCMF?
You are given two integer arrays $a$ and $b$ ($b_i \neq 0$ and $|b_i| \leq 10^9$). Array $a$ is sorted in \textbf{non-decreasing} order. The cost of a subarray $a[l:r]$ is defined as follows: - If $ \sum\limits_{j = l}^{r} b_j \neq 0$, then the cost is not defined. - Otherwise: - Construct a bipartite flow graph wit...
Let us suppose we need to calculate the answer for only one query, say complete array i.e $a[1:n]$. The scary flow structure in the problem can be reduced as- Let's replicate each vertex $i$, $|b_i|$ times. Then we can see that there will be an equal number of vertices on the left and right side. Now the problem reduce...
[ "data structures", "flows", "graphs", "greedy", "sortings", "two pointers" ]
2,700
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...
1684
A
Digit Minimization
There is an integer $n$ \textbf{without zeros} in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns. On her turn, Alice \textbf{must} swap any two digits of the integer that are on different positions. Bob on his turn always removes the last...
Let $k$ be the length of $n$. Let $n_i$ be the $i$-th digit of $n$ ($1$-indexation from the left). $k = 1$The game ends immediately so the answer is $n$ itself. The game ends immediately so the answer is $n$ itself. $k = 2$Alice should make the first move and she has to swap $n_1$ and $n_2$. After that Bob removes $n_1...
[ "constructive algorithms", "games", "math", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { string n; cin >> n; if (n.size() == 2) { cout << n[1] << '\n'; } else { cout << *min_element(n.begin(), n.end()) << '\n'; } } return 0; }
1684
B
Z mod X = C
You are given three positive integers $a$, $b$, $c$ ($a < b < c$). You have to find three positive integers $x$, $y$, $z$ such that: $$x \bmod y = a,$$ $$y \bmod z = b,$$ $$z \bmod x = c.$$ Here $p \bmod q$ denotes the remainder from dividing $p$ by $q$. It is possible to show that for such constraints the answer alw...
In this problem it is enough to find a contstruction that works for all $a < b < c$. For example: $x = a + b + c$$y = b + c$ $z = c$ $y = b + c$ $z = c$ In this case $x \bmod y = (a + b + c) \bmod (b + c) = a$ since $a < b < b + c$ $y \bmod z = (b + c) \bmod c = b$ since $b < c$ $z \bmod x = c \bmod (a + b + c) = c$ si...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int a, b, c; cin >> a >> b >> c; cout << a + b + c << " " << b + c << " " << c << "\n"; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
1684
C
Column Swapping
You are given a grid with $n$ rows and $m$ columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each $1 \le i \le n$ and $2 \le j \le m$ the following holds: $a_{i,j} \ge a_{i, j-1}$. You ha...
At first, let's check wether the given table is good. If it is not then there is a row that has elements that should be replaced. Let's say that this row is $a$ and $b$ is the sorted row $a$. Then let's find the set of positions $i$ that $a_i \neq b_i$. If there are at least $3$ such positions then the answer is $-1$ b...
[ "brute force", "constructive algorithms", "greedy", "implementation", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve(vector<vector<int>> &a) { int n = a.size(), m = a[0].size(); vector<int> bad; for (int i = 0; i < n && bad.empty(); i++) { vector<int> b = a[i]; sort(b.begin(), b.end()); for (int j = 0; j < m; j++) { if (a[i][j] ...
1684
D
Traps
There are $n$ traps numbered from $1$ to $n$. You will go through them one by one in order. The $i$-th trap deals $a_i$ base damage to you. Instead of going through a trap, you can jump it over. You can jump over no more than $k$ traps. If you jump over a trap, it does not deal any damage to you. But there is an addit...
Firstly, let's notice that it is always better to use all $k$ jumps. If we jumped over less than $k$ traps then we can jump over the last trap and the total damage will be less. Secondly, let's say that we immediately get $n - i$ damage if we jump over $i$-th trap. This way the first trap that we jump over will cause $...
[ "constructive algorithms", "greedy", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() void solve() { int n, k; cin >> n >> k; long long ans = 0; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; ans += a[i]; a[i] += i + 1; } sort(all(a)); reverse(all(a)...
1684
E
MEX vs DIFF
You are given an array $a$ of $n$ non-negative integers. In one operation you can change any number in the array to any other non-negative integer. Let's define the cost of the array as $\operatorname{DIFF}(a) - \operatorname{MEX}(a)$, where $\operatorname{MEX}$ of a set of non-negative integers is the smallest non-ne...
Let's consider all possible $\operatorname{MEX}$ after all operations. It is from $0$ to $n$ and we can check them all in the increasing order. Now let's fix some $\operatorname{MEX} = m$. There should be all numbers from $0$ to $m$ in the array, so there are some "holes" in the array that should be covered. The hole i...
[ "binary search", "brute force", "constructive algorithms", "data structures", "greedy", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define puu pair<unsigned, unsigned> #define ll long long #define mp make_pair #define ui unsigned #define ull unsigned long long #define ld double ...
1684
F
Diverse Segments
You are given an array $a$ of $n$ integers. Also you are given $m$ subsegments of that array. The left and the right endpoints of the $j$-th segment are $l_j$ and $r_j$ respectively. You are allowed to make \textbf{no more than one} operation. In that operation you choose any subsegment of the array $a$ and replace ea...
Let's say the answer is $[L, R]$. Let's consider all given segments. There should be no two equal elements that are in the same given segment and are not in $[L, R]$, i.e. at least one of them should be in the answer. Let's find such segment of minimal length for $L = 1$. To do that let's for each $r$ find such minimal...
[ "data structures", "two pointers" ]
2,600
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define puu pair<unsigned, unsigned> #define ll long long #define mp make_pair #define ui unsigned #define ull unsigned long long #define ld double ...
1684
G
Euclid Guess
Let's consider Euclid's algorithm for finding the greatest common divisor, where $t$ is a list: \begin{verbatim} function Euclid(a, b): if a < b: swap(a, b) if b == 0: return a r = reminder from dividing a by b if r > 0: append r to the back of t return Euclid(b, r) \end{verbatim} There is an array $p$ of pairs of po...
Let's consider some pair $(a, b)$ and consider a sequence of remainders that is induced by this pair: $a \bmod b = x_1$, $b \bmod x_1 = x_2$, ..., $x_{p - 2} \bmod x_{p - 1} = x_p$, where $x_p = gcd(a, b)$. If $x_i \le \frac{m}{3}$ then we can just add a pair $(3x_i, 2x_i)$ and we will get the only remainder $x_i$ so t...
[ "constructive algorithms", "flows", "graph matchings", "math", "number theory" ]
2,800
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define puu pair<unsigned, unsigned> #define ll long long #define mp make_pair #define ui unsigned #define ull unsigned long long #define ld doubl...
1684
H
Hard Cut
You are given a binary string $s$. You have to cut it into any number of non-intersecting substrings, so that the sum of binary integers denoted by these substrings is a power of 2. Each element of $s$ should be in exactly one substring.
Let's say that there are $k$ ones in the given string. We will build the answer for all $k > 0$. $k = 0$ is the only case when the answer does not exist. $k = 1$, $k = 2$, $k = 4$ - cut into single digits. $k = 3$ - described later. Let's consider $k = 5$: If all ones are in a row, then we should cut them into $1111_2 ...
[ "constructive algorithms", "dfs and similar", "divide and conquer", "math" ]
3,400
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e6; int g[MAXN + 1]; string s; vector<pair<int, int>> segments; // [l, r] int get(int k, int i) { // get k-th '1' on [i, |s|) --i; while (k --> 0) i = s.find('1', i + 1); return i; } void five() { int first = get(1, 0), last = get(5, 0); int r = (...
1685
A
Circular Local MiniMax
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors? In other words, check if there exists a rearrangement $b_1, b_2, \ldots, b_n$ of the integers $a_1, a_2, \ldots, a_...
Let's call $b_i$ local minimum if $b_{i-1} > b_i < b_{i+1}$ and local maximum if $b_{i-1} < b_i > b_{i+1}$. It's clear that in the arrangement satisfying the conditions from the statement, if $b_i$ is a local minimum, $b_{i+1}$ is a local maximum, and vice versa. Local minimums and local maximums will be alternating. T...
[ "constructive algorithms", "greedy", "sortings" ]
1,100
null
1685
B
Linguistics
Alina has discovered a weird language, which contains only $4$ words: $A$, $B$, $AB$, $BA$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string. Alina has found one such sentence $s$ and she is curious: is it possible that it consists...
For the answer to be $\texttt{YES}$ the frequency of the character $\texttt{A}$ in the $a+b+c+d$ words must coincide with its frequency in the sentence $s$, which is equivalent to the condition $a + c + d = \#\{i:\, s_i = \texttt{A}\}$. From now on we may assume that this is true. Notice that the answer to the problem ...
[ "greedy", "implementation", "sortings", "strings" ]
2,000
null
1685
C
Bring Balance
Alina has a bracket sequence $s$ of length $2n$, consisting of $n$ opening brackets '(' and $n$ closing brackets ')'. As she likes balance, she wants to turn this bracket sequence into a balanced bracket sequence. In one operation, she can reverse any substring of $s$. What's the smallest number of operations that sh...
Let's denote ( by $1$ and ) by $-1$. Then we need to achieve a sequence in which all prefix sums are nonnegative. Let our sequence be $a_1, a_2, \ldots, a_{2n}$, and denote $pref_i = a_1 + a_2 + \ldots + a_i$ for each $0 \le i \le 2n$. Key observation: It's always possible to get a balanced sequence in at most $2$ oper...
[ "brute force", "constructive algorithms", "greedy" ]
2,600
null
1685
D1
Permutation Weight (Easy Version)
\textbf{This is an easy version of the problem. The difference between the easy and hard versions is that in this version, you can output any permutation with the smallest weight}. You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$. Let's define the weight of the permutation $q_1, q_2, \l...
Let's first understand what is the minimum possible weight of $q$. When can it be $0$? Only when $q_i = p_{q_{i+1}}$ for each $i$. Clearly, such $q$ exists only when $p$ is just one cycle. This gives a hint that we should look at cycles. Consider splitting of $p$ into cycles (where a cycle is an array $[a_1, a_2, \ldot...
[ "constructive algorithms", "dfs and similar", "dsu" ]
2,800
null
1685
D2
Permutation Weight (Hard Version)
\textbf{This is a hard version of the problem. The difference between the easy and hard versions is that in this version, you have to output the lexicographically smallest permutation with the smallest weight}. You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$. Let's define the weight of...
We will start by proving that the weight is at least $2(k-1)$ (where $k$ is the number of cycles), and understanding the structure of optimal permutations in the process. Again, consider splitting of $p$ into cycles (where a cycle is an array $[a_1, a_2, \ldots, a_m]$ such that $p_{a_i} = a_{i \bmod m +1}$ for $1 \le i...
[ "constructive algorithms", "greedy" ]
3,500
null
1685
E
The Ultimate LIS Problem
It turns out that this is exactly the $100$-th problem of mine that appears in some programming competition. So it has to be special! And what can be more special than another problem about LIS... You are given a permutation $p_1, p_2, \ldots, p_{2n+1}$ of integers from $1$ to $2n+1$. You will have to process $q$ upda...
Consider element $n+1$. Replace for a while $n+1$ by $0$, each element $\le n$ by $-1$, and each element $\ge n+2$ by $1$. It's well-known that for an array of $n$ of $1$ and $n$ of $-1$ there exists a cyclic shift such that all its prefix sums are nonnegative (which is equivalent to the sequence of these $1$s and $-1$...
[ "data structures", "greedy" ]
3,500
null
1686
A
Everything Everywhere All But One
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$. After you watched the amazing film "Everything Everywhere All At Once", you came up with the following operation. In one operation, you choose $n-1$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an int...
Suppose that we did one operation and not all numbers are equal. Let's say that we have $n-1$ numbers $x$ and $1$ number $y$ now, with $x \neq y$. In the next operation, we have two options: to make operation with $n-1$ numbers $x$, or with $n-2$ of $x$ and one $y$. If we go with the first option, we will still have $n...
[ "greedy" ]
800
null
1686
B
Odd Subarrays
For an array $[b_1, b_2, \ldots, b_m]$ define its number of inversions as the number of pairs $(i, j)$ of integers such that $1 \le i < j \le m$ and $b_i>b_j$. Let's call array $b$ \textbf{odd} if its number of inversions is odd. For example, array $[4, 2, 7]$ is odd, as its number of inversions is $1$, while array $[...
Consider any optimal splitting. Clearly, for any subarray $[b_1, b_2, \ldots, b_m]$ which is not odd, we can just split it into $[b_1], [b_2], \ldots, [b_m]$, For any odd subarray $[b_1, b_2, \ldots, b_m]$ with $m \ge 3$, there exists an $1 \le i \le m-1$ such that $b_i > b_{i+1}$ (otherwise $b$ is sorted and has no in...
[ "dp", "greedy" ]
800
null
1687
A
The Enchanted Forest
\begin{quote} The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached. \hfill —Perfect Memento in Strict Sense \end{quote} Marisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $n$ points on...
Consider $k\le n$ and $k>n$ separately. Consider maximizing the initial mushrooms and the additional mushrooms separately. Is there any common strategy? If $k\le n$: Consider how to maximize the initial mushrooms she collects. Obviously she will not walk into one position more than one times, and the answer is $\max\li...
[ "brute force", "greedy" ]
1,600
T=int(input()) for t in range(T): n,m=map(int,input().split()) a=[0]+list(map(int,input().split())) for i in range(1,n+1): a[i]+=a[i-1] if m>n: print(a[n]+(m-1+m-n)*n//2) else: ans=0 for i in range(n+1): if i>=m: ans=max(ans,a[i]-a[i-m]) print(ans+(1+m-1)*(m-1)//2)
1687
B
Railway System
\begin{quote} As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to. \hfill —Yasaka Kanako, Symposium of Post-mysticism \end{quote} This is an interactive problem. Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally fi...
$2m=m+m$. What can we do with the first $m$ queries? We can now the lengths of each edge with $m$ queries. Kruskal. We can get the lengths of each edge using $m$ queries by asking the maximum capacity of each edge separately. Then, sort the edges in non-decreasing order represented by ${l}$, and ask the maximum capacit...
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
1,700
n,m=map(int,input().split()) a=[] for i in range(m): print('?','0'*i+'1'+'0'*(m-i-1),flush=1) a.append(int(input())) cur=0 s=['0' for i in range(m)] for i in range(m): x=0 for j in range(m): if a[x]>a[j]: x=j s[x]='1' print('? ',*s,sep='',flush=1) c=int(input()) if (cur+a[x]==c): cur+=a[x] else: s[x]=...
1687
C
Sanae and Giant Robot
\begin{quote} Is it really?! The robot only existing in my imagination?! The Colossal Walking Robot?!! \hfill — Kochiya Sanae \end{quote} Sanae made a giant robot — Hisoutensoku, but something is wrong with it. To make matters worse, Sanae can not figure out how to stop it, and she is forced to fix it on-the-fly.The s...
Let $b_i=0$ for convenience. The interval selected satisfies $\sum\limits_{i=l}^r a_i=0$. What does range sum remind you of? Let $s_i=\sum\limits_{k=1}^i a_k-b_k$. The task can be described as: Given an array $s$. For some given interval $[l,r]$ if $s_{l-1}=s_r$, we can assign $s_r$ to $s_i$ ($l\le i< r$). The goal is ...
[ "binary search", "brute force", "data structures", "dsu", "greedy", "sortings" ]
2,500
#include "bits/stdC++.h" using namespace std; #define all(x) (x).begin(),(x).end() typedef long long ll; int main() { ios::sync_with_stdio(0);cin.tie(0); int T;cin>>T; while (T--) { int n,m,i; cin>>n>>m; vector<ll> a(n+1); vector<int> deg(m,2),b(n+1),id(n+1); vector<pair<int,int>> p(m); vector<vector<in...
1687
D
Cute number
\begin{quote} Ran is especially skilled in computation and mathematics. It is said that she can do unimaginable calculation work in an instant. \hfill —Perfect Memento in Strict Sense \end{quote} Ran Yakumo is a cute girl who loves creating cute Maths problems. Let $f(x)$ be the minimal square number \textbf{strictly...
What is the range of the answer? How to solve it in $O(na_n)$? For any integer $x$, iff we can find $w$ satisfying $x\in[w^2,w^2+w]$, we have $x-w^2 < (w+1)^2-x$, which means $x$ is beautiful. Define $f(x)=w$. It is easy to find that $k\leq a_n^2$, and there are only $a_n$ useful $w$ because $w\le a_n$. Enumerate $f(a_...
[ "binary search", "brute force", "data structures", "dsu", "implementation", "math" ]
2,900
#include <bits/stdC++.h> using namespace std; typedef long long ll; #define all(x) (x).begin(),(x).end() const int N=2e6+2; vector<int> e[N]; struct Q { int id; mutable int len,t; bool operator<(const Q &o) const {return id<o.id;} }; int main() { ios::sync_with_stdio(0);cin.tie(0); cout<<setiosflags(ios::fixed)<<s...
1687
E
Become Big For Me
\begin{quote} Come, let's build a world where even the weak are not forgotten! \hfill —Kijin Seija, Double Dealing Characters \end{quote} Shinmyoumaru has a mallet that can turn objects bigger or smaller. She is testing it out on a sequence $a$ and a number $v$ whose initial value is $1$. She wants to make $v = \gcd\l...
Consider the Inclusion-Exclusion Principle. Let $f_p(x)$ be the maximum integer satisfying $p^{f_p(x)}|x$. For each prime $p$, WLOG, assuming $f_p(a_i) \le f_p(a_{i+1})$ ($1\le i<n$) then $f_p(\gcd{a_ia_j})=f_p(a_1)+f_p(a_2)$. Consider the Inclusion-Exclusion Principle: $k\text{-th}\min{S}=\sum\limits_{\varnothing\ne T...
[ "combinatorics", "constructive algorithms", "greedy", "math", "number theory" ]
3,500
#pragma GCC target("popcnt") #include "bits/stdC++.h" using namespace std; typedef unsigned int ui; typedef long long ll; #define all(x) (x).begin(),(x).end() namespace Prime { typedef unsigned int ui; typedef unsigned long long ll; const int N=1e6+2; ui pr[N],mn[N],phi[N],cnt; int mu[N]; void init_prime() { u...
1687
F
Koishi's Unconscious Permutation
\begin{quote} As she closed the Satori's eye that could read minds, Koishi gained the ability to live in unconsciousness. Even she herself does not know what she is up to. \hfill — Subterranean Animism \end{quote} Koishi is unconsciously permuting $n$ numbers: $1, 2, \ldots, n$. She thinks the permutation $p$ is \tex...
How Elegia's mind works? We call a permutation $p$ of length $n-s$ is good if $\forall i\in[1,n-s-1],p_i+1\not=p_{i+1}$. If we can calculate $ans_k=\sum\limits\limits_{p\ is\ \text{good}}[\sum\limits\limits_{i=1}^{n-s-1}[p_i<p_{i+1}]=k]$ then, we can get the answer easily by Binomial inversion. So we only need to focus...
[ "fft", "math" ]
3,500
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <chrono> #include <random> #include <functional> #include <vector> #define LOG(FMT...) fprintf(stderr, FMT) using namespace std; typedef long long ll; typedef unsigned long long ull; const int P = 998244353, R = 3; const in...
1688
A
Cirno's Perfect Bitmasks Classroom
\begin{quote} Even if it's a really easy question, she won't be able to answer it \hfill — Perfect Memento in Strict Sense \end{quote} Cirno's perfect bitmasks classroom has just started! Cirno gave her students a positive integer $x$. As an assignment, her students need to find the \textbf{minimum positive} integer ...
Consider $x=2^k$ and $x\ne 2^k$ separately. Let $p_i$ be the $i$-th bit of $x$, $q_i$ be the $i$-th bit of $y$ (both indexed from $0$). $x\ \texttt{and}\ y > 0\Leftrightarrow \exists i,\ p_i= q_i = 1$. $x\ \texttt{xor}\ y > 0\Leftrightarrow \exists i,\ p_i\ne q_i$. To satisfy the first condition, find the minimum integ...
[ "bitmasks", "brute force" ]
800
for T in range(int(input())): x=int(input()) y=x&-x while (x==y or (x&y)==0): y+=1 print(y)
1688
B
Patchouli's Magical Talisman
\begin{quote} She is skilled in all kinds of magics, and is keen on inventing new one. \hfill —Perfect Memento in Strict Sense \end{quote} Patchouli is making a magical talisman. She initially has $n$ magical tokens. Their magical power can be represented with \textbf{positive} integers $a_1, a_2, \ldots, a_n$. Patch...
What if there is at least one odd integer? How to produce an odd integer? Let $g(x)$ be the maximum integer satisfying $2^{g(x)}|x$. A greedy solution is to make one integer odd integer, and plus it to other even integers. Let $f(a)$ be the answer of an sequence ${a_n}$. We can find that: $f(a)=\begin{cases}\sum[g (a_i...
[ "bitmasks", "constructive algorithms", "greedy", "sortings" ]
800
//这回只花了45min就打完了。 #include "bits/stdC++.h" using namespace std; #define all(x) (x).begin(),(x).end() int main() { ios::sync_with_stdio(0);cin.tie(0); int T; cin>>T; while (T--) { int n,r; cin>>n; vector<int> a(n); for (int &x:a) cin>>x,x=__builtin_ffs(x)-1; r=max(*min_element(all(a))-1,0); for (int x:a...
1688
C
Manipulating History
\begin{quote} As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness. \hfill —Perfect Memento in Strict Sense \end{quote} Keine has the ability to manipulate history. The history of Gensokyo is a string $s$ \textbf{of length $1$ initially}. To fix the chao...
You do not need to know anything about string matching or other algorithms. Why the initial string consists of only one letter? Why the answer is unique if there is at least one answer? What if each string in the input data consist of one letter? Parity. Let $t$ be the unshuffled operation sequence. Consider a single l...
[ "constructive algorithms", "greedy", "strings" ]
1,700
_=int(input()) for __ in range(_): n=2*int(input())+1 a=[0 for i in range(26)] for i in range(n): s=input() for c in s: a[ord(c)-ord('a')]+=1 cnt=0 for i in range(26): if (a[i]%2==1): print(chr(i+ord('a'))) cnt+=1 if cnt!=1: print("fake problem")
1689
A
Lex String
Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters. Recently, Kuznecov has found two strings, $a$ and $b$, of lengths $n$ and $m$ respectively. They consist of lowercase English letters and \textbf{no character is contained in both strings}. Let another string $c$ be initially ...
Greedily take the smallest character in both strings. What's the exception to this? We can't take the smallest character in both strings when we've already took $k$ elements from the string we chose. Denote $A$ as the number of characters we've took from string $a$ in the last few consecutive moves and denote $B$ the s...
[ "brute force", "greedy", "implementation", "sortings", "two pointers" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0); int t; cin>>t; while (t--) { int n,m,k; cin>>n>>m>>k; string a,b,c; cin>>a>>b; sort(a.begin(),a.end(),greater<char>()); sort(b.begin(),b.end(),gr...
1689
B
Mystic Permutation
Monocarp is a little boy who lives in Byteland and he loves programming. Recently, he found a permutation of length $n$. He has to come up with a mystic permutation. It has to be a new permutation such that it differs from the old one in each position. More formally, if the old permutation is $p_1,p_2,\ldots,p_n$ and...
When is it impossible to find such permutation? It is impossible only for $n=1$. In every other case, iterate over each position in order from $1$ to $n$ and take the smallest available number. What's the exception to this? The exception is the last two elements. We can always take the smallest available number for eac...
[ "data structures", "greedy" ]
900
#include <bits/stdc++.h> using namespace std; int t,n,A[1010],B[1010]; int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d",&A[i]); B[i] = i; } if(n==1) { printf("-1\n"); ...
1689
C
Infected Tree
Byteland is a beautiful land known because of its beautiful trees. Misha has found a binary tree with $n$ vertices, numbered from $1$ to $n$. A binary tree is an acyclic connected bidirectional graph containing $n$ vertices and $n - 1$ edges. Each vertex has a degree at most $3$, whereas the root is the vertex with th...
We always delete a vertex directly connected to an infected one. Use dp. Let $u_1,u_2,...,u_k$ be the sequence of removed vertices such that the infection cannot spread anymore. If vertex $u_i$ was never directly connected to an infected vertex, then we could have deleted its parent instead of $u_i$ and we would have g...
[ "dfs and similar", "dp", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; vector<vector<int>> g(300005); int ch[300005],dp[300005]; void dfs(int p, int q) { ch[p]=1,dp[p]=0; int s=0; for (auto it : g[p]) if (it!=q) { dfs(it,p); s+=dp[it]; ch[p]+=ch[it]; } for (auto it : g[p]) if (it!=q) { dp[p...
1689
D
Lena and Matrix
Lena is a beautiful girl who likes logical puzzles. As a gift for her birthday, Lena got a matrix puzzle! The matrix consists of $n$ rows and $m$ columns, and each cell is either black or white. The coordinates $(i,j)$ denote the cell which belongs to the $i$-th row and $j$-th column for every $1\leq i \leq n$ and $1...
There are not a lot of useful black squares. Consider this algorithm: iterate over all squares in the matrix and find the most distant black square. Let's find out how to do that efficiently. In fact, only 4 (not necessarily distinct) black squares will be useful: one square which minimizes $i-j$, one square which maxi...
[ "data structures", "dp", "geometry", "shortest paths" ]
1,900
#include <bits/stdc++.h> using namespace std; char tab[1003][1003]; pair<int,int> a={-1,-1},b={-1,-1},c={-1,-1},d={-1,-1}; int main() { ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0); int t; cin>>t; while (t--) { a={-1,-1},b={-1,-1},c={-1,-1},d={-1,-1}; int...
1689
E
ANDfinity
Bit Lightyear, to the ANDfinity and beyond! After graduating from computer sciences, Vlad has been awarded an array $a_1,a_2,\ldots,a_n$ of $n$ non-negative integers. As it is natural, he wanted to construct a graph consisting of $n$ vertices, numbered $1, 2,\ldots, n$. He decided to add an edge between $i$ and $j$ if...
Increase every $0$ by $1$ initially. Check if the answer is $0$: check whether the graph is already connected. Check if the answer is $1$. If the answer is not $0$ or $1$, then it is $2$. Firslty, let's understand how to check whether the graph induced by some array $b$ is connected in $O(n \ log \ max \ b_i)$. We crea...
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,500
#include <bits/stdc++.h> using namespace std; int a[2005]; vector<vector<int>> g(32); bool vis[32]; void dfs(int p) { if (vis[p]) return; vis[p]=1; for (auto it : g[p]) dfs(it); } bool connected(int n) { int m=0; for (int i=0;i<n;i++) if (a[i]==0) return false; for (int i=0;i<n;i++) m|=a[i...
1690
A
Print a Pedestal (Codeforces logo?)
Given the integer $n$ — the number of available blocks. You must use \textbf{all} blocks to build a pedestal. The pedestal consists of $3$ platforms for $2$-nd, $1$-st and $3$-rd places respectively. The platform for the $1$-st place must be \textbf{strictly} higher than for the $2$-nd place, and the platform for the ...
In the $n \le 10^5$ constraints, the problem can be solved by brute force: we will go through the value for $h_1$ (the height for the first place), and then select suitable values for $h_2$ and $h_3$. Since $h_2 > h_3$, we divide the remaining $n - h_1$ blocks equally between $h_2$ and $h_3$. If it turns out that $h_2 ...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { int n; cin >> n; for (int a = 3; a < n; a++) { int c = (n - a) / 2; int b = n - a -...
1690
B
Array Decrements
Kristina has two arrays $a$ and $b$, each containing $n$ non-negative integers. She can perform the following operation on array $a$ any number of times: - apply a decrement to each non-zero element of the array, that is, replace the value of each element $a_i$ such that $a_i > 0$ with the value $a_i - 1$ ($1 \le i \l...
For all elements of the arrays to become equal after subtraction of units, $a_i>=b_i$ for $1 \le i \le n$ must be satisfied. In addition, if there exists $b_i > 0$, then the equality $a_i = b_i$ can be obtained only by subtracting exactly $a_i - b_i$ units from $a_i$. Since the equality $a_i = b_i$ must be satisfied fo...
[ "greedy", "implementation" ]
800
#include<bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int inf = 1e9 + 7; bool equals(vector<int>&a, vector<int>&b, int n){ int dif = inf; forn(i, n){ if(b[i] != 0) dif = min(dif, a[i] - b[i]); } if(dif < 0) return false; if(dif == inf) ...
1690
C
Restoring the Duration of Tasks
Recently, Polycarp completed $n$ successive tasks. For each completed task, the time $s_i$ is known when it was given, no two tasks were given at the same time. Also given is the time $f_i$ when the task was completed. For each task, there is an unknown value $d_i$ ($d_i>0$) — \textbf{duration of task execution}. It ...
Accordingly, as it was said in the task, we put all tasks into the queue in the order of their arrival, then we fix the time at the beginning as $cur\_time = 0$. So, while there is a task in the queue, we proceed as follows: Take the task from the queue. Take as time the maximum from the current and from the arrival ti...
[ "data structures", "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) void solve() { int n; cin >> n; int s[n]; int f[n]; for (int i = 0; i < n; ++i) { cin >> s[i]; } for (int i = 0; i < n; ++i) { cin >> f[i]; ...
1690
D
Black and White Stripe
You have a stripe of checkered paper of length $n$. Each cell is either white or black. What is the minimum number of cells that must be recolored from white to black in order to have a segment of $k$ consecutive black cells on the stripe? If the input data is such that a segment of $k$ consecutive black cells alread...
To obtain a segment of $k$ cells of black color, we need to paint all the white cells of the segment black. Then go through all the segments of length $k$ (there are only $n - k$) and choose such a segment among them that the number of white cells on it is minimal. You can quickly find out the number of white cells in ...
[ "implementation", "two pointers" ]
1,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n, k; cin >> n >> k; string s; cin >> s; vector<int> w(n + 1); for (int i = 1; i <= n; i++) w[i]...
1690
E
Price Maximization
A batch of $n$ goods ($n$ — an even number) is brought to the store, $i$-th of which has weight $a_i$. Before selling the goods, they must be packed into packages. After packing, the following will be done: - There will be $\frac{n}{2}$ packages, each package contains exactly two goods; - The weight of the package tha...
Note that we do not need to consider the numbers $x \ge k$, we are only interested in the remainder of the division of $x$ by $k$, and we simply add the value $\left \lfloor\frac{x}{k}\right\rfloor$ to the answer. We get an array $a$, where $a_i < k$. Let's sort it and greedily type index pairs $i < j$ such that $a_i +...
[ "binary search", "greedy", "math", "two pointers" ]
1,500
#include<bits/stdc++.h> #define len(s) (int)s.size() using namespace std; using ll = long long; void solve(){ int n, k; cin >> n >> k; vector<ll>a(n); ll sum = 0; for(int i = 0; i < n; i++) { cin >> a[i]; sum += a[i] / k; a[i] = a[i] % k; } sort(a.begin(), a.end(), ...
1690
F
Shifting String
Polycarp found the string $s$ and the permutation $p$. Their lengths turned out to be the same and equal to $n$. A permutation of $n$ elements — is an array of length $n$, in which every integer from $1$ to $n$ occurs exactly once. For example, $[1, 2, 3]$ and $[4, 3, 5, 1, 2]$ are permutations, but $[1, 2, 4]$, $[4, ...
To begin with, let's understand why the string will return to its original form. In fact, the graph that the permutation sets consists of simple cycles and it turns out that after a certain number of operations, each character will return to its place. Consider each cycle as a string that is cyclically shifted every tu...
[ "graphs", "math", "number theory", "strings" ]
1,700
def gcd(a, b): if b == 0: return a; return gcd(b, a % b) def shift(s): for i in range(1, len(s) + 1): if s == s[i:] + s[:i]: return i def solve(): n = int(input()) s = input() p = [int(x)-1 for x in input().split()] used = [False] * n ans = 1 ...
1690
G
Count the Trains
There are $n$ of independent carriages on the rails. The carriages are numbered from left to right from $1$ to $n$. The carriages are not connected to each other. The carriages move to the left, so that the carriage with number $1$ moves ahead of all of them. The $i$-th carriage has its own engine, which can accelerat...
In the set we will keep the indices that start the trains. That is, if the array $v$ - the real speeds of the carriages, then we will store in the network such values $2 \le i$ that $v[i] < v[i-1]$. As well as the value of $0$. Thus, the size of the set -is the answer to the problem. Consider now the operation to reduc...
[ "binary search", "data structures", "greedy", "sortings" ]
2,000
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<int> a(n); set<int> tmp; for (int i = 0; i < n; i++) { cin >> a[...
1691
A
Beat The Odds
Given a sequence $a_1, a_2, \ldots, a_n$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $2$ consecutive elements is even.
The sum of an odd integer and an even integer is an odd integer. So, you can't have both even and odd elements in the array for the sum of every two consecutive elements to be even. Hence, the final array should only contain all even or all odd elements. Hence, we will remove either all odd elements or all even element...
[ "brute force", "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; int num_odd = 0; for (auto x : a) if (x & 1) num_odd++; cout << min(num_odd, n - num_odd) << endl; } return 0; }
1691
B
Shoe Shuffling
A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object. There are $n$ students in the class, and you are given an array $s$ in \textbf{non-decreasing} order, wh...
We can observe that the number of pairs of shoes greater than their size is limited for any student. So if student $j$ wears shoes that are greater than their size, then some student $i$ who has a size greater than student $j$ will compromise their size. So say a valid shuffling exists where a student gets shoes of siz...
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
1,000
#include <bits/stdc++.h> using namespace std; #define ll long long typedef vector<ll> vll; #define io \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL) int main() { io; ll tc; cin >> tc; while (tc--) { ll n; ...
1691
C
Sum of Substrings
You are given a binary string $s$ of length $n$. Let's define $d_i$ as the number whose decimal representation is $s_i s_{i+1}$ (possibly, with a leading zero). We define $f(s)$ to be the sum of all the valid $d_i$. In other words, $f(s) = \sum\limits_{i=1}^{n-1} d_i$. For example, for the string $s = 1011$: - $d_1 ...
We can observe that for any string $s$, $F(s)$ can also be written as: $F(s) = 10\times s_1 + 11 \times s_2 + 11 \times s_3 \dots 11 \times s_{n-1} + 1 \times s_n$ Now, in order to minimize the value of $F(s)$, we would want to put the 1s at position $n$ first, then at position $1$ and then anywhere in the middle of th...
[ "brute force", "constructive algorithms", "greedy", "math", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; string s; cin >> s; int ones = 0, p1_first = n, p1_last = -1; for (int p = 0; p < n; p++) { if (s[p] != '1') ...
1691
D
Max GEQ Sum
You are given an array $a$ of $n$ integers. You are asked to find out if the inequality $$\max(a_i, a_{i + 1}, \ldots, a_{j - 1}, a_{j}) \geq a_i + a_{i + 1} + \dots + a_{j - 1} + a_{j}$$ holds for all pairs of indices $(i, j)$, where $1 \leq i \leq j \leq n$.
Let's look at the problem from the perspective of each $a_i$. We want to check whether the sum of the subarrays, where $a_i$ is the maximum element, exceeds $a_i$ or not. Firstly, we must find out in which subarrays is $a_i$ the maximum. This involves finding the previous greater element index and the next greater elem...
[ "binary search", "constructive algorithms", "data structures", "divide and conquer", "implementation", "two pointers" ]
1,800
#include <bits/stdc++.h> typedef long long ll; using namespace std; const ll ninf = -1e15; vector<int> nextGreater(vector<ll>& arr, int n) { stack<int> s; vector<int> result(n, n); for (int i = 0; i < n; i++) { while (!s.empty() && arr[s.top()] < arr[i]) { result[s.top()] = i; s.pop(); } s.p...
1691
E
Number of Groups
You are given $n$ colored segments on the number line. Each segment is either colored red or blue. The $i$-th segment can be represented by a tuple $(c_i, l_i, r_i)$. The segment contains all the points in the range $[l_i, r_i]$, inclusive, and its color denoted by $c_i$: - if $c_i = 0$, it is a red segment; - if $c_i...
We will be using the starting and ending points of different segments to count the final answer. We maintain a Union-Find data structure (DSU) on size $n$ corresponding to the $n$ segments given as input. We store all the starting and ending points in a set. (example: If $2$ segments are $(0,10)$ and $(11, 12)$, we sto...
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy", "sortings" ]
2,300
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll int #define pb push_back #define _ << ' ' << #define tm gfewnignefgo #define INF (int)1e9 #define mod 998244353 #define maxn 200010 ll i, i1, j, k, k1, t, n, m, res, flag[10], a, b; ll c[maxn], l[maxn], r[maxn], pr[maxn], sz[...
1691
F
K-Set Tree
You are given a tree $G$ with $n$ vertices and an integer $k$. The vertices of the tree are numbered from $1$ to $n$. For a vertex $r$ and a subset $S$ of vertices of $G$, such that $|S| = k$, we define $f(r, S)$ as the size of the smallest rooted subtree containing all vertices in $S$ when the tree is rooted at $r$. ...
Our task is to calculate $\sum_{R \in V} \sum_{S \subseteq V, |S| = k} f(R, S)$ We will calculate our answer using dynamic programming over the trees. In this technique, we will calculate some properties for each sub-tree and eventually get those properties for the entire tree. The first property that we want to calcul...
[ "combinatorics", "dfs and similar", "dp", "math", "trees" ]
2,500
#include <iostream> #include <vector> using namespace std; using ll = long long; const ll MOD = 1e9 + 7; struct Comb { vector<ll> fac; vector<ll> invfac; ll n; Comb(ll n) { this->n = n; fac.resize(n + 1, 0); invfac.resize(n + 1, 0); fac[0] = 1; for (...
1692
A
Marathon
You are given four \textbf{distinct} integers $a$, $b$, $c$, $d$. Timur and three other people are running a marathon. The value $a$ is the distance that Timur has run and $b$, $c$, $d$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.
We can re-word the problem to count the number of numbers from $b, c, d$ that are larger than $a$. A possible way to do this is by keeping a variable that gets incremented every time we checked using the if statement whether a number is larger than $a$. The complexity is $\mathcal{O}(1)$.
[ "implementation" ]
800
t = int(input()) for test in range(t): a,b,c,d = map(int, input().split()) rs = (b > a) + (c > a) + (d > a) print(rs)
1692
B
All Distinct
Sho has an array $a$ consisting of $n$ integers. An operation consists of choosing two distinct indices $i$ and $j$ and removing $a_i$ and $a_j$ from the array. For example, for the array $[2, 3, 4, 2, 5]$, Sho can choose to remove indices $1$ and $3$. After this operation, the array becomes $[3, 2, 5]$. Note that aft...
Note that the size of the array doesn't change parity, since it always decreases by $2$. Let's count the number of distinct elements, call it $x$. If $x$ is the same parity as $n$ (the length of the array), then we can make sure all of these $x$ distinct elements stay in the array by removing two elements at a time. Ot...
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> typedef long long ll; using namespace std; void solve() { int n, x; cin >> n; set<int> a; for(int i = 0; i < n; i++) { cin >> x; a.insert(x); } if((n-a.size())%2 == 0) { cout << a.size() << endl; } else { cout << a.size()-1 << endl; } } int32_t main(){ int t = 1; cin >>...
1692
C
Where's the Bishop?
Mihai has an $8 \times 8$ chessboard whose rows are numbered from $1$ to $8$ from top to bottom and whose columns are numbered from $1$ to $8$ from left to right. Mihai has placed exactly one bishop on the chessboard. \textbf{The bishop is not placed on the edges of the board.} (In other words, the row and column of t...
There are many ways to solve the problem. One way is to look for the following pattern: $\texttt{X.X}\\\texttt{.X.}\\\texttt{X.X}$ You can also look at the positions of the two diagonals and intersect them, but it requires more implementation. Time complexity: $\mathcal{O}(1)$ per testcase.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { char g[9][9]; for (int i = 1; i <= 8; i++) { for (int j = 1; j <= 8; j++) { cin >> g[i][j]; } } for (int i = 2; i <= 7; i++) { for (int j = 2; j <= 7; j++) { if (g[i][j] == '#' && g[i - 1][j - 1] == '#' && g[i - 1][j + 1] == '#' && g[i + 1][...
1692
D
The Clock
Victor has a 24-hour clock that shows the time in the format "HH:MM" (00 $\le$ HH $\le$ 23, 00 $\le$ MM $\le$ 59). He looks at the clock every $x$ minutes, and the clock is currently showing time $s$. How many \textbf{different} palindromes will Victor see in total after looking at the clock every $x$ minutes, the fir...
Note that Victor looks at the clock forever, but there are only at most $1440$ different times the clock can show (because there are $1440$ different minutes in a day). So we only have to check the first $1440$ times Victor sees, and count the palindromes (you can check a few more just to be safe, but they will repeat ...
[ "brute force", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int a[5] = {600, 60, 0, 10, 1}; int good[16] = {0, 70, 140, 210, 280, 350, 601, 671, 741, 811, 881, 951, 1202, 1272, 1342, 1412}; void solve() { string s; cin >> s; int x; cin >> x; int tot = 0; for (int i = 0; i < 5; i++) { tot += (int)(s[i] - '0') * a[i]; } s...
1692
E
Binary Deque
Slavic has an array of length $n$ consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to $s$ after performing all the operations? In case the sum ...
Note that the remaining array is a subarray of the original array. There are many ways to approach the problem. Here is one solution, which the main solution uses: Compute prefix sums on the array, so we can find out the value of $a_l + \dots + a_r$ quickly. Let's iterate through the left endpoint $l$ from $1$ to $n$. ...
[ "binary search", "implementation", "two pointers" ]
1,200
#include "bits/stdc++.h" using namespace std; #define ll long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1692
F
3SUM
Given an array $a$ of positive integers with length $n$, determine if there exist three \textbf{distinct} indices $i$, $j$, $k$ such that $a_i + a_j + a_k$ ends in the digit $3$.
Since we only care about the last digit of the sum $a_i + a_j + a_k$, we can ignore all numbers other than the last digits of the elements of $a$. (For example, we can consider $[20, 22, 19, 84]$ to be the same as $[0, 2, 9, 4]$.) Now note that if a number appears more than $3$ times in the array, we can ignore all cop...
[ "brute force", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int cnt[10] = {}; for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x % 10]++; } vector<int> v; for (int i = 0; i < 10; i++) { for (int j = 0; j < min(cnt[i], 3); j++) { v.push_back(i); } } int m = v.size(); for (in...
1692
G
2^Sort
Given an array $a$ of length $n$ and an integer $k$, find the number of indices $1 \leq i \leq n - k$ such that the subarray $[a_i, \dots, a_{i+k}]$ with length $k+1$ (\textbf{not} with length $k$) has the following property: - If you multiply the first element by $2^0$, the second element by $2^1$, ..., and the ($k+1...
Note that $2^x \cdot a_i < 2^{x+1} \cdot a_{i+1}$ is the same as $a_i < 2a_{i+1}$, since we can divide by $2^x$. This means that we only need to check whether $a_i < 2a_{i+1}$ for each pair of adjacent elements. Let's consider as an example $[20,22,19]$. Note that $20 < 2 \cdot 22$ and $22 < 2 \cdot 19$, so if you mult...
[ "data structures", "dp", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n, k; cin >> n >> k; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int ok[n]; for (int i = 0; i < n - 1; i++) { ok[i] = (a[i] < 2 * a[i + 1]); } int tot = 0; for (int i = 0; i <...
1692
H
Gambling
Marian is at a casino. The game at the casino works like this. Before each round, the player selects a number between $1$ and $10^9$. After that, a dice with $10^9$ faces is rolled so that a random number between $1$ and $10^9$ appears. If the player guesses the number correctly their total money is doubled, else thei...
There are several solutions. Here is one. If we fix the value of $a$, then let's make a new array $b$ as follows: $b_i = 1$ if $\mathrm{round}_i = a$, and $b_i = -1$ otherwise. Then the total amount of money earned will just be $2^{b_l + \dots + b_r}$, so we only need to maximize $b_l + \dots + b_r$. In other words, we...
[ "data structures", "dp", "greedy", "math" ]
1,700
#include "bits/stdc++.h" using namespace std; #define ll long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1693
A
Directional Increase
We have an array of length $n$. Initially, each element is equal to $0$ and there is a pointer located on the first element. We can do the following two kinds of operations any number of times (possibly zero) in any order: - If the pointer is not on the last element, increase the element the pointer is currently on b...
First of all the sum of the elements has to be $0$ because the pointer has to end up on the first element. Denote the number of times you do the first operation while the pointer is on the $i$-th element as $b_i$. And the number of times you do the second operation while the pointer is on the $i$-th element as $c_i$. $...
[ "greedy" ]
1,300
//In the name of God #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 100; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n, t, a[maxn]; long long ps[maxn]; int main(){ fast_io; cin >> t; while(t--){ cin >> n; for(int i = 1; i <= n; i++){ cin >> a[i]; ps[i...
1693
B
Fake Plastic Trees
We are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is the vertex $1$ and the parent of the vertex $v$ is $p_v$. There is a number written on each vertex, initially all numbers are equal to $0$. Let's denote the number written on the vertex $v$ as $a_v$. For each $v$, ...
Lemma 1. You won't perform the operation on a particular vertex more than once. Because you could merge the operations. Lemma 2. If you perform the operation on some vertex $v$, you can do it with $c_k = r_v$. If there is another operation that helps this vertex, you can cut the operation into two pieces and merge one ...
[ "dfs and similar", "dp", "greedy", "trees" ]
1,700
# include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 2e5 + 10; int t, n, l[N], r[N], ans; vector <int> adj[N]; ll DFS(int v){ ll sum = 0; for (int u : adj[v]){ sum += DFS(u); } if (sum < ll(l[v])){ ++ ans; return r[v]; } return min(ll(r[v]), sum); } int main(){ ios::sync...
1693
C
Keshi in Search of AmShZ
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $n$ cities in Italy indexed from $1$ to $n$ and $m$ \textbf{directed} roads indexed from $1$ to $m$. Initially, Keshi is located in the city $1$ and wants to go to AmShZ's house in the city $n$. Since Keshi doesn't know the map of Italy, AmShZ ...
Define $dis_v$ as the minimum number of days needed to reach city $n$ from city $v$. $dis_n = 0$. We have to assume that Keshi will always choose the worst reachable city, that is the city with maximum $dis$. For each node $v$ we kind of have to choose $nxt_v$ and block all neighbors(outgoing edges) with a distance mor...
[ "graphs", "greedy", "shortest paths" ]
2,300
# include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, m, d[N], dist[N]; priority_queue <pair <int, int> > pq; vector <int> adj[N]; bool mark[N]; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; fill(dist, dist + n + 1, m); while (m --){ int v, u; cin >> v...
1693
D
Decinc Dividing
Let's call an array $a$ of $m$ integers $a_1, a_2, \ldots, a_m$ \textbf{Decinc} if $a$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. - For example, if $a = [3, 2, 4, 1, 5]$, we can remove the decreasing subsequence $[a_1, a_4]$ from $a$ and obtain $a = [2, 4, 5]$, which is incre...
Let's solve the problem for a single subarray. Assume the $i$-th element belongs to the increasing subsequence. Define $dp_{l, i}$ for the interval $[l, i]$ as the maximum value the last element of the decreasing subsequence can have. It's $+\infty$ in case the decreasing subsequence is empty. It's $-\infty$ if the arr...
[ "brute force", "data structures", "divide and conquer", "dp", "greedy" ]
2,800
# include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, a[N], min_r[N], fen[N]; long long ans; stack <int> sk; vector <int> vec[2][N]; void mofen(int pos, int val){ for (pos += 5; pos < N; pos += pos & - pos) fen[pos] = min(fen[pos], val); } int gefen(int pos){ int res = n + 1; for (pos +...
1693
E
Outermost Maximums
Yeri has an array of $n + 2$ non-negative integers : $a_0, a_1, ..., a_n, a_{n + 1}$. We know that $a_0 = a_{n + 1} = 0$. She wants to make all the elements of $a$ equal to zero in the minimum number of operations. In one operation she can do one of the following: - Choose the leftmost maximum element and change it...
Let's calculate for each element of the array, the minimum number of times it needs to change throughout the process. Let's take a look at the first time the $i$-th element is changing. We know that $a_i$ is the maximum number and the elements smaller than $a_i$ haven't changed yet. Denote the maximum element on its le...
[ "data structures", "greedy" ]
3,400
//In the name of God #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const ll maxn = 2e5 + 100; const ll mod = 1e9 + 7; const int inf = 1e9; const ll INF = 1e18; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define file_...
1693
F
I Might Be Wrong
You are given a binary string $S$ of length $n$ indexed from $1$ to $n$. You can perform the following operation any number of times (possibly zero): - Choose two integers $l$ and $r$ ($1 \le l \le r \le n$). Let $cnt_0$ be the number of times 0 occurs in $S[l \ldots r]$ and $cnt_1$ be the number of times 1 occurs in ...
- It's trivial that we only sort with segments with balance $0$. Proof: Imagine we have sorted interval $[l, r]$ and it has $d$ more zeros than it has ones. So this operation costs $d + 1$ coins. $S_l$ has to be $1$ otherwise we could just sort $[l + 1, r]$ with $d$ coins. Now that we know $S_l$ is $1$ there exists som...
[ "binary search", "greedy", "two pointers" ]
3,400
#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> ...
1694
A
Creep
Define the score of some binary string $T$ as the absolute difference between the number of zeroes and ones in it. (for example, $T=$ 010001 contains $4$ zeroes and $2$ ones, so the score of $T$ is $|4-2| = 2$). Define the creepiness of some binary string $S$ as the maximum score among all of its prefixes (for example...
Define the minimum possible creepiness of the string as $ans$. We want to show that $ans$ is equal to $max(1, |a - b|)$. Creepiness of $S[1 \ldots 1]$ is equal to $1$ and creepiness of $S[1 \ldots n]$ is equal to $|a - b|$ so $max(1, |a - b|) \le ans$. The way to make a string with creepiness equal to $max(1, |a - b|)$...
[ "greedy", "implementation" ]
800
# include <bits/stdc++.h> using namespace std; int t, A, B; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; while (t --){ cin >> A >> B; for (int i = 0; i < min(A, B); ++ i) cout << "01"; for (int i = 0; i < abs(A - B); ++ i) cout << (A < B ? 1 : 0); cout << '\n'; } retur...
1694
B
Paranoid String
Let's call a binary string $T$ of length $m$ indexed from $1$ to $m$ \textbf{paranoid} if we can obtain a string of length $1$ by performing the following two kinds of operations $m-1$ times in any order : - Select any substring of $T$ that is equal to 01, and then replace it with 1. - Select any substring of $T$ that...
We want to show that a binary string $T$ of length $m$ is paranoid if and only if $m = 1$ or ($1 < m$ and $S[m] \neq S[m - 1]$). In the case of $S[m - 1] = S[m]$: We can never delete the last two characters because they will always remain equal. So $S$ is not paranoid. In the case of $S[m - 1] \neq S[m]$: If $m = 2$, w...
[ "constructive algorithms", "greedy" ]
1,200
# include <bits/stdc++.h> using namespace std; int t, n; string S; long long ans; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; while (t --){ cin >> n >> S, ans = n; for (int i = 1; i < n; ++ i) if (S[i] != S[i - 1]) ans += i; cout << ans << '\n'; } return 0; }
1695
A
Subrectangle Guess
Michael and Joe are playing a game. The game is played on a grid with $n$ rows and $m$ columns, \textbf{filled with distinct integers}. We denote the square on the $i$-th ($1\le i\le n$) row and $j$-th ($1\le j\le m$) column by $(i, j)$ and the number there by $a_{ij}$. Michael starts by saying two numbers $h$ ($1\le ...
Note that for any rectangle size, we can always choose an $h$ by $w$ rectangle that contains the maximum element in the grid (which is unique). So in order for Michael to ensure that he can win, he needs to make $h$ and $w$ big enough such that every $h$ by $w$ rectangle contains the maximum element in the grid. Let $(...
[ "games" ]
800
#include <bits/stdc++.h> using namespace std; int grid[45][45]; int main() { int num_tests; cin >> num_tests; for (int test = 0; test < num_tests; ++test) { int n, m; cin >> n >> m; int max_i = 0, max_j = 0; for (int i = 0; i < n; ++i) for (int j = 0;...
1695
B
Circle Game
Mike and Joe are playing a game with some stones. Specifically, they have $n$ piles of stones of sizes $a_1, a_2, \ldots, a_n$. These piles are arranged in a circle. The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $1$. Formally, if ...
Note that since all piles are initially nonempty, the game will not end for the first $n$ turns, because on each of those turns, a player will be removing from a nonempty pile. If $n$ is odd, Mike can remove all of the stones from the first pile. Then, on the $n+1$th turn (the first turn where the game can end), Joe wi...
[ "games", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int num_tests; cin >> num_tests; for (int test = 0; test < num_tests; ++test) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; if (n % 2 == 1) { cout << "Mike\n...
1695
C
Zero Path
You are given a grid with $n$ rows and $m$ columns. We denote the square on the $i$-th ($1\le i\le n$) row and $j$-th ($1\le j\le m$) column by $(i, j)$ and the number there by $a_{ij}$. All numbers are equal to $1$ or to $-1$. You start from the square $(1, 1)$ and can move one square down or one square to the right ...
Note that if $n+m$ is even, then the sum of any path from the top left to bottom right will be odd, and therefore nonzero. So in this case, there is no solution. Otherwise, every path from top left to bottom right will have even sum. For each position $(i, j)$ in the grid, we define $max_{ij}$ to be the maximum possibl...
[ "brute force", "data structures", "dp", "graphs", "greedy", "shortest paths" ]
1,700
#include <bits/stdc++.h> using namespace std; #define N 1010 int grid[N][N], mn[N][N], mx[N][N]; int main() { int num_tests; cin >> num_tests; for (int test = 0; test < num_tests; ++test) { int n, m; cin >> n >> m; for(int i = 0; i < n; ++i) for(int j = 0; j ...
1695
D1
Tree Queries (Easy Version)
\textbf{The only difference between this problem and D2 is the bound on the size of the tree.} You are given an unrooted tree with $n$ vertices. There is some hidden vertex $x$ in that tree that you are trying to find. To do this, you may ask $k$ queries $v_1, v_2, \ldots, v_k$ where the $v_i$ are vertices in the tre...
If $n=1$, then no queries are needed, because there is only one vertex. Otherwise, we need at least one query. If we fix a node $u$, and force it to be a query, we can root the tree at $u$ and do a greedy DFS to compute the answer. Note that because we guarantee that the root is a query, when we are computing the answe...
[ "brute force", "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; #define N 2010 vector<int> tree[N]; int dfs(int i, int p) { int sm = 0, z = 0; for (int j : tree[i]) if (j != p) { int x = dfs(j, i); sm += x; if (x == 0) z++; } return sm + max(0, z - 1); } int main() { ...
1695
D2
Tree Queries (Hard Version)
\textbf{The only difference between this problem and D1 is the bound on the size of the tree.} You are given an unrooted tree with $n$ vertices. There is some hidden vertex $x$ in that tree that you are trying to find. To do this, you may ask $k$ queries $v_1, v_2, \ldots, v_k$ where the $v_i$ are vertices in the tre...
In the previous solution, we forced the root to be a query, because we needed to ensure that for every node $v$, either $v$ was queried, or there was a query outside the subtree of $v$. Notice that if the root has degree $\geq 3$, regardless of whether we query the root, this property still holds. The way we compute va...
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,300
#include <bits/stdc++.h> using namespace std; #define N 200010 vector<int> tree[N]; int dfs(int i, int p) { int sm = 0, z = 0; for (int j : tree[i]) if (j != p) { int x = dfs(j, i); sm += x; if (x == 0) z++; } return sm + max(0, z - 1); } int main() { ...
1695
E
Ambiguous Dominoes
Polycarp and Monocarp are both solving the same puzzle with dominoes. They are given the same set of $n$ dominoes, the $i$-th of which contains two numbers $x_i$ and $y_i$. They are also both given the same $m$ by $k$ grid of values $a_{ij}$ such that $m\cdot k = 2n$. The puzzle asks them to place the $n$ dominoes on ...
We represent the set of dominoes as a graph on $2n$ vertices, where the vertices are the values $1$ to $2n$, and the ith domino represents an edge between $x_i$ and $y_i$. Note that this graph can contain self-loops and duplicate edges. If any of the connected components of the graph contain only one edge, then that me...
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,700
#include <bits/stdc++.h> using namespace std; #define N 600010 vector<pair<int, int>> graph[N]; vector<int> lst; int ans[2][N]; bool used[N], usedEdges[N]; void dfs(int i) { lst.push_back(i); if (!used[i]) { used[i] = true; for (pair<int, int> p : graph[i]) if (!usedEd...
1696
A
NIT orz!
NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $\operatorname{or} z$. Can you solve this problem too? You are given a 1-indexed array of $n$ integers, $a$, and an integer $z$. You can do the follow...
How many operations will we perform? At most one. Why? Suppose we can only perform exactly one operation. In this case the answer is $S=\max_{1\le i\le n}(a_i\mathrm{\ or\ }z)$. In fact, we can prove that this is the answer. Define $a_i'$ as the value of $a_i$ after some operations. It suffices to prove the answer will...
[ "bitmasks", "greedy" ]
800
null
1696
B
NIT Destroys the Universe
For a collection of integers $S$, define $\operatorname{mex}(S)$ as the smallest non-negative integer that does not appear in $S$. NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times. The universe can be represen...
How many operations will we perform? At most two. Why? How to check if the array can be destroyed in $0$ or $1$ operations? The answer is at most $2$, because doing the operation on $[1,n]$ at most twice will always work. (If the array contains at least one zero, we need $2$ operations. Otherwise we need $1$ operation....
[ "greedy" ]
900
null
1696
C
Fishingprince Plays With Array
Fishingprince is playing with an array $[a_1,a_2,\dots,a_n]$. He also has a magic number $m$. He can do the following two operations on it: - Select $1\le i\le n$ such that $a_i$ is divisible by $m$ (that is, there exists an integer $t$ such that $m \cdot t = a_i$). Replace $a_i$ with \textbf{$m$ copies} of $\frac{a_...
The operation is reversible. (The two operations are reverses of each other.) Try to find a middle state, such that we can turn both $a$ and $b$ into it. Call the first operation "expand" and the second operation "shrink". Keep doing expand on both arrays until we can't do expand anymore, call the resulting arrays $a'$...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,400
null
1696
D
Permutation Graph
A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). You are given a permutation o...
This problem has two different solutions. The first one is more beautiful, but less straight-forward. The solution is $O(n)$. We don't need any data structures. Instead of trying to construct the shortest path from $1$ to $n$, find a "transfer vertex" that we must pass through. We will always pass through the position ...
[ "binary search", "constructive algorithms", "data structures", "divide and conquer", "greedy", "shortest paths" ]
1,900
null
1696
E
Placing Jinas
We say an infinite sequence $a_{0}, a_{1}, a_2, \ldots$ is \textbf{non-increasing} if and only if for all $i\ge 0$, $a_i \ge a_{i+1}$. There is an infinite right and down grid. The upper-left cell has coordinates $(0,0)$. Rows are numbered $0$ to infinity from top to bottom, columns are numbered from $0$ to infinity f...
Try to find out the number of operations we do on a specific cell $(i,j)$, call it $f(i,j)$. Write the recurrence formula for $f(i,j)$. What is $f(i,j)$? $f(i,j)=\binom{i+j}j$ The answer is the sum of $f(i,j)$ over all white cells $(i,j)$. Use some combinatorics formula to speed it up. Let us find out the number of ope...
[ "combinatorics", "math" ]
2,000
null
1696
F
Tree Recovery
Fishingprince loves trees. A tree is a connected undirected graph without cycles. Fishingprince has a tree of $n$ vertices. The vertices are numbered $1$ through $n$. Let $d(x,y)$ denote the shortest distance on the tree from vertex $x$ to vertex $y$, assuming that the length of each edge is $1$. However, the tree wa...
The solution does not contain painful casework and deadly implemention. Suppose we aleady know edge $(i,j)$ exists in the tree. What can we know from it? We can immediately recover the whole tree. Read the hints first to understand the solution better. Construct a graph with $\binom n2$ vertices $(1,2),(1,3),\dots,(n-1...
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs", "trees" ]
2,600
null
1696
G
Fishingprince Plays With Array Again
Suppose you are given a 1-indexed sequence $a$ of non-negative integers, whose length is $n$, and two integers $x$, $y$. In consecutive $t$ seconds ($t$ can be any positive real number), you can do one of the following operations: - Select $1\le i<n$, decrease $a_i$ by $x\cdot t$, and decrease $a_{i+1}$ by $y\cdot t$....
What kind of problem is this problem? Linear programming. Consider the dual. Consider the case when $n=2$. Draw the linear programming on a xOy-coordinate. Try to observe what the answer might be. First we solve the problem with only 1 query on the whole array $A$. This is a linear programming problem: $\text{minimize}...
[ "brute force", "data structures", "geometry", "math" ]
3,300
null