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
1081
G
Mergesort Strikes Back
Chouti thought about his very first days in competitive programming. When he had just learned to write merge sort, he thought that the merge sort is too slow, so he restricted the maximum depth of recursion and modified the merge sort to the following: Chouti found his idea dumb since obviously, this "merge sort" some...
How does "merge" work? What is this "mergesort" actually doing? First, consider how "merge" will work when dealing with two arbitrary arrays. Partition every array into several blocks: find all elements that are larger than all elements before them and use these elements as the start of the blocks. Then, by 'merging' w...
[ "math", "probabilities" ]
3,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second #define SZ 123456 int n,k,MOD,ts[SZ],tn=0; ll inv[SZ],invs[SZ]; ll qp(ll a,ll b) { ll x=1; a%=MOD; while(b) { if(b&1) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } void go(int l,int r,int h) { if(h<=1||l==r) ts...
1081
H
Palindromic Magic
After learning some fancy algorithms about palindromes, Chouti found palindromes very interesting, so he wants to challenge you with this problem. Chouti has got two strings $A$ and $B$. Since he likes palindromes, he would like to pick $a$ as some non-empty palindromic substring of $A$ and $b$ as some non-empty palin...
What will be counted twice? Warning: This editorial is probably new and arcane for ones who are not familiar with this field. If you just want to get a quick idea about the solution, you can skip all the proofs (they're wrapped in spoiler tags). Some symbols: All indices of strings start from zero. $x^{R}$ stands for t...
[ "data structures", "hashing", "strings" ]
3,500
#include <bits/stdc++.h> using namespace std; const int N = 234567; const int LOG = 18; const int ALPHA = 26; const int base = 2333; const int md0 = 1e9 + 7; const int md1 = 1e9 + 9; struct hash_t { int hash0, hash1; hash_t(int hash0 = 0, int hash1 = 0):hash0(hash0), hash1(hash1) { } hash_t operator + (con...
1082
A
Vasya and Book
Vasya is reading a e-book. The file of the book consists of $n$ pages, numbered from $1$ to $n$. The screen is currently displaying the contents of page $x$, and Vasya wants to read the page $y$. There are two buttons on the book which allow Vasya to scroll $d$ pages forwards or backwards (but he cannot scroll outside ...
It is easy to understand that the optimal answer is achieved in one of three cases: Vasya is trying to visit page $y$ without visiting pages $1$ and $n$; Vasya first goes to the page $1$, and then to the page $y$; Vasya first goes to the $n$ page, and then to the $y$ page. In the first case, Vasya can go directly to th...
[ "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; const int INF = int(2e9) + 99; int n, x, y, d; int dist(int x, int y){ return (abs(x - y) + (d - 1)) / d; } int main() { int t; cin >> t; for(int i = 0; i < t; ++i){ cin >> n >> x >> y >> d; int len = abs(x - y); int res = INF; if(...
1082
B
Vova and Trophies
Vova has won $n$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row. The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement a...
Let $r_i$ be the maximal segment of gold cups that begins in the cup $i$. Let $l_i$ be the maximum segment of gold cups that ends in the cup $i$. Also, let the total number of gold cups be $cntG$. Note that it makes no sense to change the cups of the same color. Then let's consider the silver cup, which will change wit...
[ "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; int n; string s; int main() { cin >> n >> s; vector <int> l(n), r(n); for(int i = 0; i < n; ++i){ if(s[i] == 'G'){ l[i] = 1; if(i > 0) l[i] += l[i - 1]; } } for(int i = n - 1; i >= 0; --i){ if(s[i] == 'G'){ r[i] = 1; if(i + 1 < n) r[i] += r[i +...
1082
C
Multi-Subject Competition
A multi-subject competition is coming! The competition has $m$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $n$ candidates. For the $i$-th person he knows subject $s_i$ the candidate specializes in and $r_i$ — a skill level...
At first, it's optimal to take candidates with maximal levels for a fixed subject. At second, if we fix number of participants in each subject for some delegation, then it's always optimal to choose all subjects with positive sum of levels. It leads us to a following solution. Let's divide all candidates by it's $s_i$ ...
[ "greedy", "sortings" ]
1,600
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) int n, m; vector<int> s, r; inline bool read() { if(!(cin >> n >> m)) return false; s.assign(n, 0); r.assign(n, 0); fore(i, 0, n) { assert(cin >> s[i] >> r[i]); s[i]--; }...
1082
D
Maximum Diameter Graph
Graph constructive problems are back! This time the graph you are asked to build should match the following properties. The graph is connected if and only if there exists a path between every pair of vertices. The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in...
Let's construct the graph the following manner. Take all the vertices with $a_i > 1$ and build a bamboo out of them. Surely, all but the end ones will have degree $2$, the diameter now is the number of vertices minus 1. One can show that building the graph any other way won't make the diameter greater. How should we di...
[ "constructive algorithms", "graphs", "implementation" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 1000 + 7; int n; int a[N]; int main() { scanf("%d", &n); forn(i, n) scanf("%d", &a[i]); int sum = 0; forn(i, n) sum += a[i]; if (sum < 2 * n - 2){ puts("NO"); return 0; } vector<int>...
1082
E
Increasing Frequency
You are given array $a$ of length $n$. You can choose one segment $[l, r]$ ($1 \le l \le r \le n$) and integer value $k$ (positive, negative or even zero) and change $a_l, a_{l + 1}, \dots, a_r$ by $k$ each (i.e. $a_i := a_i + k$ for each $l \le i \le r$). What is the maximum possible number of elements with value $c$...
Let $cnt(l, r, x)$ be a number of occurrences of number $x$ in subsegment $[l, r]$. The given task is equivalent to choosing $[l, r]$ and value $d$ such that $ans = cnt(1, l - 1, c) + cnt(l, r, d) + cnt(r + 1, n, c)$ is maximum possible. But with some transformations $ans = cnt(1, n, c) + (cnt(l, r, d) - cnt(l, r, c))$...
[ "binary search", "dp", "greedy" ]
2,000
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) const int INF = int(1e9); int n, c; vector<int> a; inline bool read() { if(!(cin >> n >> c)) return false; a.assign(n, 0); fore(i, 0, n) assert(scanf("%d", &a[i]) == 1); retu...
1082
F
Speed Dial
Polycarp's phone book contains $n$ phone numbers, each of them is described by $s_i$ — the number itself and $m_i$ — the number of times Polycarp dials it in daily. Polycarp has just bought a brand new phone with an amazing speed dial feature! More precisely, $k$ buttons on it can have a number assigned to it (not nec...
The first thing to come to one's mind is dynamic programming on a trie. The most naive of the solutions take $O(S \cdot n^2 \cdot k^2)$, where $S$ is the total length of strings. I'll introduce the faster approach. Let $dp[x][rem][k]$ be the solution for subtree of the vertex $x$ with $rem$ buttons remaining and $k$ is...
[ "dp", "strings", "trees" ]
2,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 500 + 7; const int M = 11; const int INF = 1e9; struct node{ int nxt[10]; int cnt; node(){ memset(nxt, -1, sizeof(nxt)); cnt = 0; } }; node trie[N]; int cnt; int h[N]; void add(string s, int m){...
1082
G
Petya and Graph
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of $n$ vertices and $m$ edges. The weight of the $i$-th vertex is $a_i$. The weight of the $i$-th edge is $w_i$. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet t...
This problem can be reduced to one of well-known flow problems: "Projects and Instruments". In this problem, we have a set of projects we can do, each with its cost, and a set of instruments (each also having some cost). Each project depends on some instruments, and each instrument can be used any number of times. We h...
[ "flows", "graphs" ]
2,400
#include <bits/stdc++.h> using namespace std; typedef long long li; const int N = 2009; const int INF = int(1e9) + 777; struct edge{ int to, f, c; edge () {} edge (int to, int f, int c) : to(to), f(f), c(c) {} }; int n, m; int s, t; vector<edge> edges; vector <int> g[N]; int u[N], cu; void addEdge(int v, int t...
1083
A
The Fair Nut and the Best Path
The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined t...
Let's write on edge with length $l$ number $-l$. Let sum on the path be sum of amounts of gasoline, which can be bought in cities on this path plus sum of the numbers, which were written on its edges. If we don't run out of gasoline on some path, sum on it will be equal to amount of gasoline at the end of way. If we ru...
[ "data structures", "dp", "trees" ]
1,800
null
1083
B
The Fair Nut and Strings
Recently, the Fair Nut has written $k$ strings of length $n$, consisting of letters "a" and "b". He calculated $c$ — the number of strings that are prefixes of at least one of the written strings. \textbf{Every string was counted only one time}. Then, he lost his sheet with strings. He remembers that all written strin...
If $s$ and $t$ are equal, answer is $n$. Let's cut common prefix of $s$ and $t$, and increase answer to its length. Now $s$ starts from "a" and $t$ starts from "b". Let $m$ is new lengths of $s$ and $t$. If string $s$ weren't written, we can change the lexicographically smallest string to $s$, and $c$ will not decrease...
[ "greedy", "strings" ]
2,000
null
1083
C
Max Mex
Once Grisha found a tree (connected graph without cycles) with a root in node $1$. But this tree was not just a tree. A permutation $p$ of integers from $0$ to $n - 1$ is written in nodes, a number $p_i$ is written in node $i$. As Grisha likes to invent some strange and interesting problems for himself, but not alway...
First let's redefine the MEX query more clearly - you need to find what is the maximum $a$, such that all nodes with permutation values up to $a$ lie on the same path. For that you can use just a simple segment tree - in a node of a segment tree you need to store is it true that all nodes with permutation values betwee...
[ "data structures", "trees" ]
2,900
null
1083
D
The Fair Nut's getting crazy
The Fair Nut has found an array $a$ of $n$ integers. We call subarray $l \ldots r$ a sequence of consecutive elements of an array with indexes from $l$ to $r$, i.e. $a_l, a_{l+1}, a_{l+2}, \ldots, a_{r-1}, a_{r}$. No one knows the reason, but he calls a pair of subsegments good if and only if the following conditions ...
Consider O($N^2$) solution: Fix intersection of this segments $L \dots R$. We will call right barrier those integer $Right$, that right border of right segment can be from $R \dots Right$. Also Left barrier is integer, that left border of left segment can be from $Left \dots L$. If we precalculate for each element the ...
[ "data structures", "implementation" ]
3,500
null
1083
E
The Fair Nut and Rectangles
The Fair Nut got stacked in planar world. He should solve this task to get out. You are given $n$ rectangles with vertexes in $(0, 0)$, $(x_i, 0)$, $(x_i, y_i)$, $(0, y_i)$. For each rectangle, you are also given a number $a_i$. Choose some of them that the area of union minus sum of $a_i$ of the chosen ones is maximu...
Let's order rectangles by $x_i$, so $x_1, ..., x_n$ will be increasing. If the $x_1, ..., x_n$ is increasing, $y_1, ..., y_n$ is decreasing, because there are no nested rectangles. Then lets define $dp_i$ as the maximum value, which can be acheived by choosing some subset of first $i$ rectangles which contains the $i$-...
[ "data structures", "dp", "geometry" ]
2,400
null
1083
F
The Fair Nut and Amusing Xor
The Fair Nut has two arrays $a$ and $b$, consisting of $n$ numbers. He found them so long ago that no one knows when they came to him. The Fair Nut often changes numbers in his arrays. He also is interested in how similar $a$ and $b$ are after every modification. Let's denote similarity of two arrays as the minimum n...
Let $c_{i}=a_{i} \oplus b_{i}$. Let's notice that if there is list of operations to both arrays, which makes them equal, applying these operations to $a$ makes it equal to $b$. Because of this, applying them to $c$ makes all elements equal to $0$. Now we are processing modifications of $c$. Let's make array $d$ with le...
[ "data structures" ]
3,300
null
1084
A
The Fair Nut and Elevator
The Fair Nut lives in $n$ story house. $a_i$ people live on the $i$-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was dec...
For each request of passenger who lives on the $p$-th floor to get to the first floor, we need $2 \cdot (max(p, x) - 1)$ energy, because in this case lift moves from the $x$-th floor to the $p$-th, then from the $p$-th to the first, then from the first to the $x$-th. So sum is $|p - x| + |x - 1| + |p - 1|$ and it equal...
[ "brute force", "implementation" ]
1,000
null
1084
B
Kvass and the Fair Nut
The Fair Nut likes kvass very much. On his birthday parents presented him $n$ kegs of kvass. There are $v_i$ liters of kvass in the $i$-th keg. Each keg has a lever. You can pour your glass by \textbf{exactly} $1$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $s$ li...
If $\sum a_i$ $\le s$ - the answer is $-1$ Otherwise, let $v$ - minimal volume from these kegs. The answer is $\le v$. For all i: $s$-=$(a_i - v)$. Now all elements equal to $v$. if $s$ become $\le 0$ the answer is $v$. Else the answer is $\lfloor v - (s + n - 1) / n\rfloor$.
[ "greedy", "implementation" ]
1,200
null
1084
C
The Fair Nut and String
The Fair Nut found a string $s$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $p_1, p_2, \ldots, p_k$, such that: - For each $i$ ($1 \leq i \leq k$), $s_{p_i} =$ 'a'. - For each $i$ ($1 \leq i < k$), there is such $j$ that $p_...
Firstly, let's erase all symbols different from 'a' and 'b'. Then let's split string on blocks of consecutive symbols 'a'. Now we need to multiply all sizes of blocks increased by 1. It is an answer which also includes one empty subsequence, so we should just decrease it by one.
[ "combinatorics", "dp", "implementation" ]
1,500
null
1085
A
Right-Left Cipher
Polycarp loves ciphers. He has invented his own cipher called Right-Left. Right-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{n}$ Polycarp uses the following algorithm: - he writes down $s_1$, - he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current ...
You can simulate the process, maintaining the indices of characters of the initial string. So, like this you can find the value of character of the initial string.
[ "implementation", "strings" ]
800
null
1085
B
Div Times Mod
Vasya likes to solve equations. Today he wants to solve $(x~\mathrm{div}~k) \cdot (x \bmod k) = n$, where $\mathrm{div}$ and $\mathrm{mod}$ stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, $k$ and $n$ are positive integer parameters, and $x$ is a positi...
$n$ has to be divisible by $p = x \bmod k$, which in turn is less than $k$. We can try all options of $p$ (in $O(p)$ time), and for suitable options restore $x = p \cdot \frac{n - p}{k}$. Choose the smallest possible $x$. Note that $p = 1$ always divides $n$, hence at least one option will always be available.
[ "math" ]
1,100
null
1085
C
Connect Three
The Squareland national forest is divided into equal $1 \times 1$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $(x, y)$ of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land ...
The smallest possible number of plots required to connect all three plots is at least $\Delta_x + \Delta_y + 1$, where $\Delta_x = x_{max} - x_{min}$ and $\Delta_y = y_{max} - y_{min}$ (here $x_{min}$, $x_{maxn}$, $y_{min}$, $y_{max}$ are extreme coordinate values among the three given plots). It now suffices to find a...
[ "implementation", "math" ]
1,600
null
1085
D
Minimum Diameter Tree
You are given a tree (an undirected connected graph without cycles) and an integer $s$. Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $s$. At the same time, he wants to make the diameter of the tree as small as possible. Let's define the diamete...
Let's denote the number of leaves in this tree for $l$. Let's prove that the answer is $\frac {2s} {l}$. To construct an example with such diameter, let's put the weight $\frac s l$ to the edge adjacent to the leaf, and let's put the weight $0$ to other edges. It is easy to see that the diameter of this tree is $\frac ...
[ "constructive algorithms", "implementation", "trees" ]
1,700
null
1085
E
Vasya and Templates
Vasya owns three strings $s$ , $a$ and $b$, each of them consists only of first $k$ Latin letters. Let a template be such a string of length $k$ that each of the first $k$ Latin letters appears in it exactly once (thus there are $k!$ distinct templates). Application of template $p$ to the string $s$ is the replacement...
Let's implement the following strategy: obtain the minimal string which is greater than or equal to $a$ to correspond to at least one template. If there exists such a string and it is less than or equal to $b$ then the answer exists, otherwise it's not. Let's iterate over the length of prefix of the answer $s'$, which ...
[ "greedy", "implementation", "strings" ]
2,300
null
1085
F
Rock-Paper-Scissors Champion
$n$ players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and tw...
First, let's determine which players can win in a given configuration. If all players have the same shape, then everyone can win. If there are only two kinds of shapes, then one shape always loses, and everyone with the other shape can win. Let's now assume there are all three shapes present. If a player $i$ can win, t...
[]
2,500
null
1085
G
Beautiful Matrix
Petya collects beautiful matrix. A matrix of size $n \times n$ is beautiful if: - All elements of the matrix are integers between $1$ and $n$; - For every row of the matrix, all elements of this row are different; - For every pair of vertically adjacent elements, these elements are different. Today Petya bought a be...
Calculate the following dp: $dp[n]$ - the number of permutations of length $n$ of elements $1 \dots n$ such that $p_i \ne i$ for every $i = 1 \dots n$ $dp[n] = (n - 1) \cdot (dp[n - 1] + dp[n - 2])$; Calculate the following dp: $dp2[n][k]$ - the number of permutations of length $n$ of elements $1, 2, \dots, n, n + 1, n...
[ "combinatorics", "data structures", "dp" ]
2,900
null
1086
F
Forest Fires
Berland forest was planted several decades ago in a formation of an infinite grid with a single tree in every cell. Now the trees are grown up and they form a pretty dense structure. So dense, actually, that the fire became a real danger for the forest. This season had been abnormally hot in Berland and some trees got...
Let $f(t)$ be the total number of trees burnt during first $t$ seconds. The answer can be represented as $t f(t) - \sum \limits_{i = 0}^{t - 1} f(i)$. Computing one value of $f(t)$ can be done in $O(n^2)$ or $O(n \log n)$ with scanline or something like that. Let's analyze how the value of this function is changed as t...
[ "math" ]
3,500
null
1088
A
Ehab and another construction problem
Given an integer $x$, find 2 integers $a$ and $b$ such that: - $1 \le a,b \le x$ - $b$ divides $a$ ($a$ is divisible by $b$). - $a \cdot b>x$. - $\frac{a}{b}<x$.
Well, the constraints allow a brute-force solution, but here's an $O(1)$ solution: If $x = 1$, there's no solution. Otherwise, just print $x - x%2$ and 2. Time complexity: $O(1)$.
[ "brute force", "constructive algorithms" ]
800
"#include <iostream>\nusing namespace std;\nint main()\n{\n int x;\n cin >> x;\n if (x==1)\n cout << -1;\n else\n cout << x-x%2 << ' ' << 2;\n}"
1088
B
Ehab and subtraction
You're given an array $a$. You should repeat the following operation $k$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Let $s$ be the set of numbers in input (sorted and distinct). In the $i^{th}$ step, $s_{i}$ is subtracted from all bigger or equal elements, and all smaller elements are 0. Thus, the answer in the $i^{th}$ step is $s_{i} - s_{i - 1}$ ($s_{0} = 0$). Time complexity: $O(nlog(n))$.
[ "implementation", "sortings" ]
1,000
"#include <iostream>\n#include <set>\nusing namespace std;\nint main()\n{\n int n,m;\n scanf(\"%d%d\",&n,&m);\n set<int> s;\n s.insert(0);\n while (n--)\n {\n \tint a;\n \tscanf(\"%d\",&a);\n \ts.insert(a);\n\t}\n\tauto it=s.begin();\n\tfor (int i=0;i<m;i++)\n\t{\n\t\tif (next(it)==s.end())\n...
1088
C
Ehab and a 2-operation task
You're given an array $a$ of length $n$. You can perform the following operations on it: - choose an index $i$ $(1 \le i \le n)$, an integer $x$ $(0 \le x \le 10^6)$, and replace $a_j$ with $a_j+x$ for all $(1 \le j \le i)$, which means add $x$ to all the elements in the prefix ending at $i$. - choose an index $i$ $(1...
The editorial uses 0-indexing. Both solutions make $a_{i} = i$. First, let's make $a_{i} = x * n + i$ (for some $x$). Then, let's mod the whole array with $n$ (making $a_{i} = i$). If the "add update" changed one index, we can just add $i + n - a_{i}%n$ to index $i$. The problem is, if we make $a_{i} = x * n + i$, then...
[ "constructive algorithms", "greedy", "math" ]
1,400
"#include <iostream>\nusing namespace std;\nint a[2005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\tscanf(\"%d\",&a[i]);\n\tprintf(\"%d\\n\",n+1);\n\tint sum=0;\n\tfor (int i=n-1;i>=0;i--)\n\t{\n\t\tint add=(i-(a[i]+sum)%n+n)%n;\n\t\tprintf(\"1 %d %d\\n\",i+1,add);\n\t\tsum+=add;\n\t}\n\t...
1088
D
Ehab and another another xor problem
\textbf{This is an interactive problem!} Ehab plays a game with Laggy. Ehab has 2 hidden integers $(a,b)$. Laggy can ask a pair of integers $(c,d)$ and Ehab will reply with: - 1 if $a \oplus c>b \oplus d$. - 0 if $a \oplus c=b \oplus d$. - -1 if $a \oplus c<b \oplus d$. Operation $a \oplus b$ is the bitwise-xor oper...
This problem is particularly hard to explain :/ I recommend the simulation. Let's build $a$ and $b$ bit by bit from the most significant to the least significant (assume they're stored in $curA$ and $curB$). Then, at the $i^{th}$ step, $a\oplus c u r A$ and $b\oplus c u r B$ have all bits from the most significant to t...
[ "bitmasks", "constructive algorithms", "implementation", "interactive" ]
2,000
"#include <iostream>\nusing namespace std;\nint ask(int c,int d)\n{\n\tcout << \"? \" << c << ' ' << d << endl;\n\tint ans;\n\tcin >> ans;\n\treturn ans;\n}\nint main()\n{\n\tcout.flush();\n\tint a=0,b=0,big=ask(0,0);\n\tfor (int i=29;i>=0;i--)\n\t{\n\t\tint f=ask(a^(1<<i),b),s=ask(a,b^(1<<i));\n\t\tif (f==s)\n\t\t{\n\...
1088
E
Ehab and a component choosing problem
You're given a tree consisting of $n$ nodes. Every node $u$ has a weight $a_u$. You want to choose an integer $k$ $(1 \le k \le n)$ and then choose $k$ connected components of nodes that don't overlap (i.e every node is in at most 1 component). Let the set of nodes you chose be $s$. You want to maximize: $$\frac{\sum\...
Assume you already chose the components. Let the sum of nodes in the $i^{th}$ component be $b_{i}$. Then, the expression in the problem is equivalent to $average(b_{1}, b_{2}, ..., b_{k})$. Assume we only bother about the fraction maximization problem and don't care about $k$. Then, it'll always be better to choose the...
[ "dp", "greedy", "math", "trees" ]
2,400
"#include <iostream>\n#include <vector>\nusing namespace std;\nint a[300005],k;\nlong long dp[300005],ans=-1e9;\nvector<int> v[300005];\nvoid dfs(int node,int p,bool f)\n{\n\tdp[node]=a[node];\n\tfor (int u:v[node])\n\t{\n\t\tif (u!=p)\n\t\t{\n\t\t\tdfs(u,node,f);\n\t\t\tdp[node]+=max(dp[u],0LL);\n\t\t}\n\t}\n\tif (f)\...
1088
F
Ehab and a weird weight formula
You're given a tree consisting of $n$ nodes. Every node $u$ has a weight $a_u$. It is guaranteed that there is only one node with minimum weight in the tree. For every node $u$ (except for the node with the minimum weight), it must have a neighbor $v$ such that $a_v<a_u$. You should construct a tree to minimize the wei...
First, let's reduce the problem to ordinary MST. We know that each edge ${u, v}$ adds $ \lceil log_{2}(dist(u, v)) \rceil \cdot min(a_{u}, a_{v})$ to $w$. In fact, it also adds 1 to $deg_{u}$ and $deg_{v}$. Thus, the problem is ordinary MST on a complete graph where each edge ${u, v}$ has weight $( \lceil log_{2}(dist...
[ "data structures", "trees" ]
2,800
"#include <iostream>\n#include <string.h>\n#include <vector>\nusing namespace std;\nvector<int> v[500005];\nint m=1,a[500005],dp[20][500005];\nlong long ans;\nvoid dfs(int node,int p)\n{\n\tdp[0][node]=p;\n\tfor (int i=1;i<20;i++)\n\t{\n\t\tif (dp[i-1][node]!=-1)\n\t\tdp[i][node]=dp[i-1][dp[i-1][node]];\n\t}\n\tint d;\...
1091
A
New Year and the Christmas Ornament
Alice and Bob are decorating a Christmas Tree. Alice wants only $3$ types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have $y$ yellow ornaments, $b$ blue ornaments and $r$ red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: - the number of blue ornaments used is grea...
Consider some solution $Y$, $B$, $R$, where $Y + 1 = B$ and $B + 1 = R$. Let's add two yellow ornaments and one blue both to the solution and to the reserve, then we have $Y = B = R$. We can see that this new problem is equivalent to the old one. In this problem, the best solution is achieved when we use $\min(y,b,r)$ ...
[ "brute force", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int a, b, c; cin >> a >> b >> c; cout << min(a + 2, min(b + 1, c)) * 3 - 3; }
1091
B
New Year and the Treasure Geolocation
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $T$, which coordinates to be found out. Bob travelled around the world and collected clues of the treasure location at $n$ obelisks. These clues were in an ancient language, and he has only decrypted them at...
We know that there exists some permutation $p$ such that for all $i$ the following holds: $(t_x, t_y) = (x_{p_i} + a_i, y_{p_i} + b_i)$ Summing this for all $i$ we get: $n \cdot (t_x, t_y) = \sum (x_{p_i} + a_i, y_{p_i} + b_i) = \left(\sum (x_{p_i} + a_i), \sum (y_{p_i} + b_i)\right) = \left(\sum x_i + \sum a_i, \sum y...
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
1,200
#include <vector> #include <algorithm> #include <iostream> using namespace std; typedef pair<int,int> pii; #define x first #define y second int main() { int N; cin >> N; vector<pii> O(N), T(N); for (int i = 0; i < N; i++) cin >> O[i].x >> O[i].y; for (int i = 0; i < N; i++) cin >> T[i].x >> T[i].y; ...
1091
C
New Year and the Sphere Transmission
There are $n$ people sitting in a circle, numbered from $1$ to $n$ in the order in which they are seated. That is, for all $i$ from $1$ to $n-1$, the people with id $i$ and $i+1$ are adjacent. People with id $n$ and $1$ are adjacent as well. The person with id $1$ initially has a ball. He picks a positive integer $k$ ...
Subtract $1$ from all values for convenience. Fix the value of $k$. We get values of $a \cdot k \bmod n$ for all $a$ from $0$ until we reach $0$ again. This value can be also written as $a \cdot k - b \cdot n$. Due to Bezout's theorem, the equation $a \cdot k - b \cdot n = c$ has an integer solution for $a$ and $b$ if ...
[ "math", "number theory" ]
1,400
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long ll; int main() { ll N; cin >> N; vector<ll> ans; for (ll i = 1; i*i <= N; ++i) { if (N%i==0) { ans.push_back(N*(i-1)/2 + i); if (i*i!=N) { ans.push_back(N*(N/i-1)/2 + N/i); } } } sort(ans.begin(),...
1091
D
New Year and the Permutation Concatenation
Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $p$. For example, if $n = 3$, then $p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence will be $n \cdot n!$. Let $1 \leq i \leq j \leq n \cdot...
There are two types of subarrays with length $n$: They are fully formed from one permutations. They are a concatenation of a $k$ long suffix of one permutation, and a $n-k$ long prefix of the next permutation. There are $n!$ such subarrays of the first type, and they all have the the correct sum. Let's investigate the ...
[ "combinatorics", "dp", "math" ]
1,700
#include <iostream> #include <vector> using namespace std; template <unsigned int N> class Field { typedef unsigned int ui; typedef unsigned long long ull; inline ui pow(ui a, ui p){ui r=1,e=a;while(p){if(p&1){r=((ull)r*e)%N;}e=((ull)e*e)%N;p>>=1;}return r;} inline ui inv(ui a){return pow(a,N-2);} public: ...
1091
E
New Year and the Acquaintance Estimation
Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if $a$ is a friend of $b$, then $b$ is also a friend of $a$. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: graph reali...
The first observation is that using the Handshaking lemma, we know the parity of $a_{n+1}$. Secondly, on the integers of same parity, the answer always forms a continuous interval, that is if $a_{n+1} = X$ is one possible answer and $a_{n+1} = Y$ is another with $X < Y$, then every $X < Z < Y$ satisfying $X \bmod 2 == ...
[ "binary search", "data structures", "graphs", "greedy", "implementation", "math", "sortings" ]
2,400
#include <iostream> #include <algorithm> #include <vector> using namespace std; #define MAXN 500000 int N; int A[MAXN]; long long sum; #define TOO_SMALL -1 #define OK 0 #define TOO_BIG 1 int is_score(int value) { vector<int> C(N+1,0); for (int i = 0; i < N; ++i) ++C[A[i]]; ++C[value]; int less = 0;...
1091
F
New Year and the Mallard Expedition
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! \begin{center} Duck is the ultimate animal! (Image courtesy of See Bang) \end{center} The journey can be represented as a straight line, consisting of $n$ segments. Bob is located to the left of the first segment, while Alice's nest is on the...
We start with a greedy solution. This means that we fly over lava, swim on water and walk on grass, keeping track of time and the stamina. There are two types of issues that may happen - either we don't have enough stamina to fly over lava, or we have some leftover stamina at the end. If we lack some stamina, we can wa...
[ "constructive algorithms", "greedy" ]
2,600
#include <iostream> #include <vector> #include <string> typedef long long ll; using namespace std; int main() { int N; cin >> N; vector<ll> L(N); for (ll &l: L) cin >> l; string T; cin >> T; bool hadWater = false; ll time = 0, stamina = 0, twiceGrass = 0; for (int i = 0; i < N; ++i) { ...
1091
G
New Year and the Factorisation Collaboration
Integer factorisation is hard. The RSA Factoring Challenge offered $$100\,000$ for factoring RSA-$1024$, a $1024$-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a $1024$-bit number. Since your programming language of choice might not offer facilities f...
Most of the operations we're given are useless, as we can perform them on our own. However, we cannot perform the square root ourselves, so we should be able to use the information given us by the square root oracle to find the factorisation. First let's solve the task for a product of two primes. Select $x$ uniformly ...
[ "interactive", "math", "number theory" ]
3,200
import random def isPrime(n): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if n!=int(n): return False n=int(n) #Miller-Rabin test for prime if n==0 or n==1 or n==4 or n==6...
1091
H
New Year and the Tricolore Recreation
Alice and Bob play a game on a grid with $n$ rows and infinitely many columns. In each row, there are three tokens, blue, white and red one. \textbf{Before} the game starts and \textbf{after every move}, the following two conditions must hold: - Any two tokens are not in the same cell. - In each row, the blue token is...
If you represent the row state as a pair $(x,y)$ where $x$ is the distance between blue and white token and $y$ is the distance between white and red, we can see that each player has one operation that reduces $x$ by $k$, and a second operation which reduces $y$ by $k$. In other words, each $x$ and $y$ defines a symmet...
[ "games" ]
3,200
#include <vector> #include <stack> #include <iostream> #include <algorithm> #include <bitset> using namespace std; typedef unsigned int ui; typedef long long ll; struct Sieve : public std::vector<bool> { // ~10ns * n explicit Sieve(ui n) : vector<bool>(n+1, true), n(n) { at(0) = false; if (n!=0) at(1) = fals...
1092
A
Uniform String
You are given two integers $n$ and $k$. Your task is to construct such a string $s$ of length $n$ that for each $i$ from $1$ to $k$ there is at least one $i$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to \t...
The only thing you need to do is to place letters by blocks $1, 2, \dots, k$, $1, 2, \dots, k$ and so on. The last block can contain less than $k$ letters but it is ok. It is easy to see that this letters distribution is always not worse than others.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int i = 0; i < t; ++i) { int n, k; cin >> n >> k; for (int j = 0; j < n; ++j) { cout << char('a' + j % k); } cout << endl; ...
1092
B
Teams Forming
There are $n$ students in a university. The number of students is even. The $i$-th student has programming skill equal to $a_i$. The coach wants to form $\frac{n}{2}$ teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their ...
If we sort the students in order of non-decreasing their skill, we can see that the minimum cost of the team with the lowest skill (let's call it the first team) is equal to $a_2 - a_1$ (if $a$ is already sorted), the cost of the second team is $a_4 - a_3$ and so on. So if we sort $a$ in non-decreasing order then the a...
[ "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.begin(), a.end()); int res = 0; for (int i = 0; i < n; i += 2) ...
1092
C
Prefixes and Suffixes
Ivan wants to play a game with you. He picked some string $s$ of length $n$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $1$ to $n-1$), but he didn't tell you which strings are pref...
The first observation: if we will take two strings of length $n-1$ then we almost can restore the initial string. Why almost? Because there are two possible options: when the first string of length $n-1$ is a prefix and the second one is the suffix and vice versa. Let's write a function check(pref, suf) which will chec...
[ "strings" ]
1,700
#include <bits/stdc++.h> using namespace std; int n; vector<string> v; string res; bool check(const string &pref, const string &suf) { string s = pref + suf.substr(n - 2); multiset<string> vv, sPref, sSuf; for (int i = 0; i < n - 1; ++i) { sPref.insert(s.substr(0, n - i - 1)); vv.insert(s.substr(0, n - i - 1...
1092
D1
Great Vova Wall (Version 1)
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches. The current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i...
Fairly enough, solutions of both versions of the problem are pretty similar. The major difference between them are the vertical bricks. As you aren't required to minimize the total height, you can work not with the heights themselves but with their parities instead. Vertical brick now does nothing and horizontal brick ...
[ "greedy", "implementation", "math" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; int n; int a[N]; int main() { scanf("%d", &n); forn(i, n){ scanf("%d", &a[i]); a[i] &= 1; } set<pair<int, int>> seg, even; forn(i, n){ int j = i; while (j + 1 < n && a[j +...
1092
D2
Great Vova Wall (Version 2)
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches. The current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i...
Fairly enough, solutions of both versions of the problem are pretty similar. Read the second part of the previous tutorial first. This problem can also be implemented in the strightforward manner. The greedy solution now is searching for the first minimum in array and putting a brick in there. If it's impossible then t...
[ "data structures", "implementation" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 1000 * 1000 + 13; int n; int a[N]; int main() { scanf("%d", &n); forn(i, n) scanf("%d", &a[i]); vector<int> st; int mx = *max_element(a, a + n); forn(i, n){ if (a[i] == mx) continue; int ...
1092
E
Minimal Diameter Forest
You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree. The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the \textbf{shortest} path between any pair of its vertices. You task is to add some edges (poss...
Let's start with the solution and then proceed to the proof. For each tree in a forest find such a vertex that the maximal distance from it to any vertex is minimal possible (a center of a tree). Tree may include two centers, take any of them in that case. Find the the tree with the maximum diameter. Connect the center...
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const int INF = 1000000000; int n, m; vector<int> g[N]; int bfs(int x, int dist[N]){ queue<int> q; q.push(x); dist[x] = 0; int lst = -1; while (!q.empty()){ int v = q.front(); q...
1092
F
Tree with Maximum Cost
You are given a tree consisting exactly of $n$ vertices. Tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a value $a_v$ assigned to it. Let $dist(x, y)$ be the distance between the vertices $x$ and $y$. The distance between the vertices is the number of edges on the simple path b...
Firstly, let's calculate the answer (let it be $res$) for some fixed vertex. Let this vertex be the vertex $1$. Just run simple dfs and calculate the result using the formula from the problem statement. Also let's calculate the sum of values (let the sum in the subtree of the vertex $v$ be $sum_v$) in each subtree of t...
[ "dfs and similar", "dp", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; long long res, ans; vector<int> a; vector<long long> sum; vector<vector<int>> g; void dfs(int v, int p = -1, int h = 0) { res += h * 1ll * a[v]; sum[v] = a[v]; for (auto to : g[v]) { if (to == p) { continue; } dfs(to, v, h + 1); sum[v] += sum[to]; } } ...
1093
A
Dice Rolling
Mishka got a six-faced dice. It has integer numbers from $2$ to $7$ written on its faces (all numbers on faces are different, so this is an \textbf{almost} usual dice). Mishka wants to get exactly $x$ points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for ...
It is enough to print $\lfloor\frac{x_i}{2}\rfloor$ for each query, where $\lfloor\frac{x}{y}\rfloor$ is $x$ divided by $y$ rounded down.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { int x; cin >> x; cout << x / 2 << endl; } return 0; }
1093
B
Letters Rearranging
You are given a string $s$ consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a \textbf{good} string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string \textbf{good} if it is not a palin...
The only case when the answer is -1 is when all letters of the string are equal. Why is it so? Because if we have at least two different letters we can place the first one at the first position of the string and the second one at the last position of the string. Then it is clearly that the obtained string is good. We c...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { string s; cin >> s; sort(s.begin(), s.end()); if (s[0] == s.back()) cout << -1 << endl; else cout << s << endl; } return 0; }
1093
C
Mishka and the Last Exam
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were $n$ classes of that subject during the semester and on $i$-th class professor mentioned some non-negative ...
Let's present the following greedy approach. The numbers will be restored in pairs $(a_1, a_n)$, $(a_2, a_{n - 1})$ and so on. Thus, we can have some limits on the values of the current pair (satisfying the criteria about sort). Initially, $l = 0, r = 10^{18}$ and they are updated with $l = a_i, r = a_{n - i + 1}$. Let...
[ "greedy" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const long long INF64 = 1'000'000'000'000'000'000ll; const int N = 200 * 1000 + 13; int n; long long a[N], b[N]; void brute(int x, long long l, long long r){ if (x == n / 2){ forn(i, n) printf("%lld ", a[i]); ...
1093
D
Beautiful Graph
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges. You have to write a number on each vertex of the graph. Each number should be $1$, $2$ or $3$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possi...
Let's denote a way to distribute numbers as a painting. Let's also call the paintings that meet the constraints good paintings (and all other paintings are bad). We can solve the problem for each connected component of the graph independently and multiply the answers. Let's analyze a painting of some connected componen...
[ "dfs and similar", "graphs" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 999; const int MOD = 998244353; int n, m; vector <int> g[N]; int p2[N]; int cnt[2]; int col[N]; bool bad; void dfs(int v, int c){ col[v] = c; ++cnt[c]; for(auto to : g[v]){ if(col[to] == -1) dfs(to, 1 - c); if((col[v] ^ col[to]) == 0) ...
1093
E
Intersection of Permutations
You are given two permutations $a$ and $b$, both consisting of $n$ elements. Permutation of $n$ elements is such a integer sequence that each value from $1$ to $n$ appears exactly once in it. You are asked to perform two types of queries with them: - $1~l_a~r_a~l_b~r_b$ — calculate the number of values which appear i...
At first, time limit was not that tight for the problem. We didn't want any sqrt, bitset or straight up $nm$ solution to pass (and it's close to none to pass). Jury solution works faster than twice the time limit so we decided 6 seconds is alright. The task is purely about implementation. You renumerate numbers in perm...
[ "data structures" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; int n, m; int a[N], b[N], pos[N]; vector<int> f[N]; vector<int> vals[N]; void addupd(int x, int y){ for (int i = x; i < N; i |= i + 1) vals[i].push_back(y); } void addget(int x, int...
1093
F
Vasya and Array
Vasya has got an array consisting of $n$ integers, and two integers $k$ and $len$ in addition. All numbers in the array are either between $1$ and $k$ (inclusive), or equal to $-1$. The array is good if there is no segment of $len$ consecutive \textbf{equal} numbers. Vasya will replace each $-1$ with some number from ...
Let's try dynamic programming approach to this problem. Let $dp_{cnt, lst}$ be the number of ways to replace all $-1$ with numbers from $1$ to $k$ in such a way that array $a_{1 \dots cnt}$ is good and the last number of that array is $lst$. Let $sdp_{cnt} = \sum\limits_{i=1}^{k} dp_{cnt, i}$. Then initially it's $dp_{...
[ "dp" ]
2,400
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); ++i) #define forn(i, n) fore(i, 0, n) #define nfor(i, n) for(int i = int(n) - 1; i >= 0; --i) #define for1(i, n) for(int i = 1; i < int(n); ++i) #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).beg...
1093
G
Multidimensional Queries
You are given an array $a$ of $n$ points in $k$-dimensional space. Let the distance between two points $a_x$ and $a_y$ be $\sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|$ (it is also known as Manhattan distance). You have to process $q$ queries of the following two types: - $1$ $i$ $b_1$ $b_2$ ... $b_k$ — set $i$-th ...
Let's rewrite the formula of distance between two points as follows: $\sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}| = \sum \limits_{i = 1}^{k} c_i (a_{x, i} - a_{y, i}) = \sum \limits_{i = 1}^{k} c_i a_{x, i} - \sum \limits_{i = 1}^{k} c_i a_{y, i}$, where $c_i = 1$ if $a_{x, i} \ge a_{y, i}$, otherwise $c_i = -1$. Co...
[ "bitmasks", "data structures" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const int INF = 1e9; struct point{ int a[5]; point(){}; int& operator[](int x){ return a[x]; } }; int n, k; point a[N]; int t[32][4 * N]; int apply(point& p, int mask){ int res ...
1095
A
Repeating Cipher
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{m}$ ($1 \le m \le 10$), Polycarp uses the following algorithm: - he writes down $s_1$ ones, - he writes down $s_2$ twice, - he writes down $s_3$ three times, - .....
There are many possible approaches in this problem, I will describe one of the easiest. Let's print the initial string by the following algorithm: firstly, init the variable $i = 1$. Then, while the encrypted string isn't empty, print the first character of this string, remove $i$ first characters from it and increase ...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string s; cin >> s; int index = 0; int gap = 1; while (index < n) cout << s[index], index += gap, gap++; }
1095
B
Array Stabilization
You are given an array $a$ consisting of $n$ integer numbers. Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$. You have to remove \textbf{exactly one} element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is ...
It is easy to see that we always have to remove either minimum or maximum of the array. So we can sort the array and the answer will be $min(a_{n - 1} - a_{1}, a_{n} - a_{2})$. We also can do it without sort because two minimal and two maximal elements of the array can be found in linear time.
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.begin(), a.end()); cout << min(a[n - 2] - a[0], a[n - 1] - a[1])...
1095
C
Powers Of Two
A positive integer $x$ is called a power of two if it can be represented as $x = 2^y$, where $y$ is a non-negative integer. So, the powers of two are $1, 2, 4, 8, 16, \dots$. You are given two positive integers $n$ and $k$. Your task is to represent $n$ as the \textbf{sum} of \textbf{exactly} $k$ powers of two.
First of all, let's analyze how can we calculate the minimum number of powers of two needed to get $n$ as the sum. We can use binary representation of $n$: each bit in it, which is equal to $1$, becomes a summand in the answer. Firstly, if the number of summands is greater than $k$ then the answer is NO. Okay, what if ...
[ "bitmasks", "greedy" ]
1,400
#include<bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; map<int, int> ans; queue<int> q; for(int i = 0; i <= 30; i++) if(n & (1 << i)) { if(i > 0) q.push(1 << i); ans[1 << i]++; } if(int(ans.size()) > k) { puts("NO"); return 0; } int cnt = ans.size(); while(cnt < k...
1095
D
Circular Dance
There are $n$ kids, numbered from $1$ to $n$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $p_1$, $p_2$, ..., $p_n$ (all these numbers are from $1$ to $n$ and are distinct, so $p$ is a permutation). Let the next kid for a kid $p_i$ be kid $p_{i + 1}$ if $i < n$ and $p_...
Let's write a function check(a, b) which will try to restore the circle if kid with number $b$ comes right after kid with number $a$. If $b$ comes right after $a$ then we can determine $c$ - the number of kid who is next to kid $b$. So now we have: $b$ comes right after $a$, $c$ comes right after $b$. Let's determine $...
[ "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int n; vector<vector<int>> a; void check(int l, int r) { vector<int> ans; for (int i = 0; i < n; ++i) { int nxt = -1; if (a[l][0] == r) { nxt = a[l][1]; } else if (a[l][1] == r) { nxt = a[l][0]; } else { return; } ans.push_back(nxt); l = r; r =...
1095
E
Almost Regular Bracket Sequence
You are given a bracket sequence $s$ consisting of $n$ opening '(' and closing ')' brackets. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences ...
In this problem we have to calculate the number (count) of positions such that if we change the type of the bracket at this position then the obtained bracket sequence will become regular. Let's calculate the balance of each prefix of the bracket sequence and store it in the array $prefBal$. Just iterate from left to r...
[ "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; string rs(s.rbegin(), s.rend()); for (int i = 0; i < n; ++i) { if (rs[i] == '(') { rs[i] = ')'; } else { rs[i] = ...
1095
F
Make It Connected
You are given an undirected graph consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is $a_i$. Initially there are no edges in the graph. You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $x$ and $y$ is $a_x + a_y$ coin...
Suppose we have found all the edges of the graph explicitly, sorted them, and start running Kruskal on the sorted list of edges. Each time we add some edge to MST, it is either a special edge given in the input, or an edge which was generated with cost $a_x + a_y$ (whichever costs less). Let's try to analyze how can we...
[ "dsu", "graphs", "greedy" ]
1,900
#include<bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair typedef pair<long long, pair<int, int> > edge; const int N = 200043; int p[N]; long long a[N]; int get_leader(int x) { return (x == p[x] ? x : (p[x] = get_leader(p[x]))); } bool merge(int x, int y) { x = get_lead...
1096
A
Find Divisible
You are given a range of positive integers from $l$ to $r$. Find such a pair of integers $(x, y)$ that $l \le x, y \le r$, $x \ne y$ and $x$ divides $y$. If there are multiple answers, print any of them. You are also asked to answer $T$ independent queries.
Print $l$ and $2l$. Firstly, the smallest value of $\frac y x$ you can have is $2$ and if any greater value fits then $2$ fits as well. Secondly, the absolute difference between $x$ and $2x$ increases when you increase $x$, thus lessening the possibility of both numbers fitting into the range. Overall complexity: $O(1)...
[ "greedy", "implementation", "math" ]
800
T = int(input()) for i in range(T): l, r = map(int, input().split()) print(l, l * 2)
1096
B
Substring Removal
You are given a string $s$ of length $n$ consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove \textbf{exactly} one subst...
Firstly, let's calculate the length of the prefix of equal letters (let it be $l$) and the length of the suffix of equal letters (let it be $r$). It can be done with two cycles with breaks. It is obvious that this prefix and suffix wouldn't overlap. Then let's consider two cases: the first one is when $s_1 \ne s_n$ and...
[ "combinatorics", "math", "strings" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; int cntl = 0, cntr = 0; for (int i = 0; i < n; ++i) { if (s[i] == s[0]) { ++cntl; } else { break; } } for (int ...
1096
C
Polygon for the Angle
You are given an angle $\text{ang}$. The Jury asks You to find such \textbf{regular} $n$-gon (regular polygon with $n$ vertices) that it has three vertices $a$, $b$ and $c$ (they can be non-consecutive) with $\angle{abc} = \text{ang}$ or report that there is no such $n$-gon. If there are several answers, print the \t...
At first, let prove that all possible angles in the regular $n$-gon equal to $\frac{180k}{n}$, where $1 \le k \le n - 2$. To prove it we can build circumscribed circle around $n$-gon. Then the circle will be divided on $n$ equal arcs with lengths $\frac{360}{n}$. Any possible angle in the $n$-gon is a inscribed angle i...
[ "brute force", "geometry" ]
1,600
#include<bits/stdc++.h> using namespace std; int ang; inline bool read() { if(!(cin >> ang)) return false; return true; } inline void solve() { int g = __gcd(ang, 180); int k = ang / g; int n = 180 / g; if(k + 1 == n) k *= 2, n *= 2; cout << n << endl; } int main() { #ifdef _DEBUG freopen("input.txt",...
1096
D
Easy Problem
Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $n$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaa...
Denote string $t$ as hard. We will solve this problem with dynamic programming. Denote $dp_{cnt, len}$ - the minimum possible ambiguity if we considered first $cnt$ letters of statement and got prefix $t$ having length $len$ as a subsequence of the string. If $cnt$-th letter of the statement is not equal to $t_{len}$, ...
[ "dp" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 100 * 1000 + 13; const long long INF64 = 1e18; int n; string s; int a[N]; long long dp[N][5]; const string h = "hard"; int main() { scanf("%d", &n); static char buf[N]; scanf("%s", buf); s = buf; f...
1096
E
The Top Scorer
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are $p$ players doing penalty shoot-outs. Winner is the one who scores the most. \textbf{In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.} They have just f...
An straightforward dp solution is to calculate $dp_{s,p,m} =$ {number of states at the end of the game in which no one has scored more than $m$ goals} where $s$ is the number of total goals to be scored and $p$ is the number players in the game. Fix the score of Hasan in the game and by using this dp the rest is easy (...
[ "combinatorics", "dp", "math", "probabilities" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; const int N = 10 * 1000 + 7; const int M = 100 + 7; int fact[N], rfact[N]; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){...
1096
F
Inversion Expectation
A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, ...
Let's break the problem into four general cases. Case 1. Inversions between two unknown numbers. Each pair of numbers can either be or inversion or not and the number of permutations for both cases is the same. Thus, the expected value of that is $\frac{cnt(-1) \cdot (cnt(-1) - 1)}{2} \cdot \frac 1 2$. Case 2 and 3. In...
[ "dp", "math", "probabilities" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const int MOD = 998244353; int n; int p[N]; bool used[N]; int gt[N]; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b){ return (a * 1ll * b)...
1096
G
Lucky Tickets
All bus tickets in Berland have their numbers. A number consists of $n$ digits ($n$ is even). Only $k$ decimal digits $d_1, d_2, \dots, d_k$ can be used to form ticket numbers. If $0$ is among these digits, then numbers may have leading zeroes. For example, if $n = 4$ and only digits $0$ and $4$ can be used, then $0000...
The naive solution would be $dp_{x, y}$ - the number of sequences of allowed digits with length $x$ and sum $y$. We compute it for $x = \frac{n}{2}$ and for every possible $y$, and the answer is $\sum_y dp_{\frac{n}{2}, y}^2$. Let's speed this up. Let's denote the following polynomial: $f(x) = \sum_{i = 0}^{9} c_i x^i$...
[ "divide and conquer", "dp", "fft" ]
2,400
#include<bits/stdc++.h> using namespace std; const int LOGN = 21; const int N = (1 << LOGN); const int MOD = 998244353; const int g = 3; #define forn(i, n) for(int i = 0; i < int(n); i++) inline int mul(int a, int b) { return (a * 1ll * b) % MOD; } inline int norm(int a) { while(a >= MOD) a -= MOD; while(a <...
1097
A
Gennady and a Card Game
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, o...
The task is to check if some card in the second line has a common character with the card in the first line. The best way to do this is to create a single string for the card in the hand and an array of strings for the cards on the table. After reading the input, just iterate with a loop over the array. If a string in ...
[ "brute force", "implementation" ]
800
null
1097
B
Petr and a Combination Lock
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of $360$ degrees and a pointer which initially points at zero: Petr called his car dealer, who instructe...
The best way to check the condition in the statement is to use bitmasks. Iterate from $0$ to $2^n-1$ and for each number consider its binary representation. If the $i$-th bit of the representation is set to $0$, then decide to perform the $i$-th rotation clockwise. In the opposite case, do it counterclockwise. Finally,...
[ "bitmasks", "brute force", "dp" ]
1,200
null
1097
C
Yuhao and a Parenthesis
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences. A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting c...
It turns out that each bracket sequence can be described by a pair $(a, b)$, where $a$ and $b$ are the minimal non-negative integers such that after adding $a$ opening parentheses "(" to the left of the string and $b$ closing parentheses ")" to the right of the string it becomes a correct bracket sequence. These number...
[ "greedy", "implementation" ]
1,400
null
1097
D
Makoto and a Blackboard
Makoto has a big blackboard with a positive integer $n$ written on it. He will perform the following action exactly $k$ times: Suppose the number currently written on the blackboard is $v$. He will randomly pick one of the divisors of $v$ (possibly $1$ and $v$) and replace $v$ with this divisor. As Makoto uses his fam...
How to solve the problem if $n$ is a prime power $p^{\alpha}$? We can simply use dynamic programming. Let $DP_{i, j}$ denote the probability that after $i$ steps the current number on the blackboard is $p^j$. At the beginning, $DP_{0, \alpha} = 1$. The transitions in DP are rather straightforward. The expected value of...
[ "dp", "math", "number theory", "probabilities" ]
2,200
null
1097
E
Egor and an RPG game
One Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign: Egor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute the letters...
Firstly, consider this testcase: $\{1, 3, 2, 6, 5, 4, 10, 9, 8, 7, 15, 14, 13, 12, 11\}$. It's easy to see that here we need at least $5$ sequences. It's possible to generalize it and see that if $n \geq \frac{k \cdot (k+1)}{2}$ for some integer $k$, then we need at least $k$ sequences. So, maybe if $n < \frac{k \cdot ...
[ "constructive algorithms", "greedy" ]
3,400
null
1097
F
Alex and a TV Show
Alex decided to try his luck in TV shows. He once went to the quiz named "What's That Word?!". After perfectly answering the questions "How is a pseudonym commonly referred to in the Internet?" ("Um... a nick?"), "After which famous inventor we name the unit of the magnetic field strength?" ("Um... Nikola Tesla?") and ...
Firstly, let's store in a bitset of size $7000$ an information which elements occur an odd number of times in some multiset. Let's think about the query of the third type like about a convolution. We'll solve it similarly to FFT: we'll change both polynomials (arrays) into a form of "values in points", multiply them by...
[ "bitmasks", "combinatorics", "number theory" ]
2,500
null
1097
G
Vladislav and a Great Legend
A great legend used to be here, but some troll hacked Codeforces and erased it. Too bad for us, but in the troll society he earned a title of an ultimate-greatest-over troll. At least for them, it's something good. And maybe a formal statement will be even better for us? You are given a tree $T$ with $n$ vertices numb...
Firstly, to properly understand what does "calculate the sum of the $k$-th powers" means, I recommend you to get acquainted with these two lectures (especially the "powers technique"): https://codeforces.com/blog/entry/62690 https://codeforces.com/blog/entry/62792 Here is a shorter version of what you should understand...
[ "combinatorics", "dp", "trees" ]
3,000
null
1097
H
Mateusz and an Infinite Sequence
A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence $\mathrm{gen}$ of length $d$ and an integer $m$, obtained in the following sequence of steps: - In the beginning, we define the one-element sequence $M_0=(0)$. - In the $k$-th step, $k ...
In the beginning, change the query about an interval into two queries about prefixes. Nextly, let's generalize the problem. Change the condition $A_i \leq B_j$ into $A_i \in X_j$, where $X_j$ is some set of possible values (and will be represented as a bitmask). The problem is that the length of the sequence from the i...
[ "bitmasks", "brute force", "dp", "strings" ]
3,400
null
1098
A
Sum in the tree
Mitya has a rooted tree with $n$ vertices indexed from $1$ to $n$, where the root has index $1$. Each vertex $v$ initially had an integer number $a_v \ge 0$ written on it. For every vertex $v$ Mitya has computed $s_v$: the sum of all values written on the vertices on the path from vertex $v$ to the root, as well as $h_...
To achieve the minimum possible sum of values in the tree, for vertices with even depth we need to put 0 for leaves and the maximum value possible for other vertices, because increasing the value does not make the resulting sum worse - our children would compensate for it. Since $a_v \ge 0$, it's obvious that ${s_p}_v ...
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
1,600
null
1098
B
Nice table
You are given an $n \times m$ table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every $2 \times 2$ square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.
Key idea: In a good matrix, either each row contain at most two different characters, or each column contain at most two different characters. Proof: (it will be here, but for now the editorial fields are too narrow to contain it). In other words, the field looks either like (up to a permutation of <<AGCT>>): <<AGAGAG>...
[ "brute force", "constructive algorithms", "greedy", "math" ]
2,100
null
1098
C
Construct a tree
Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with $n$ vertices, indexed from 1 to $n$, where the root has index 1. Every other vertex has a parent $p_i$, and $i$ is called a child of vertex $p_i$. Vertex $u$ belo...
Note, that vertex belongs to subtrees of vertexes, which lay on its way to root. So, sum of sizes of subtrees is equal to $p + n$, where $p$ is sum of lengths of ways from root to vertexes. Let's consider which sum of sizes of subtrees can be in tree with branching coefficient less or equal than $k$. Minimal sum can be...
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
2,400
null
1098
D
Eels
Vasya is a big fish lover, and his parents gave him an aquarium for the New Year. Vasya does not have a degree in ichthyology, so he thinks that filling a new aquarium with eels is a good idea. Unfortunately, eels are predators, so Vasya decided to find out how dangerous this idea was. Getting into one aquarium, eels ...
Let's consider a set of fishes of size $k$ and sort it in non-decreasing order: $a_1 \le a_2 \le \ldots \le a_k$. Let's call a fish fat if its weight is greater than twice the sum of all fishes with smaller indices: fish $a_i$ is fat iff $a_i > 2 \sum_{j < i} a_j$. Key fact. Let $t$ be the total number of fat fishes. W...
[ "data structures" ]
2,800
null
1098
E
Fedya the Potter
Fedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array $a_1, a_2, \ldots a_n$ and a beautiful data structure. This data structure, given $l$ and $r$, $1 \le l \le r \le n$, could find the greatest integer $d$, such that $d$ divides each of $a_l$, $...
There are $O(N\cdot logN)$ different values of gcd, because if we fix the left bound of a segment and iterate right bound from left bound to the end, the gcd stays unchanged or decreases in two or more times. We can get a compressed version of array $b$ if we compress equal consecutive elements in to pair $(value, coun...
[ "binary search", "implementation", "math", "number theory" ]
3,400
null
1098
F
Ж-function
The length of the longest common prefix of two strings $s=s_1 s_2 \ldots s_n$ and $t = t_1 t_2 \ldots t_m$ is defined as the maximum $k \le \min(n, m)$ such that $s_1 s_2 \ldots s_k$ equals $t_1 t_2 \ldots t_k$. Let's denote the longest common prefix of two strings $s$ and $t$ as $lcp(s,t)$. Z-function of a string $s_...
Answer for query $l$, $r$ is equal to $\sum^{r}_{i=l}{\min(lcp(l,i), r - i + 1)}$. $lcp(i, l)$ is the length of longest common preffix of $i$-th and $l$-th suffixes. Let $\min(lcp(l,i), r - i + 1)$ be denoted by <<cutted $lcp$>> of two suffixes. Now we can use another approach to calculate the answer. For each $k = 1 \...
[ "string suffix structures", "strings" ]
3,500
null
1099
A
Snowball
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height $h$ and it has weight $w$. Each second the following sequence of events happens: snowball's weights increases b...
This problem can be solved in many ways, we will tell you one of them. Let's just iterate through all the heights of $i$ from $h$ to $1$. Inside the loop, we have to add $i$ to the weight of snowball, and then check whether there is a stone at this height. If there is, then you need to check whether weight of snowball ...
[ "implementation" ]
800
null
1099
B
Squares and Segments
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw $n$ squares in the snow with a side length of $1$. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length $1$, parallel to the coordinate axes, w...
Consider any resulting configuration of the squares. We can safely assume that a set of non-empty rows and non-empty columns are connected (otherwise just move the disconnected part a bit closer to any other). Clearly, in every column and every row we can <<for free>> extend it to have all the squares in the bounding b...
[ "binary search", "constructive algorithms", "math" ]
1,100
null
1099
C
Postcard
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it. Andrey noticed that snowflakes and candy canes always stand af...
If the string in the postcard does not contain any snowflakes or candy cones, $k$ must be equal to the length of the string, because the only string encoded by such message is the string itself, and in this case if $k$ is not equal to the length of the string, the answer is <<Impossible>>. Let's call the characters of ...
[ "constructive algorithms", "implementation" ]
1,200
null
1099
F
Cookies
Mitya and Vasya are playing an interesting game. They have a rooted tree with $n$ vertices, and the vertices are indexed from $1$ to $n$. The root has index $1$. Every other vertex $i \ge 2$ has its parent $p_i$, and vertex $i$ is called a child of vertex $p_i$. There are some cookies in every vertex of the tree: ther...
If Mitya moves the chip to vertex $i$ during the game and then moves it back to the root, he will have exactly $T - 2 \cdot (\text{time to reach vertex $i$ from the root})$ time to eat cookies. Let's denote the maximum number of cookies he can eat during this time by $f[i]$. Let's first focus on what to do next, assumi...
[ "binary search", "data structures", "dfs and similar", "dp", "games", "trees" ]
2,400
null
1100
A
Roman and Browser
This morning, Roman woke up and opened the browser with $n$ opened tabs numbered from $1$ to $n$. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them. He decided to accomplis...
The constraints in this task allowed us to simply iterate over the closed tab and check the answer, but we can solve it more quickly - calculate the sum for each value modulo $k$ and count the total sum for the whole array. After that, you just need to go through the module tab numbers that we delete, and update the an...
[ "implementation" ]
1,000
null
1100
B
Build a Contest
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$. To hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the ...
We will keep the arrays, how many problems are created for each specific complexity $i$ - $cnt_i$ and how many problems have been created for the round $j$ - $exist_j$. Then if we create a task with complexity $c$, we will recalculate $cnt_c = cnt_c + 1$, $exist_ {cnt_c} = exist_ {cnt_c} + 1$. Suppose we have already g...
[ "data structures", "implementation" ]
1,300
null
1100
C
NN and the Optical Illusion
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture him...
Consider three circles - inner and two outer. Since all the circles are tangent, the sides of the triangle constructed on the centers of the circles pass through the tangency points of the circles. Denote by $\alpha$ the angle in an equilateral $n$ -gon. Then $\alpha = \frac {\pi (n - 2)} {n}$. On the other hand, $\fra...
[ "binary search", "geometry", "math" ]
1,200
null
1100
D
Dasha and Chess
This is an interactive task. Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below. There are $666$ black rooks and $1$ white king on the chess board of size $999 \times 999$. The white king wins if he gets chec...
One of the possible strategies: the king goes to the center, then goes to the corner that he has as few rooks as possible behind his back. The solution uses the Pigeonhole principle, since in the largest corner and in two neighbors to it, the sum will be no less than $666 * 3/4 > 499$ rooks, i.e. $\geq 500$ rooks, and ...
[ "constructive algorithms", "games", "interactive" ]
2,500
null
1100
E
Andrew and Taxi
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to...
Suppose we have $k$ traffic controllers. They can turn all edges whose weight is less than or equal to $k$. Then let's remove all these edges from the graph, make a topological sorting of the remaining graph, and orient the other edges in the order of topological sorting. If there are cycles left in the graph after rem...
[ "binary search", "dfs and similar", "graphs" ]
2,200
null
1100
F
Ivan and Burgers
Ivan loves burgers and spending money. There are $n$ burger joints on the street where Ivan lives. Ivan has $q$ friends, and the $i$-th friend suggested to meet at the joint $l_i$ and walk to the joint $r_i$ $(l_i \leq r_i)$. While strolling with the $i$-th friend Ivan can visit all joints $x$ which satisfy $l_i \leq x...
Note that to answer on a segment, it is enough to know the basis of this segment, that is, the minimum set of numbers, with which you can represent all the numbers that are representable on this segment. Since $0 \leq a_i \leq 1000000$, then the basis will be no more than $20$. To find the maximum number, run the Gauss...
[ "data structures", "divide and conquer", "greedy", "math" ]
2,500
null
1101
A
Minimum Integer
You are given $q$ queries in the following form: {Given three integers $l_i$, $r_i$ and $d_i$, find minimum \textbf{positive} integer $x_i$ such that it is divisible by $d_i$ and it does not belong to the segment $[l_i, r_i]$}. Can you answer all the queries? Recall that a number $x$ belongs to segment $[l, r]$ if $...
There are two basic cases we have to consider: either the element we want to find is less than $l_i$, or it is greater than $r_i$. In the first case, we are interested in $d_i$ itself: it is the minimum positive number divisible by $d_i$, and if it is less than $l_i$, then it is the answer. In the second case, we have ...
[ "math" ]
1,000
q = int(input()) for i in range(q): l, r, d = map(int, input().split()) if(d < l or d > r): print(d) else: print((r // d) * d + d)
1101
B
Accordion
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $091$), a colon (ASCII code $058$), some (possibly zero) vertical line characters (ASCII code $124$), another colon, ...
No cases. No any special thoughts. Just greedy. The solution consists of six steps: Remove the prefix of the string until the position of leftmost '[' character. If there is no such character, print -1; Remove the prefix of the string until the position of leftmost ':' character. If there is no such character, print -1...
[ "greedy", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; void rem(string &s, const string &c) { auto pos = s.find(c); if (pos == string::npos) { cout << -1 << endl; exit(0); } s.erase(0, pos + 1); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s; ...
1101
C
Division and Union
There are $n$ segments $[l_i, r_i]$ for $1 \le i \le n$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group. To optimize ...
Let's prove that division possible if and only if union of all segments has two and more segments. If the union have at least two segments, then we can choose one of them and put all segments it contains in one group and other segments to another group. On the other hand, if we can divide all segments in two groups in ...
[ "sortings" ]
1,500
#include<bits/stdc++.h> using namespace std; #define x first #define y second typedef pair<int, int> pt; int n; vector< pair<pt, int> > segs; inline bool read() { if(!(cin >> n)) return false; segs.resize(n); for(int i = 0; i < n; i++) { cin >> segs[i].x.x >> segs[i].x.y; segs[i].y = i; } return true; }...
1101
D
GCD Counting
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$. Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vert...
I know there exists $O(n \log MAXN)$ solution and author of the problem promises to tell it to you (here he explained it). I'd love to tell easier to code and about the same time to work $O(n \log^2 MAXN)$ solution. At first, notice that it is only enough to check the paths such that all vertices on it is divisible by ...
[ "data structures", "dfs and similar", "dp", "number theory", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define all(a) a.begin(), a.end() #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, l, r) for(int i = int(l); i < int(r); i+...
1101
E
Polycarp's New Job
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). ...
Let's find the smallest wallet to fit all bills. One its side is the maximum side of any bill. Now we orient the bills in such a way that their longer side is put against this side of the wallet. The second side of the wallet is the maximum of the other sides. More formally, for set of bills $(a_1, b_1)$, $(a_2, b_2)$,...
[ "implementation" ]
1,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n; scanf("%d", &n); int mxa = 0, mxb = 0; static char buf[5]; forn(i, n){ int x, y; scanf("%s%d%d", buf, &x, &y); if (x < y) swap(x, y); if (buf[0] == '+'){ mxa = max(mxa, x); mxb ...
1101
F
Trucks and Cities
There are $n$ cities along the road, which can be represented as a straight line. The $i$-th city is situated at the distance of $a_i$ kilometers from the origin. All cities are situated in the same direction from the origin. There are $m$ trucks travelling from one city to another. Each truck can be described by $4$ ...
First (bonus) solution: implement idea from Blogewoosh #6. Time complexity will be somewhat $O((q + \log{q} \log{\text{MAX}})n)$ and space complexity is $O(n + q)$. Honest solution: Note, that for each truck lower bound on the answer is $\max(c_i \cdot (a[p_{j + 1}] - a[p_{j}])) = c_i \cdot \max(a[p_{j + 1}] - a[p_j])$...
[ "binary search", "dp" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define mp make_pair #define pb push_back #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = in...
1101
G
(Zero XOR Subset)-less
You are given an array $a_1, a_2, \dots, a_n$ of integer numbers. Your task is to divide the array into the maximum number of segments in such a way that: - each element is contained in \textbf{exactly one} segment; - each segment contains at least one element; - there doesn't exist a non-empty subset of segments suc...
Let's consider some division $[0, i_1)$, $[i_1, i_2)$, ..., $[i_k, n)$. Represent the XOR sum of the subset via prefix-XOR. Those are $pr[i_1] \oplus pr[0]$, $pr[i_2] \oplus pr[i_1]$, ..., $pr[n] \oplus pr[i_k]$. I claim that you can collect any subset that is a XOR of an even number of $pr[x]$ for pairwise distinct va...
[ "math", "matrices" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const int LOGN = 30; int n; int a[N], pr[N]; int base[LOGN]; void try_gauss(int v){ for(int i = LOGN - 1; i >= 0; i--) if (base[i] != -1 && (v & (1 << i))) v ^= base[i]; if (v == ...
1102
A
Integer Sequence Dividing
You are given an integer sequence $1, 2, \dots, n$. You have to divide it into two sets $A$ and $B$ in such a way that each element belongs to \textbf{exactly one} set and $|sum(A) - sum(B)|$ is minimum possible. The value $|x|$ is the absolute value of $x$ and $sum(S)$ is the sum of elements of the set $S$.
The first solution: take $n$ modulo $4$ and solve the problem manually (then for cases $n = 0$ and $n = 3$ the answer is $0$ and for $n = 1$ and $n = 2$ the answer is $1$). Prove: Let's see what can we make for numbers $n$, $n - 1$, $n - 2$ and $n - 3$. We can add $n$ and $n - 3$ in $A$ and add $n - 1$ and $n - 2$ in $...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; long long sum = n * 1ll * (n + 1) / 2; cout << (sum & 1) << endl; return 0; }
1102
B
Array K-Coloring
You are given an array $a$ consisting of $n$ integer numbers. You have to color this array in $k$ colors in such a way that: - Each element of the array should be colored in some color; - For each $i$ from $1$ to $k$ there should be \textbf{at least one} element colored in the $i$-th color in the array; - For each $i...
How can we solve this problem easily? Firstly, let's sort the initial array (but maintain the initial order of the elements in the array to restore the answer). Then let's just distribute all the colors uniformly. Let's color the first element in the first color, the second one - in the second, the $k$-th element - in ...
[ "greedy", "sortings" ]
1,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, k; cin >> n >> k; vector<pair<int, int>> a(n); for (int i = 0; i < n; ++i) { cin >> a[i].first; a[i].second = i; } sort(a.begin(), a.end()); ...