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
821
C
Okabe and Boxes
Okabe and Super Hacker Daru are stacking and removing boxes. There are $n$ boxes numbered from $1$ to $n$. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru $2n$ commands: $n$ of which are to add a box to the top of the stack, and $n$ of which are to remove a box from the top of the s...
It looks like Daru should only reorder the boxes when he has to (i.e. he gets a remove operation on a number which isn't at the top of the stack). The proof is simple: reordering when Daru has more boxes is always not worse than reordering when he has less boxes, because Daru can sort more boxes into the optimal arrang...
[ "data structures", "greedy", "trees" ]
1,500
#include <vector> #include <utility> #include <iostream> #include <cassert> #include <map> #include <climits> #include <deque> #include <algorithm> #include <set> #include <stack> using namespace std; #define ll long long #define REP(i,a) for(int i = 0; i < (a); i++) #define PB push_back #define SZ(a) (a).size() #defi...
821
D
Okabe and City
Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren. Okabe's city is represented by a 2D grid of cells. Rows are numbered from $1$ to $n$ from top to bottom, and columns are numbered $1$ to $m$ from left to right. Exactly $k$ cells in the ...
First, let's make this problem into one on a graph. The important piece of information is the row and column we're on, so we'll create a node like this for every lit cell in the grid. Edges in the graph are 0 between 2 nodes if we can reach the other immediately, or 1 if we can light a row/column to get to it. Now it's...
[ "dfs and similar", "graphs", "shortest paths" ]
2,200
/*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp>*/ #include <bits/stdc++.h> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update...
821
E
Okabe and El Psy Kongroo
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points $(x, y)$ such that $x$ and $y$ are non-negative. Okabe starts at the origin (point $(0, 0)$), and nee...
You can get a naive DP solution by computing $f(x, y)$, the number of ways to reach the point $(x, y)$. It's just $f(x - 1, y + 1) + f(x - 1, y) + f(x - 1, y - 1)$, being careful about staying above x axis and under or on any segments. To speed it up, note that the transitions are independent of x. This is screaming ma...
[ "dp", "matrices" ]
2,100
#include <queue> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cst...
822
A
I'm bored with life
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
Tutorial is not available
[ "implementation", "math", "number theory" ]
800
int a, b; scanf ( "%d%d", &a, &b ); int ans = 1; for ( int j = 1; j <= min( a, b ); j++ ) ans *= j; printf ( "%d\n", ans );
822
B
Crossword solving
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta...
Let's consider all the positions $i$ $(1 \le i \le m - n + 1)$ that denotes the begining of the occurrence of the string $s$ in the string $t$. Then let's find out how many symbols we should replace if the begining of the occurrence is position $i$. After the considering of all $m - n + 1$ positions the optimal ans...
[ "brute force", "implementation", "strings" ]
1,000
const int maxn = 1050; vector < int > ans; vector < int > newAns; char t1[maxn]; char t2[maxn]; int n, m; scanf ( "%d%d\n", &n, &m ); gets( t1 ); gets( t2 ); for ( int j = 0; j < n; j++ ) ans.pb( j ); for ( int j = 0; j < m - n + 1; j++ ) { newAns.clear(); ...
822
C
Hacker, pack your bags!
It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha. So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly $x$ days. Y...
Let's sort all the vouchers by their left border $l_{i}$. Let's consider the vouchers in this sorted order. Now we want to consider $i$-th one. The duration of the $i$-th voucher is $r_{i} - l_{i} + 1$. Consequentally only the vouchers with the duration $x - r_{i} + l_{i} - 1$ can make a couple with the $i$-th one. At ...
[ "binary search", "greedy", "implementation", "sortings" ]
1,600
const int maxn = 200500; const int inf = ( 2e9 ) + 2; vector < pair < pair < int, int >, pair < int, int > > > queries; int bestCost[maxn]; int l[maxn]; int r[maxn]; int cost[maxn]; int solution( int n, int needLen ) { queries.clear(); for ( int j = 0; j < n; j++ ) { queries.pb( mp( mp( l[j], -1 ), m...
822
D
My pretty girl Noora
In Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail. The contest is held in several stages. Suppose that exactly $n$ girls participate in the competition initiall...
Suppose we have already calculated $f(2), f(3), ..., f(r)$. Then calculating the value of the expression is easy. Consider process of calculating $f(x)$. Suppose we found optimal answer. Represent this answer as sequence of integers $d_{1}, d_{2}, ..., d_{k}$ - on the first stage we will divide girls into groups of $d_...
[ "brute force", "dp", "greedy", "math", "number theory" ]
1,800
const int maxn = 5000500; int isPrime[maxn]; ll dp[maxn]; int main() { int t, l, r; scanf ( "%d%d%d", &t, &l, &r ); for ( int j = 2; j < maxn; j++ ) isPrime[j] = j; for ( int j = 2; j * j < maxn; j++ ) if ( isPrime[j] == j ) for ( int i = j * j; i < maxn; i += j ) ...
822
E
Liar
The first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length $m$ from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, ...
Formally, you were given two strings $s$ and $t$. Also number $x$ was given. You need to determine whether condition $f(s, t) \le x$ is satisfied. $f(s, t)$ is equal to the minimal number of non-intersect substrings of string $s$ which can be concatenated together to get $t$. Substrings should be concatenated in the ...
[ "binary search", "dp", "hashing", "string suffix structures" ]
2,400
import java.io.*; import java.util.*; public class Main implements Runnable { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in), 1 << 20); tokenizer = null...
822
F
Madness
The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study. Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory....
Firstly let's notice the fact that in the optimal answer each of the paths consists of exactly one edge. Let's choose one particular vertex. Let's the degree of this vertex is $deg$. The most optimal answer for this vertex is $\frac{2}{d e c g}$, because one point make a full loop of the edge in $2$ seconds. Vetrex wit...
[ "constructive algorithms", "dfs and similar", "trees" ]
2,500
const int maxn = 105; vector < pair < int, int > > edge[maxn]; int used[maxn]; int from[maxn]; int where[maxn]; ld dist[maxn]; void dfs( int v, ld prevTime ) { used[v] = true; int sz = edge[v].size(); ld bestTime = 2.0L / sz; ld nextTime = prevTime + bestTime; if ( nextTime >= 2.0L ) nextT...
825
A
Binary Protocol
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: - Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). - Digits are written one by one in order...
Let's decode the number digit by digit starting from the leftmost. When you meet '1' in the string, increase the value of the current digit. For '0' print current digit and proceed to the next one. Don't forget to print the last digit when the string is over. Overall complexity: $O(|s|)$.
[ "implementation" ]
1,100
null
825
B
Five-In-a-Row
Alice and Bob play 5-in-a-row game. They have a playing field of size $10 × 10$. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins i...
This one is a pure implementation task. Just check every possible line of length 5. If the current one contains 4 crosses and 1 empty cell then the answer is 'YES'.
[ "brute force", "implementation" ]
1,600
null
825
C
Multi-judge Solving
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty $d$ on Decoforces is as hard as the problem with difficulty $d$ on any other judge)....
Obviously sorting the tasks by difficulty will always produce the most optimal order of solving. In that case ability to solve some task $i$ will mean ability to solve any task from $1$ to $i - 1$. Now let's maintain the upper limit of difficulty of problem Makes is able to solve. Right after solving some problem $i$ i...
[ "greedy", "implementation" ]
1,600
null
825
D
Suitable Replacement
You are given two strings $s$ and $t$ consisting of small Latin letters, string $s$ can also contain '?' characters. Suitability of string $s$ is calculated by following metric: Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all ...
Notice that the order of letters doesn't matter at all, suitability depends only on amount of each letter. Let $f_{i}$ be the possibility that string $t$ will occur in $s$ at least $i$ times after replacing all '?' signs and after some swaps. If $f_{i}$ is true then $f_{i - 1}$ is also true. That leads to binary search...
[ "binary search", "greedy", "implementation" ]
1,500
null
825
E
Minimal Labels
You are given a directed acyclic graph with $n$ vertices and $m$ edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: - Labels form a valid permutation of length $n$ — an integer sequence such that each i...
This problem is usually called "Topological labelling". Though it's pretty common problem, we decided that it might be educational to some of participants. Let's set labels in descending order starting from label $N$ to label $1$. Look at first step. Vertex with label $N$ should have out-degree equal to zero. Among all...
[ "data structures", "dfs and similar", "graphs", "greedy" ]
2,300
null
825
F
String Compression
Ivan wants to write a letter to his friend. The letter is a string $s$ consisting of lowercase Latin letters. Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string $s$ instea...
Let $dp[i]$ be the answer for the prefix of $s$ consisting of $i$ first characters. How can we update $dp[j]$ from $dp[i]$ ($i < j$)? Suppose that we try to represent the substring from index $i$ to index $j - 1$ ($0$-indexed) by writing it as some other string $k$ times. Then this string has to be the smallest period ...
[ "dp", "hashing", "string suffix structures", "strings" ]
2,400
null
825
G
Tree Queries
You are given a tree consisting of $n$ vertices (numbered from $1$ to $n$). Initially all vertices are white. You have to process $q$ queries of two different types: - $1$ $x$ — change the color of vertex $x$ to black. It is guaranteed that the first query will be of this type. - $2$ $x$ — for the vertex $x$, find the...
After the first query make the vertex that we painted black the root of the tree and for each other vertex calculate the minimum index on the path to the root. This can be done by simple DFS. Then suppose we are painting some vertex $x$ black. In can easily proved that for every vertex $y$ and every vertex $z$ that is ...
[ "dfs and similar", "graphs", "trees" ]
2,500
null
827
A
String Reconstruction
Ivan had string $s$ consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string $s$. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string $s$. Namely, he remembers, that string $t_{i}$ occurs in string $s$ at least $k_{...
At first let's sort all given string by their positions and also determine the length of the answer string. After that fill the answer string with letters "a" because the answer string must be lexicographically minimal. Let's use variable $prev$ - the minimal index of letter in the answer string which did not already p...
[ "data structures", "greedy", "sortings", "strings" ]
1,700
null
827
B
High Load
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of $n$ nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly $k$ of the nodes should be exit-nodes, that means that each of them should...
Hint: one of the optimal solutions is a star-like tree: one "center" node with $k$ paths with lengths difference at most one. Proof: let the optimal answer be something different from the structure described. If it is a star with $k$ paths, but the lengths differ by more than one, we can shorten the longest one and len...
[ "constructive algorithms", "greedy", "implementation", "trees" ]
1,800
null
827
C
DNA Evolution
Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string $s$ initially. Evolution of the species is described as a sequence of changes ...
Note that there are only $4$ different characters and queries' lengths are only up to $10$. How does this help? Let's make $4$ arrays of length $|s|$ for each of the possible letters, putting $1$ where the letter in $s$ is that letter, and $0$ otherwise. We can update these arrays easily with update queries. Consider a...
[ "data structures", "strings" ]
2,100
null
827
D
Best Edge Weight
You are given a connected weighted graph with $n$ vertices and $m$ edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id $i$. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change t...
Hint 1: Find some MST in the initial graph and name it $M$. Now there are edges of two types: in the tree, and not in the tree. Process them in a different way. Hint 2: For edges not in the MST, the answer is the maximum weight of MST edges on the path between the edge's ends, minus one. Proof: Consider the edge $E$ su...
[ "data structures", "dfs and similar", "graphs", "trees" ]
2,700
null
827
E
Rusty String
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length $n$ and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written. Grigory couldn't understand for a long time what these letters remind hi...
Let $s_{i}$ is symbol number $i$ from the given string. Statement: $k$ can be period of string $s$ when if and only if there are no two indices $i$ and $j$ for which $s_{i}\neq s_{j},s_{i}\neq?\gamma,s_{j}\neq7,t{\mathrm{~}}\mathrm{~}\mathrm{mod}\;k=j\mathrm{~mod}\;k$. Evidence: Necessity: Let it is not true. Then for ...
[ "fft", "math", "strings" ]
2,700
null
827
F
Dirty Arkady's Kitchen
Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during...
Let's consider undirected edge$(u;v)$ as two directed edges $(u;v)$ and $(v;u)$. Let Arkady came to the vertex $u$ in moment of time $t$. Then he can come to $v$ in moments of time $t + 1, t + 3, ...$ until the edge is existing. We will expand each directed edge: on one of them we can come in even moments of time and l...
[ "data structures", "dp", "graphs", "shortest paths" ]
3,200
null
828
A
Restaurant Tables
In a small restaurant there are $a$ tables for one person and $b$ tables for two persons. It it known that $n$ groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater ...
We need to store three values: $a$ - the number of free tables for one person, $b$ - the number of free tables for two persons and $c$ - the number of tables for two persons occupied by single person. If the next group consisting of $2$ persons and there are no free tables for two persons (i. e. $b = = 0$) the restaura...
[ "implementation" ]
1,200
null
828
B
Black Square
Polycarp has a checkered sheet of paper of size $n × m$. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minimum possibl...
If there are no black cells on the field it is enough to paint any one cell. In the other case, we need to calculate $4$ values: $minX$ - the index of upper row with black cell; $maxX$ - the index of bottom row with black cell; $minY$ - the index of leftmost column with black cell; $maxY$ - the index of rightmost colum...
[ "implementation" ]
1,300
null
830
A
Office Keys
There are $n$ people and $k$ keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine th...
To solve this problem you need to understand the fact that all keys which people will take is continuous sequence of length $n$ in sorted array of keys. At first let's sort all keys in increasing order of their positions. Then brute which of the keys will take a leftmost person. Let it will be $i$-th key. Then the seco...
[ "binary search", "brute force", "dp", "greedy", "sortings" ]
1,800
null
830
B
Cards Sorting
Vasily has a deck of cards consisting of $n$ cards. There is an integer on each of the cards, this integer is between $1$ and $100 000$, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the num...
First note that operation "put a card under the deck" is the same as "stark viewing from the beginning when you reach the end", and do not move cards anywhere. Then, let's proceed all cards with equal numbers on them at once. It's obvious that Vasily puts them away one after another. Let's denote the position where he ...
[ "data structures", "implementation", "sortings" ]
1,600
null
830
C
Bamboo Partition
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are $n$ bamboos in a row, and the $i$-th from the left is $a_{i}$ meters high. Vladimir has just planted $n$ bamboos in a ro...
First fact: The problem is asking to maximize $d$ such that: $\textstyle\sum_{i=1}^{n}(d\lceil{\frac{a_{i}}{d}}\rceil-a_{i})\leq k$. $\textstyle{\sum_{i=1}^{n}(d\left[{\frac{a_{i}}{d}}\right]-a_{i})\leq k\Rightarrow d\sum_{i=1}^{n}\left[{\frac{a_{i}}{d}}\right]\leq k+\sum_{i=1}^{n}a_{i}}$. Let $C=k+\textstyle\sum_{i=1}...
[ "brute force", "data structures", "implementation", "math", "number theory", "sortings", "two pointers" ]
2,300
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e2 + 17, maxsq = sqrt(1e9); const ll inf = 1e12; int n, a[maxn], sz; ll C, seg[maxn * 2 * maxsq]; int ceil(int n, int r){ return (n + r - 1) / r; } int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n ...
830
D
Singer House
It is known that passages in Singer house are complex and intertwined. Let's define a Singer $k$-house as a graph built by the following process: take complete binary tree of height $k$ and add edges from each vertex to all its successors, if they are not yet present. \begin{center} {\small Singer $4$-house} \end{cent...
Hint: Compute dp[k][c] "what is the number of sets of $c$ non-intersecting paths in $k$-house?" Yes, it works. The answer is dp[k][1]. $dp_{1, 0} = dp_{1, 1} = 1$. For updating $dp_{i}$ from $dp_{i - 1}$ for each $L, R(1 \le L, R \le 2^{i - 1})$ Let $X = dp_{i - 1, L} \cdot dp_{i - 1, R}$: Take the root, and make i...
[ "combinatorics", "dp", "graphs", "trees" ]
2,800
null
830
E
Perpetual Motion Machine
Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way. Each element has one controller that can be set to any non-negative real value. If a controller is set on some value $x$, then the controller consumes $x^{2}$ energy units per second. A...
By default, all vertices contain $0$. We will solve problem in few steps, getting answer for our question in different cases. Graph contains cycle. In this case, solution exists, all vertices of cycle contain $1$, sum would be $0$. Graph contains vertex with degree more than $3$. Solution exists, this vertex has $2$ an...
[ "constructive algorithms", "dp", "graphs", "implementation", "math", "trees" ]
3,100
null
831
A
Unimodal Array
Array of integers is unimodal, if: - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arrays ...
Let use two variables $pos_{1}$ and $pos_{2}$. Initially $pos_{1} = 0$ and $pos_{2} = n - 1$. After that we need to iterate through the given array from the left to the right and increase $pos_{1}$ until the next element is strictly more than previous. After that we need to iterate through the given array from the righ...
[ "implementation" ]
1,000
null
831
B
Keyboard Layouts
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with $26$ letters which coincides with English alphabet. You are given two strings consisting of $26$ distinct letters each: all keys of the first and the second layou...
At first we need to support the correspondence of letters on keyboards. For example, it can be done with help of $map < char, char >$. Let's call it $conformity$. Let the first layout equals to $s_{1}$ and the second - $s_{2}$. Now we need to iterate through the first string and make $conformity[s_{1}[i]] = s_{2}[i]$. ...
[ "implementation", "strings" ]
800
null
831
C
Jury Marks
Polycarp watched TV-show where $k$ jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the $i$-th jury member gave $a_{i}$ p...
At first let's calculate an array $sum$ where $sum[i]$ equals to sum of the first $i$ jury points. Now consider the value $b_{1}$. Let the initial score equals to $x$. Here we need to iterate by $m$ from $1$ to $k$ - how many members of jury rated the participant until Polycarp remembered $b_{1}$. Then $x = b_{1} - sum...
[ "brute force", "constructive algorithms" ]
1,700
null
832
A
Sasha and Sticks
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws $n$ sticks in a row. After that the players t...
Note, that it's not important from which side sticks are being crossing out. Players will make summary $\left\lfloor{\frac{22}{k}}\right\rfloor$ turns. If this number is odd, Sasha made $1$ more turn than Lena and won. Otherwise, Sasha and Lena made same number of turns and Sasha didn't win.
[ "games", "math" ]
800
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 17, lg = 17; ll n, k; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; cout << ((n / k) & 1 ? "YES" : "NO") << '\n'; return 0; }
832
B
Petya and Exam
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is kno...
If pattern doesn't contain "*", to match pattern, it's neccesary that string's size is equal to pattern size , all letters in pattern match with the letters in string, and in the positions on which pattern contains "?", the string contains good characters. If pattern contains "*", split it into two strings: $p_{1}$ con...
[ "implementation", "strings" ]
1,600
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 17, z = 26; int n; bool good[z]; string goods, pat; bool mat(string pat, string s){ if(pat.size() != s.size()) return 0; for(int i = 0; i < s.size(); i++) if(pat[i] != '?'){ if(s[i] != pat[i]) return 0; } else ...
832
C
Strange Radiation
$n$ people are standing on a coordinate axis in points with positive integer coordinates strictly less than $10^{6}$. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all...
We'll use binary search by answer. Obviously, that answer is always less than $10^{6}$ and more than $0$. We denote the answer for $t$ at current iteration. For each person, running left, we have to find positions of bomb, at which he will have time to reach the point $0$ in time $t$. Let $d$ be the distance between th...
[ "binary search", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x...
832
D
Misha, Grisha and Underground
Misha and Grisha are funny boys, so they like to use new underground. The underground has $n$ stations connected with $n - 1$ routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morni...
Let vertex $1$ be the root of the tree. For each vertex $i$ we calculate value $h_{i}$ - distance to the root. Now we can represent way $v_{1}$ $\to$ $v_{2}$ as two ways $v_{1}$ $\to$ $lca(v_{1}, v_{2})$ and $lca(v_{1}, v_{2})$ $\to$ $v_{2}$. Note that number of edges in the interseption of two such ways $v_{1}$ $\to$ ...
[ "dfs and similar", "graphs", "trees" ]
1,900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 17, lg = 17; int n, q, par[maxn][lg], h[maxn], ver[3]; vector<int> g[maxn]; void dfs(int v = 0){ for(int i = 1; i < lg; i++) par[v][i] = par[ par[v][i - 1] ][i - 1]; for(auto u : g[v]){ h[u] = h[v] ...
832
E
Vasya and Shifts
Vasya has a set of $4n$ strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into $n$ groups of $4$ equal strings each. Vasya also has one special string $a$ of the same length, consisting of letters "a" only. Vasya wants to obtain from string $a$ some...
The first thing to notice is that the problem can be reduced to a matrix form. To do this quite easily, we note that if we denote $x_{i}$ as the number of times we apply the $i$-th row, then we will get the matrix, we will have exactly $n$ columns ($x_{i}$) and $m$ rows. That is, $A_{ij}$ will match the $i$-th symbol i...
[ "matrices" ]
2,600
#include <bits/stdc++.h> using namespace std; #define ll long long #define ABS(x) ((x) < 0 ? -(x) : (x)) const int N = 500, MODM = 1e9 + 7; int matr_divide[5][5]; ll bin_pow(ll a, ll b, ll pp) { if (b == 0) return 1; if (b == 1) return a % pp; if (b & 1) return a * bin_pow(...
833
A
The Meaningless Game
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number $k$ is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is...
Prequisites: none (maybe binary search). Let $S$ denote the product of the set of numbers said by Slastyona, and $P$ denote the product of the set of numbers barked by Pushok (in case one of the sets is empty the corresponding product is assumed to be equal to one). Then, we can reformulate the problem in a following w...
[ "math", "number theory" ]
1,700
#include <cmath> #include <cstdio> using namespace std; typedef long long ll; const int MAXR = 1000005; ll cubic_root(ll x) { ll l = 0, r = MAXR; while (l != r) { ll m = (l + r + 1) / 2; if (m * m * m > x) r = m - 1; else l = m; } return l; } int...
833
B
The Bakery
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery. Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack ca...
Prerequisites: dp + segment trees All authors' solutions are based on the following dp idea: let's calculate $dp(k, n)$ - the maximum cost we can obtain if we assign the first $n$ cakes to $k$ boxes. For $k = 1$ the answer is equal to the number of distinct values on a prefix. For $k > 1$ the answer can be deduced as f...
[ "binary search", "data structures", "divide and conquer", "dp", "two pointers" ]
2,200
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #i...
833
C
Ever-Hungry Krakozyabra
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner. Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislike...
Prerequisites: Combinatorics or strong faith :) At first we might assume (without loss of generality) that both left and right bounds are strictly less than $10^{18}$ (otherwise we just append $1$ to the list of unedible tails) and hence consider only numbers with no more than 18 decimal digits. Notice that there are n...
[ "brute force", "combinatorics", "greedy", "math" ]
2,700
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #i...
833
D
Red-Black Cobweb
Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb. The cobweb is a set of $n$ nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread connects...
Prequisites: centroid decomposition, segment tree / BIT / treap, modulo division Analogically to the vast variety of problems where we are to find some information about all the paths of the tree at once, we can use centroid decomposition as a basis. Let us fix some centroid and some path consisting of $r$ red and $b$ ...
[ "data structures", "divide and conquer", "implementation", "trees" ]
2,800
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #i...
833
E
Caramel Clouds
It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has $m$ seedlings, and the $j$-th seedling needs at least $k_{j}$ minutes of sunlight to grow up. Most of the time it's sunny in Sweetland, but sometimes some caramel clou...
Prequisites: scanline. The key idea is that only minutes which are covered by no more than two clouds can contribute to the answer. Let us demonstrate how to solve the problem for a fixed $k$ using scanline. Let's create $2 \cdot n$ events: for the start and the end of each cloud. We will then go through all the events...
[ "data structures", "dp", "sortings" ]
3,400
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <unordered_set> #include <vector> #include <cmath> #include <string> #include <set> #include <map> #include <cstdio> #include <functional> #include <random> #include <ctime> #include <cassert> #include <bitset> #include <unordered_map> #i...
834
A
The Useless Toy
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of caramel. Each s...
Prequisites: none. The sole fact that the spinner has four positions, which are repeated periodically, leads us to the following observations that are easily verifiable: first thing is that no matter what the direction was, when $k$ is even we're going to get the same ending position; secondly, if we replace $n$ by $n{...
[ "implementation" ]
900
DIRS = ['v', '<', '^', '>'] a, b = map(DIRS.index, input().split()) n = int(input()) delta = (b - a + 4) % 4 if delta == 0 or delta == 2: print('undefined') elif delta == n % 4: print('cw') else: print('ccw')
834
B
The Festive Evening
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom...
Prerequisites: none. This problem is solved with two linear sweeps. In the first one, we determine the last position for each letter. In the second one, we just model the process: we mark the letter as active when we stumble upon it for the first time, and as inactive when we reach the last position for this letter. If...
[ "data structures", "implementation" ]
1,100
#include <iostream> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; unordered_map<char, int> last_pos; unordered_set<char> active; int main() { int n, k; string s; cin >> n >> k >> s; for (int i = 0; i < n; i++) { last_pos[s[i]] = i; } f...
835
A
Key races
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of $s$ characters. The first participant types one character in $v_{1}$ milliseconds and has ping $t_{1}$ milliseconds. The second participant types one character in $v_{2}$ milliseconds and h...
Information on the success of the first participant will come in $2 \cdot t_{1} + v_{1} \cdot s$ milliseconds, of the second participant - in $2 \cdot t_{2} + v_{2} \cdot s$ milliseconds. We need to compare these numbers and print the answer depending on the comparison result.
[ "math" ]
800
s, v1, v2, t1, t2 = map(int, input().split()) q1 = 2 * t1 + s * v1 q2 = 2 * t2 + s * v2 if q1 < q2: print('First') elif q1 > q2: print('Second') else: print('Friendship')
835
B
The number on the board
Some natural number was written on the board. Its sum of digits was not less than $k$. But you were distracted a bit, and someone changed this number to $n$, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbe...
Let's rephrase the problem a little. Suppose that we initially have a number $n$ and we need to make a number from it with the sum of digits at least $k$, changing as fewer digits as possible. Obviously, it is optimal to replace the digit with $9$. When we replace digit $d$ with $9$, we increase the sum by $9 - d$. It ...
[ "greedy" ]
1,100
k = int(input()) n = input() digits = [] for c in n: digits.append(ord(c) - ord('0')) digits.sort() cur = sum(digits) ans = 0 for d in digits: if cur < k: cur += 9 - d ans += 1 print(ans)
835
C
Star sky
The Cartesian coordinate system is set in the sky. There you can see $n$ stars, the $i$-th has coordinates ($x_{i}$, $y_{i}$), a maximum brightness $c$, equal for all stars, and an initial brightness $s_{i}$ ($0 ≤ s_{i} ≤ c$). Over time the stars twinkle. At moment $0$ the $i$-th star has brightness $s_{i}$. Let at mo...
The brightness of the $i$-th star in moment $t$ is $(s_{i}+t_{i})~\mathrm{mod}~(c+1)$, where $\mathrm{mod}$ is modulo operator. Let's precalc for each $p = 0...C$, $x = 1...100$, $y = 1...100$ $cnt[p][x][y]$ - the number of stars with the initial brightness $p$ in the rectangle ($1$; $1$)-($x$; $y$). It is calculated l...
[ "dp", "implementation" ]
1,600
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { new Solution().run(); } } class Solution { final int MAX_CORD = 100; Scanner in; Buffe...
835
D
Palindromic characteristics
Palindromic characteristics of string $s$ with length $|s|$ is a sequence of $|s|$ integers, where $k$-th number is the total number of non-empty substrings of $s$ which are $k$-palindromes. A string is $1$-palindrome if and only if it reads the same backward as forward. A string is $k$-palindrome ($k > 1$) if and on...
Observation I. If the string is $k$-palindrome, then it is ($k - 1$)-palindrome. Observation II. The string is $k$-palindrome if and only if the both following conditions are true: It is a palindrome. It's left half is non-empty ($k - 1$)-palindrome. Solution. Let's calculate the following dp. $dp[l][r]$ is the maximum...
[ "brute force", "dp", "hashing", "strings" ]
1,900
s = input() n = len(s) dp = [[0 for i in range(n - le + 1)] for le in range(n + 1)] ans = [0 for i in range(n + 1)] for le in range(1, n + 1): for l in range(0, n - le + 1): r = l + le if s[l] != s[r - 1]: continue if le == 1: dp[1][l] = 1 ans[1] += 1 ...
835
E
The penguin's game
Pay attention: this problem is interactive. Penguin Xoriy came up with a new game recently. He has $n$ icicles numbered from $1$ to $n$. Each icicle has a temperature — an integer from $1$ to $10^{9}$. \textbf{Exactly two} of these icicles are special: their temperature is $y$, while a temperature of all the others is...
The solution can be separated into several parts. I. Finding the parity of the number of special icicles in the given subset using 1 question. Consider the following cases: Subset's size is even, the number of special icicles in it is even. Then the answer to such question is $0$. Subset's size is even, the number of s...
[ "binary search", "constructive algorithms", "interactive" ]
2,400
#include <bits/stdc++.h> using namespace std; int n, x, y; int ask(const vector<int> &a) { if (a.empty()) { return 0; } cout << "? "; cout << a.size() << " "; for (int el : a) { cout << el << " "; } cout << endl; int res; cin >> res; return res; } int solv...
835
F
Roads in the Kingdom
In the Kingdom K., there are $n$ towns numbered with integers from $1$ to $n$. The towns are connected by $n$ bi-directional roads numbered with integers from $1$ to $n$. The $i$-th road connects the towns $u_{i}$ and $v_{i}$ and its length is $l_{i}$. There is no more than one road between two towns. Also, there are n...
Observation I. The given graph is a cycle with hanged trees. So, we can remove the edge only from the cycle, the resulting graph will be a tree. Observation II. We can minimize the distances only between the pairs of vertexes such that path between them goes through the cycle's edges. Let's say that these pairs are int...
[ "dfs and similar", "dp", "graphs", "trees" ]
2,500
#include <iostream> #include <vector> #include <cassert> #include <algorithm> using namespace std; const int N = (int) 2e5 + 2; const long long INF = (long long) 1e18 + 123; int n; vector<pair<int, int>> g[N]; vector<int> cycle; int color[N]; bool vis[N]; long long depth[N], weight[N]; long long pref_diam[N], suf...
837
A
Text Volume
You are given a text of single-space separated words, consisting of small and capital Latin letters. Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text. Calculate the volume of the given text.
Maintain the amount of capital letters taken by going from left to right, make it zero when you meet space. Overall complexity: $O(n)$.
[ "implementation" ]
800
null
837
B
Flag of Berland
The flag of Berland is such rectangular field $n × m$ that satisfies following conditions: - Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. - Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has \textbf{exactly one color...
There are lots of ways to check correctness. For example, you can keep boolean array with already used colors, check stripes naively and mark the color used if the stripe has single color. If all the colors are used in the end then the answer is YES. Overall complexity: $O(n \cdot m)$.
[ "brute force", "implementation" ]
1,600
null
837
C
Two Seals
One very important person has a piece of paper in the form of a rectangle $a × b$. Also, he has $n$ seals. Each seal leaves an impression on the paper in the form of a rectangle of the size $x_{i} × y_{i}$. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees). A ...
If you can place two rectangles in some way (without rotations), then it's always possible to move one of them to the top left corner and stick the other either to the bottom of the first (and push it all the way to the left) or to the right of it (and push it all the way to the top). Now let's try all possible reorder...
[ "brute force", "implementation" ]
1,500
null
837
D
Round Subset
Let's call the roundness of the number the number of zeros to which it ends. You have an array of $n$ numbers. You need to choose a subset of exactly $k$ numbers so that the roundness of the product of the selected numbers will be maximum possible.
Let's use dynamic programming to solve this task. Obviously, the roundness of the number is determined by minimum of powers of 2 and 5 in the number. Let $pw5_{i}$ be the maximal power of 5 in the number and $pw2_{i}$ be the maximal power of 2. Let $dp[i][j][l]$ be the maximum amount of twos we can collect by checking ...
[ "dp", "math" ]
2,100
null
837
E
Vasya's Function
Vasya is studying number theory. He has denoted a function $f(a, b)$ such that: - $f(a, 0) = 0$; - $f(a, b) = 1 + f(a, b - gcd(a, b))$, where $gcd(a, b)$ is the greatest common divisor of $a$ and $b$. Vasya has two numbers $x$ and $y$, and he wants to calculate $f(x, y)$. He tried to do it by himself, but found out t...
One important fact is that when we subtract $gcd(x, y)$ from $y$, new $gcd(x, y)$ will be divisible by old $gcd(x, y)$. And, of course, $x$ is always divisible by $gcd(x, y)$. Let's factorize $x$. Consider the moment when $gcd(x, y)$ changes. If we denote old value of $gcd(x, y)$ by $g$, the new value of $gcd(x, y)$ wi...
[ "binary search", "implementation", "math" ]
2,100
null
837
F
Prefix Sums
Consider the function $p(x)$, where $x$ is an array of $m$ integers, which returns an array $y$ consisting of $m + 1$ integers such that $y_{i}$ is equal to the sum of first $i$ elements of array $x$ ($0 ≤ i ≤ m$). You have an infinite sequence of arrays $A^{0}, A^{1}, A^{2}...$, where $A^{0}$ is given in the input, a...
Let's delete all zeroes from the beginning of the array; they won't affect the answer. Also we will return an array of $m$ elements when calculating prefix sums (sum of zero elements becomes a zero in the beginning of the array, and so has to be removed). If the size of array is at least $10$, then we will get $k$ afte...
[ "binary search", "brute force", "combinatorics", "math", "matrices" ]
2,400
null
837
G
Functions On The Segments
You have an array $f$ of $n$ functions.The function $f_{i}(x)$ ($1 ≤ i ≤ n$) is characterized by parameters: $x_{1}, x_{2}, y_{1}, a, b, y_{2}$ and take values: - $y_{1}$, if $x ≤ x_{1}$. - $a·x + b$, if $x_{1} < x ≤ x_{2}$. - $y_{2}$, if $x > x_{2}$. There are $m$ queries. Each query is determined by numbers $l$, $r...
Let's build a data structure that allows us to find sum of functions on some prefix. The answer to the query can be obviously obtained using two answers on prefixes. We will use some persistent data structure that handles prefix sum queries - persistent segment tree, for example. We will actually use two different stru...
[ "data structures" ]
2,500
null
838
A
Binary Blocks
You are given an image, that can be represented with a $2$-d $n$ by $m$ grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer $k > 1$ and split the image into $k$ by $k$ blocks. If $n$ and $m$...
Let's define function $onesInRect(sx, sy, ex, ey)$ as number of ones in rectangle with top-left $(sx, sy)$ and down-right $(ex - 1, ey - 1)$ (0-based). Let $ps_{i, j}$ the number of ones in rectangle with top-left $(0, 0)$ and down-right $(i - 1, j - 1)$ (0-based). $ps_{i, j} = ps_{i - 1, j} + ps_{i, j - 1} - ps_{i - 1...
[ "brute force" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() const int maxn = 2505; int pr[maxn][maxn]; int n, m; int cost(int x1, int y1, int x2, int y2) { if (x...
838
B
Diverging Directions
You are given a directed weighted graph with $n$ nodes and $2n - 2$ edges. The nodes are labeled from $1$ to $n$, while the edges are labeled from $1$ to $2n - 2$. The graph's edges can be split into two parts. - The first $n - 1$ edges will form a rooted spanning tree, with node $1$ as the root. All these edges will ...
For each second type of query, there are two options: $u$ is an ancestor of $v$. $u$ isn't an ancestor of $v$.Let's define distance $v$ from root be $disFromRoot_{v}$. Answer of the first type of second query is obviously $disFromRoot_{v} - disFromRoot_{u}$. Let's define minimum possible distance $v$ from some node in ...
[ "data structures", "dfs and similar", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() int n; const int maxn = 200200; ll wup[maxn]; ll wroot[maxn]; int eid[maxn * 2]; vector<int> g[maxn]; ...
838
C
Future Failure
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists $n$ characters, each of which is one of the first $k$ letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if th...
Let the frequencies of the characters be $a_{1}, a_{2}, ..., a_{k}$. Alice loses if and only if $\left({}_{a_{1},a_{2},\ldots,a_{k}}\right)$ is odd and $n$ is even. So, if $n$ is odd, answer is $k^{n}$. Otherwise, we have to count number of $a_{1}, a_{2}, ..., a_{k}$ such that $a_{1} + a_{2} + ... + a_{k} = n$ and $\fr...
[ "dp", "games" ]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() int mod; void udd(int &a, int b) { a += b; if (a >= mod) a -= mod; } void uub(int &a, int b) { ...
838
D
Airplane Arrangements
There is an airplane which has $n$ rows from front to back. There will be $m$ people boarding this airplane. This airplane has an entrance at the very front and very back of the plane. Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the...
Consider adding an extra seat, and the plane is now circular. Now the number of ways such that $n + 1$-th seat becomes empty is the answer. For each seat there is $\frac{(2\cdot(n+1))^{2m}\cdot(n+1\!-\!m)}{n\!+\!1}$
[ "math", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() const int mod = 1e9 + 7; void udd(int &a, int b) { a += b; if (a >= mod) a -= mod; } int mul(ll ...
838
E
Convex Countour
You are given an strictly convex polygon with $n$ vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once. More specifically your path can be represented as some sequence of distinct polygon vertic...
Let $dp_{i, j}$ be the longest path given that we've included segment $i, j$ in our solution, and we are only considering points to the right of ray $i, j$ (so $dp_{i, j}$ and $dp_{j, i}$ may be different). This leads to an $O(n^{3})$ solution. The optimal solution will pass from all of the points, so let's define $dp_...
[ "dp" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() struct pt { ld x, y; pt operator-(const pt &p) const { return pt{x - p.x, y - p.y}; } ld abs() const { re...
838
F
Expected Earnings
You are playing a game with a bag of red and black balls. Initially, you are told that the bag has $n$ balls total. In addition, you are also told that the bag has probability $p_{i} / 10^{6}$ of containing exactly $i$ red balls. You now would like to buy balls from this bag. You really like the color red, so red ball...
We want to compute $dp_{i, j}$: expected value given we have seen $i$ red balls and $j$ black balls. Final answer is $dp_{0, 0}$. Now, to compute $dp_{i, j}$, we either take a ball or don't. Let $p_{i, j}$ be the probability that after we have seen $i$ red balls and $j$ black balls the next ball is red. Then, $dp_{i, j...
[]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() ld fact[100100]; const int maxn = 10005; ld d[2][maxn]; ld p[2][maxn]; signed main() { #ifdef LOCAL assert(fre...
839
A
Arya and Bran
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have $0$ Candies. There are $n$ days, at the $i$-th day, Arya finds $a_{i}$ candies in a box, that is given by the Many-Faced God. Every day she can give Bran \textbf{at...
Let $t$ be number of her candies. At $i$-th day , we increase $t$ by $a_{i}$ ,then we give Bran $min(8, t)$ . So we decrease $k$ from this value. We will print the answer once $k$ becomes smaller or equal to $0$ . Or we will print $- 1$ if it does'n happen after $n$ days.
[ "implementation" ]
900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e2 + 17; int n, k, cur, ans; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; while(n--){ int x; cin >> x; cur += x; int r = min(8, cur); cur -= r; k -= r; ans++; if(k <= 0) break; } if(k > 0)...
839
B
Game of the Rows
Daenerys Targaryen has an army consisting of $k$ groups of soldiers, the $i$-th group contains $a_{i}$ soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has $n$ rows, each of them has $8$ seats. ...
Use greedy solution. Consider a group with $x \ge 4$ members, put $4$ of them in seats [3, 6] of some row, and throw the row. Now we have $x - 4$ members in this group now. Continue till all of the seats in the range $[3, 6]$ become full, continue with $[1, 2]$ and $[7, 8]$. Now handle groups with size $ \le 3$. For...
[ "brute force", "greedy", "implementation" ]
1,900
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; const int maxn = 1e2 + 17; int n, k, have[5], cnt[5]; int main(){ ios::sync_with_stdio(0), cin.tie(0); cin >> n >> k; have[2] = 2 * n, have[4] = n; for(int i = 0; i < k; i++){ int x; cin >> x; while(x >= 3) if(have[4] > 0) x -= 4, h...
839
C
Journey
There are $n$ cities and $n - 1$ roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings t...
Let the cities be vertices and roads be edges of a tree and vertex $1$ be the root of the tree. Let $ans[i]$ be the answer for the $i$-th vertex (the expected value if they start their journey from that vertex and the horse doesn't go to it's parent). Now we can calculate $ans[i]$ by knowing the answer for it's childre...
[ "dfs and similar", "dp", "graphs", "probabilities", "trees" ]
1,500
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long double ld; const int maxn = 2e5 + 17, maxv = 1e6 + 17, mod = 1e9 + 7; int n; vector<int> g[maxn]; ld dfs(int v = 0, int p = -1){ ld sum = 0; for(auto u : g[v]) if(u != p) sum += dfs(u, v) + 1; return sum ? sum / (g[v].size() - (...
839
D
Winter is here
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of $n$ soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the $i$-th soldier’s stre...
1st method: Let $cnt[i]$ be the number of such $j$s that $a_{j}$ is divisible by $i$. Also let $p[i]$ be $i$-th prime number. Let $f(m)$ be $\textstyle\sum_{x\subseteq S}s i z e(x)$ for an arbitrary set with $m$ members(something like the sum of strengths of all possible subsets, but replace $1$ with the $gcd$ of the s...
[ "combinatorics", "dp", "math", "number theory" ]
2,200
//sobskdrbhvk //remember the flying, the bird dies ):( #include <bits/stdc++.h> using namespace std; typedef long long int LL; typedef pair<int, int> pii; typedef pair<LL, LL> pll; #define PB push_back #define MP make_pair #define L first #define R second #define sz(x) ((int)(x).size()) #define smax(x, y) ((x) = ...
839
E
Mother of Dragons
There are $n$ castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has ...
Lemma : Let $G$ be a simple graph. To every vertex of $G$ we assign a nonnegative real number such that the sum of the numbers assigned to all vertices is $1$. For any two connected vertices (by an edge), compute the product of the numbers associated to these vertices. The maximal value of the sum of these products is ...
[ "brute force", "graphs", "math", "meet-in-the-middle" ]
2,700
// God & me // Fly ... #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 40, C = 20; int n, k, dp[1 << C]; ll adj[maxn]; int maxc(){ for(int i = 0; i < n; i++) for(int j = 0, x; j < n; j++) cin >> x, adj[i] |= (ll) (x || i == j) << j; for(int i = 1; i < (1 << max(0, n - C)); ...
840
A
Leha and Function
Leha like all kinds of strange things. Recently he liked the function $F(n, k)$. Consider all possible $k$-element subsets of the set $[1, 2, ..., n]$. For subset find minimal element in it. $F(n, k)$ — mathematical expectation of the minimal element among all $k$-element subsets. But only function does not interest h...
First of all, let's understand what is the value of $F(N, K)$. For any subset of size $K$, say, $a_{1}, a_{2}...a_{K}$, we can represent it as a sequence of numbers $d_{1}, d_{2}...d_{K + 1}$, so that $d_{1} = a_{1}$, $d_{1} + d_{2} = a_{2}$, ..., $\sum_{i=1}^{K+1}d_{i}=N+1$. We're interested in $E[d_{1}]$, expected va...
[ "combinatorics", "greedy", "math", "number theory", "sortings" ]
1,300
null
840
B
Leha and another game about graph
Leha plays a computer game, where is on each level is given a connected graph with $n$ vertices and $m$ edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer $d_{i}$, which can be equal to $0$, $1$ or $ - 1$. To pass the level, he needs to find a «good» subset of edges of t...
Model solution uses the fact that the graph is connected. We'll prove that "good" subset exists iff $- 1$ values among $d_{i}$ can be changed to $0 / 1$ so that $\sum_{i=1}^{n}d_{i}$ is even. If the sum can only be odd, there is no solution obviously (every single valid graph has even sum of degrees). Now we'll show ho...
[ "constructive algorithms", "data structures", "dfs and similar", "dp", "graphs" ]
2,100
null
840
C
On the Bench
A year ago on the bench in public park Leha found an array of $n$ numbers. Leha believes that permutation $p$ is right if for all $1 ≤ i < n$ condition, that $a_{pi}·a_{pi + 1}$ is not perfect square, holds. Leha wants to find number of right permutations modulo $10^{9} + 7$.
Let's divide all numbers into groups. Scan all numbers from left to right. Suppose that current position is $i$. If $group_{i}$ is not calculated yet, $i$ forms a new group. Assign unique number to $group_{i}$. Then for all $j$ such that $j > i$ and $a[j] \cdot a[i]$ is a perfect square, make $group_{j}$ equal to $grou...
[ "combinatorics", "dp" ]
2,500
null
840
D
Destiny
Once, Leha found in the left pocket an array consisting of $n$ integers, and in the right pocket $q$ queries of the form $l$ $r$ $k$. If there are queries, then they must be answered. Answer for the query is minimal $x$ such that $x$ occurs in the interval $l$ $r$ strictly more than $\textstyle{\frac{r-l+1}{k}}$ times ...
We will use classical divide and conquer approach to answer each query. Suppose current query is at subsegment $[L;R]$. Divide the original array into two parts: $[1;mid]$ and $[mid + 1;N]$, where $m i d={\frac{L+R}{2}}$. If our whole query belongs to the first or the second part only, discard the other part and repeat...
[ "data structures", "probabilities" ]
2,500
null
840
E
In a Trap
Lech got into a tree consisting of $n$ vertices with a root in vertex number $1$. At each vertex $i$ written integer $a_{i}$. He will not get out until he answers $q$ queries of the form $u$ $v$. Answer for the query is maximal value $a_{i}\oplus d i s t(i,v)$ among all vertices $i$ on path from $u$ to $v$ including $u...
The path from $u$ to $v$ can be divided into blocks of $256$ nodes and (possibly) a single block with less than $256$ nodes. We can consider this last block separately, by iterating all of its nodes. Now we need to deal with the blocks with length exactly $256$. They are determined by two numbers: $x$ - last node in th...
[ "trees" ]
3,200
null
841
A
Generous Kefa
One day Kefa found $n$ baloons. For convenience, we denote color of $i$-th baloon as $s_{i}$ — lowercase letter of the Latin alphabet. Also Kefa has $k$ friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out \textbf{all} baloons to his friends. Help Kefa to find out, can he give o...
Consider each balloon color separately. For some color $c$, we can only assign all balloons of this color to Kefa's friends if $c \le k$. Because otherwise, by pigeonhole principle, at least one of the friends will end up with at least two balloons of the same color. This leads us to a fairly simple solution: calcula...
[ "brute force", "implementation" ]
900
null
841
B
Godsend
Leha somehow found an array consisting of $n$ integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts...
First player wins if there is at least one odd number in the array. Let's prove this. Let's denote total count of odd numbers at $T$. There are two cases to consider: 1) $T$ is odd. First player takes whole array and wins. 2) $T$ is even. Suppose that position of the rightmost odd number is $pos$. Then the strategy for...
[ "games", "math" ]
1,100
null
842
A
Kirill And The Game
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers ...
Let's denote the potion's amount of experience as $exp$ and its cost as $cost$. We want to know if there is a potion such that $exp$ and $cost$ meet the following condition: $\stackrel{\alpha,p}{\omega,q}=k$. To do this, we can iterate on $cost$ from $x$ to $y$ and check that $exp = k \cdot cost$ is not less than $l$ a...
[ "brute force", "two pointers" ]
1,200
"#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nsigned main()\n{\n // k = exp / cost;\n int l, r, x, y, k;\n bool ans = 0;\n cin >> l >> r >> x >> y >> k;\n for (int i = x; i <= y; i++)\n {\n if (l <= i * k && i * k <= r)\n {\n ans = 1;\n }\n ...
842
B
Gleb And Pizza
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius $r$ and center at the origin. Pizza consists of the main part — circle of radius $r - d$ with center at the origin...
To understand whether some piece of sausage intersects with pizza, we can check if their borders intersect. And to check this, since their borders are circles, we are interested in their radii and the distance between their centers. To check if a piece of sausage is inside the crust, we firstly check that it is inside ...
[ "geometry" ]
1,100
"#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <vector>\n#include <string>\n#include <ctime>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n\n//#include <unordered_set>\n//#include <unordered_map>\n\n#define forn(i,...
842
C
Ilya And The Tree
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex $1$. There is an integer number written on each vertex of the tree; the number written on vertex $i$ is equal to $a_{i}$. Ilya believes that the beauty of the vertex $x$ is the greatest...
It's easy to see that if the number written on some vertex $i$ is not equal to $0$, then its beauty will be some divisor of $a_{i}$. Also if the number written on the root is $0$ then the beauty of each vertex can be easily calculated. Otherwise beauty of each vertex will be a divisor of the number in the root. Let's c...
[ "dfs and similar", "graphs", "math", "number theory", "trees" ]
2,000
"#include<bits/stdc++.h>\n#define f first\n#define s second\nusing namespace std;\n\nint n;\nvector<int>ans;\nvector<bool>vis;\nvector<int>mas;\nvector<int>del;\nvector<int>koll;\nvector<vector<int>>edges;\n\nint nod(int a, int b)\n{\n if (b == 0)\n return a;\n return nod(b, a % b);\n}\n\nvoid dfs1(int v)\...
842
D
Vitya and Strange Lesson
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, $mex([4, 33, 0, 1, 1, 5]) = 2$ and $mex([1, 2, 3]) = 0$. Vitya quickly understood all tasks of the teacher, but can you do th...
If the last query was $x_{i}$ and then we receive a query $x_{i + 1}$, then we can leave the original array unchanged and use the number $x_{i}\oplus x_{i+1}$ as the second query. So we will maintain current xor of queries instead of changing the array. It's easy to see that if the array contains all numbers from zero ...
[ "binary search", "data structures" ]
2,000
"#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <vector>\n#include <string>\n#include <ctime>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n\n//#include <unordered_set>\n//#include <unordered_map>\n\n#define forn(i,...
842
E
Nikita and game
Nikita plays a new computer game. There are $m$ levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class $y_{i}$ (and $y_{i}$ is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index $1$. ...
The vertices in the answer are the endpoints of some diameter of the tree. Let's consider diameter ($a$, $b$), where $a$ and $b$ are its endpoints, and we add a new vertex $c$. Then the length of diameter either remains the same or increases by one (then new endpoints are vertices ($a$, $c$) or ($b$, $c$)). We have to ...
[ "binary search", "dfs and similar", "divide and conquer", "graphs", "trees" ]
2,800
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = int(1e9), N = 1e6, M = 21;\n\nint n, up[M][N], tin[N], tout[N], p[4 * N], timer;\npair<int, int> t[4 * N];\nvector<int> g[N];\n\nvoid push(int now)\n{\n\tif (p[now] == 0)\n {\n\t\treturn;\n\t}\n\tt[now].first += p[now];\n\tif (now * 2 + 2 < 4 * N)\...
843
A
Sorting by Subsequences
You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ consisting of \textbf{different} integers. It is required to split this sequence into the \textbf{maximum} number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting...
Sorting any sequence means applying some permutation to its elements. All elements of sequence $a$ are different, so this permutation is unique and fixed. Let's call it $P$. One could split this permutation into simple cycles. The subsequences in the answer are subsequences formed by these simple cycles. One could prov...
[ "dfs and similar", "dsu", "implementation", "math", "sortings" ]
1,400
null
843
B
Interactive LowerBound
This is an interactive problem. You are given a \textbf{sorted} in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to $x$. More formally, there is a singly liked list built on an array of $n$ elements. Element with index $i$ contains two integers: $v...
Let's ask the values in index $start$ and in 999 other random indexes, choose among them the largest value less or equal to $x$. Let's go from it in order to the elements of the list, until we meet the first element greater or equal to x, which will be the answer. The probability that this algorithm for 2000 of actions...
[ "brute force", "interactive", "probabilities" ]
2,000
null
843
C
Upgrading Tree
You are given a tree with $n$ vertices and you are allowed to perform \textbf{no more than} $2n$ transformations on it. Transformation is defined by three vertices $x, y, y'$ and consists of deleting edge $(x, y)$ and adding edge $(x, y')$. Transformation $x, y, y'$ could be performed if all the following conditions ar...
A centroid-vertex remains a centroid during such process. If we have two centroids in a tree, the edge between them couldn't change. The components that are attached to the centroid can not change centroid they attached to or separate to several components. Using the size of the component operations, one could turn it ...
[ "constructive algorithms", "dfs and similar", "graphs", "math", "trees" ]
2,600
null
843
D
Dynamic Shortest Path
You are given a weighted directed graph, consisting of $n$ vertices and $m$ edges. You should answer $q$ queries of two types: - 1 v — find the length of shortest path from vertex $1$ to vertex $v$. - {2 c $l_{1} l_{2} ... l_{c}$} — add $1$ to weights of edges with indices $l_{1}, l_{2}, ..., l_{c}$.
Firstly, let's run an usual Dijkstra from $s$, find distances and make them a potentials of vertices. Then for each request let's recalculate all distances and make the potentials equal to these distances. To quickly recalculate the distance between requests, we can use the fact that in a graph with potentials, all dis...
[ "graphs", "shortest paths" ]
3,400
null
843
E
Maximum Flow
You are given a directed graph, consisting of $n$ vertices and $m$ edges. The vertices $s$ and $t$ are marked as source and sink correspondingly. Additionally, there are no edges ending at $s$ and there are no edges beginning in $t$. The graph was constructed in a following way: initially each edge had capacity $c_{i}...
Let's find a minimal set of saturated edges. We will create new flow network consisting of the same set of vertices and a little bit different edges. For an each edge from original graph without any flow let's create a new edge with the same direction and $c = INF$ carrying capacity. For every edge with a flow let's cr...
[ "flows", "graphs" ]
3,000
null
844
A
Diversity
Calculate the minimum number of characters you need to change in the string $s$, so that it contains at least $k$ different letters, or print that it is impossible. String $s$ consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
One could note what in case $k > |s|$, we should always print <<impossible>>. Overwise the finding value is equal $max(0, k - d)$, where $d$ is a number of different letters in the original string. It is correct because if $k \le d$ condition is satisfied and we shouldn't do anything, so the answer is zero. If $d < k...
[ "greedy", "implementation", "strings" ]
1,000
null
844
B
Rectangles
You are given $n × m$ table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: - All cells in a set have the same color. - Every two cells in a set share row or column.
One could note, that each appropriate set of cells is always contained in one row or in one column. We should calculate numbers of white and black cells $k_{0}$ and $k_{1}$ in every row and every column. For every $k$ we will summarize $2^{k} - 1$ (the number of non-empty subsets of this color contained in one row/colu...
[ "combinatorics", "math" ]
1,300
null
845
A
Chess Tourney
Berland annual chess tournament is coming! Organizers have gathered $2·n$ chess players who should be divided into two teams with $n$ people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil. Thus, organizer...
Let's sort the input array in non-decreasing order. Now we should take the first $n$ players to the first team and the last $n$ players - to the second team. That will guarantee that every member of the first team has greater or equal rating than every member of the second team. Now the only thing left is to check if a...
[ "implementation", "sortings" ]
1,100
null
845
B
Luba And The Ticket
Luba has a ticket consisting of $6$ digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of l...
Let's iterate over all 6-digit numbers. Now we will calculate number of positions in which digit of current ticket differs from digit of input ticket and call it $res$. Then answer will be minimal value $res$ over all lucky tickets.
[ "brute force", "greedy", "implementation" ]
1,600
null
845
C
Two TVs
Polycarp is a great fan of television. He wrote down all the TV programs he is interested in for today. His list contains $n$ shows, $i$-th of them starts at moment $l_{i}$ and ends at moment $r_{i}$. Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at...
Let's process all the segments on the line from left to right. For each segment we should push events ($l_{i}, 1$) and ($r_{i} + 1, - 1$) into some array. Sort this array of pair in increasing order (usual less comparator for pairs). Then we iterate over its elements and maintain $cnt$ - the current amount of open segm...
[ "data structures", "greedy", "sortings" ]
1,500
null
845
D
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that af...
Let's notice that you should never say that you didn't notice signs "no speed limit" and "overtake is allowed". Also if you drive with speed $sp$, you don't want to remove signs "speed limit" with number greater or equal to $sp$. Thus, greedy solution will work. Process all the events in chronological order. We should ...
[ "data structures", "dp", "greedy" ]
1,800
null
845
E
Fire in the City
The capital of Berland looks like a rectangle of size $n × m$ of the square blocks of same size. Fire! It is known that $k + 1$ blocks got caught on fire ($k + 1 ≤ n·m$). Those blocks are centers of ignition. Moreover positions of $k$ of these centers are known and one of these stays unknown. All $k + 1$ positions ar...
We can use binary search to find the answer. When binary searching, to check whether the whole city will be lightened up after $t$ minutes, we can use sweep line technique to find the smallest $x$-coordinate of the cell that is not lightened by $k$ centers of ignition (and the smallest $y$-coordinate too). Suppose that...
[ "binary search", "data structures" ]
2,400
null
845
F
Guards In The Storehouse
Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop. The storehouse can be represented as a matrix with $n$ rows and $m$ columns. Each element of the matrix is either . (an...
This problem can be solved using dynamic programming with broken profile. First of all, we have to make the number of rows not larger than $15$; if it is larger, then we can just rotate the given matrix. Let's fill the matrix from left to right, and in each column from top to bottom. Let $dp[pos][mask][f1][f2]$ be the ...
[ "bitmasks", "dp" ]
2,500
null
845
G
Shortest Path Problem?
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path betwe...
Let's find some path from $1$ to $n$. Let its length be $P$, then the answer to the problem can be represented as $P\oplus C$, where $C$ is the total length of some set of cycles in the graph (they can be disconnected; it doesn't matter because we can traverse the whole graph and return to the starting vertex with cost...
[ "dfs and similar", "graphs", "math" ]
2,300
null
846
A
Curriculum Vitae
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced $n$ games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zer...
The statement literally asks for the longest subsequence which looks like $[0, 0, 0, ..., 1, 1, 1]$. Let's find out how many zeroes will be in this sequence and then take all ones which come after the last zero. On each step take the next zero from the beginning of the sequence and count ones after it. Update answer wi...
[ "brute force", "implementation" ]
1,500
null
846
B
Math Show
Polycarp takes part in a math show. He is given $n$ tasks, each consists of $k$ subtasks, numbered $1$ through $k$. It takes him $t_{j}$ minutes to solve the $j$-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order...
Constraints tell us that we can avoid making any weird assumptions for any greedy solutions. You can easily count the answer for some fixed amount of tasks completed. Just sort all left subtasks (but the longest to solve in each uncompleted task) and take the easiest till the time is over. Now you can iterate from $0$ ...
[ "brute force", "greedy" ]
1,800
null
846
C
Four Segments
You are given an array of $n$ integer numbers. Let $sum(l, r)$ be the sum of all numbers on positions from $l$ to $r$ non-inclusive ($l$-th element is counted, $r$-th element is not counted). For indices $l$ and $r$ holds $0 ≤ l ≤ r ≤ n$. Indices in array are numbered from $0$. For example, if $a = [ - 5, 3, 9, 4]$, t...
Imagine the same task but without the first term in sum. As the sum of the array is fixed, the best second segment should be the one with the greatest sum. This can be solved in $O(n)$ with partial sums. When recalcing the best segment to end at position $i$, you should take minimal prefix sum from $0$ to $i$ inclusive...
[ "brute force", "data structures", "dp" ]
1,800
null
846
D
Monitor
Recently Luba bought a monitor. Monitor is a rectangular matrix of size $n × m$. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square $k × k$ consisting entirely of broken pixels. She knows that $q$ pixels are ...
At first let's sort broken pixels in non-descending order by times they appear. Obviously, if the first $cnt$ broken pixels make monitor broken, $cnt + 1$ pixel won't fix it. Thus, binary search on answer will work. Let's search for the first moment in time when the monitor becomes broken. The function to check if in s...
[ "binary search", "data structures" ]
1,900
null
846
E
Chemistry in Berland
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations (yes, chemistry i...
Since $x_{i} < i$, then the transformation graph is a tree. Let's solve the problem recursively. Suppose that material $j$ is a leaf in the tree (there is no $y$ such that $x_{y} = j$). Then if we don't have enough material $j$, we have to transform some of material $x_{j}$ into $j$. Let's transform the amount required...
[ "dfs and similar", "greedy", "trees" ]
2,300
null
846
F
Random Query
You are given an array $a$ consisting of $n$ positive integers. You pick two integer numbers $l$ and $r$ from $1$ to $n$, inclusive (numbers are picked randomly, equiprobably and independently). If $l > r$, then you swap values of $l$ and $r$. You have to calculate the expected value of the number of unique elements in...
For each index $i$ we will find the number of pairs $(l, r)$ (before swapping) such that $i$ is the first occurence of $a_{i}$ in the chosen segment. Let $f(i)$ be previous occurence of $a_{i}$ before $i$ (if $i$ is the first occurence, then $f(i) = 0$ if we suppose the array to be $1$-indexed). Let's find the number o...
[ "data structures", "math", "probabilities", "two pointers" ]
1,800
null