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
769
A
Year of University Entrance
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups fo...
This task can be solved in several ways. The simplest of them is - to put all given integers to an array, sort out it and print the median of the resulting array (it means that the element which is in the middle of it).
[ "*special", "implementation", "sortings" ]
800
null
769
B
News About Credit
Polycarp studies at the university in the group which consists of $n$ students (including himself). All they are registrated in the social net "TheContacnt!". Not all students are equally sociable. About each student you know the value $a_{i}$ — the maximum number of messages which the $i$-th student is agree to send ...
For solving this task you need to consider the following. Let it be that not all students knew news for that moment. If there are not students which knew this news and still can send messages, the answer for the task is -1. Otherwise, it is necessary to send the message to the student $x$, which still doesn't know news...
[ "*special", "greedy", "two pointers" ]
1,200
null
769
C
Cycle In Maze
The Robot is in a rectangular maze of size $n × m$. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. ...
Initially check $k$ on parity. If $k$ is odd, there is no the answer, because the cycle in the task should always have an even length. Otherwise, we will act as follows. With the help of the search algorithm of the width to find the shortest distance from the starting cell to the rest free cells. After that we will mov...
[ "*special", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,700
null
769
D
k-Interesting Pairs Of Integers
Vasya has the sequence consisting of $n$ integers. Vasya consider the pair of integers $x$ and $y$ k-interesting, if their binary representation differs from each other exactly in $k$ bits. For example, if $k = 2$, the pair of integers $x = 5$ and $y = 3$ is k-interesting, because their binary representation $x$=101 an...
To solve this problem you need to each value from $1$ to $10^{4}$ calculate the number of numbers in the sequence which equal to this value. Let $cnts[x]$ is a number of elements which equal to $x$. After that with two nested loops from $1$ to $10^{4}$ we can brute all pairs and for each pair ($i$, $j$) check that the ...
[ "*special", "bitmasks", "brute force", "meet-in-the-middle" ]
1,700
null
770
A
New Password
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: - the length of the password must be equal to $n$, - the password should consist...
To solve this problem, consider the first $k$ Latin letters. We will add them to the answer in the order, firstly, we add a, then b and so on. If letters are finished but the length of the answer is still less than the required one, then we start again adding letters from the beginning of the alphabet. We will repeat t...
[ "*special", "implementation" ]
800
null
770
B
Maximize Sum of Digits
Anton has the integer $x$. He is interested what positive integer, which doesn't exceed $x$, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
Initially, we put the integer $x$ to the answer. Then look at the integer from right to left. Do the following for each digit: if the digit is not zero, reduce it by one and change all other digits to nine. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answe...
[ "*special", "implementation", "math" ]
1,300
null
770
C
Online Courses In BSU
Now you can take online courses in the Berland State University! Polycarp needs to pass $k$ \textbf{main} online courses of his specialty to get a diploma. In total $n$ courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those tha...
Initially, we construct an oriented graph. If it is necessary firstly to take the course $j$ to pass the course $i$, add the edge from $i$ to $j$ to the graph. Then run the search in depth from all vertices, which correspond to main courses. In the depth search, we will simultaneously check the existence of oriented cy...
[ "*special", "dfs and similar", "graphs", "implementation" ]
1,500
null
770
D
Draw Brackets!
A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudo...
It is necessary to draw brackets carefully according to the condition to solve this problem. Draw brackets in a two-dimensional array. Firstly, you need to determine the size of the array and then start to draw. To determine the height of the image, you need to find the maximum nesting of the brackets $x$. Then the hei...
[ "*special", "implementation" ]
1,400
null
771
A
Bear and Friendship Condition
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are $n$ members, numbered $1$ through $n$. $m$ pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote th...
The main observation is that you should print "YES" if the graph is a set of disjoint cliques (in each connected non-clique there is a triple of vertices X,Y,Z that X-Y and Y-Z but not X-Z). To check if each connected component is a clique, you can run dfs and count vertices and edges in the connected component - it's ...
[ "dfs and similar", "dsu", "graphs" ]
1,500
#include <bits/stdc++.h> using namespace std; const int nax = 150123; vector<int> edges[nax]; bool vis[nax]; void dfs(int a, int & cnt_vertices, int & cnt_edges) { assert(!vis[a]); vis[a] = true; ++cnt_vertices; cnt_edges += edges[a].size(); for(int b : edges[a]) if(!vis[b]) dfs(b, cnt_vertices, cnt_edges);...
771
B
Bear and Different Names
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?). A group of soldiers is effective if and only if their names...
First generate $n$ different names. If the $i$-th given string is "NO", make names $i$ and $i + k - 1$ equal. Note that it doesn't affect other groups of $k$ consecutive names.
[ "constructive algorithms", "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; string s[105]; int main() { int n, k; cin >> n >> k; // generate n different names for(int i = 1; i <= n; ++i) { s[i] = "Aa"; s[i][0] += i / 26; s[i][1] += i % 26; } for(int start = 1; start <= n - k + 1; ++start) { string should; cin >> should; if(should[...
771
C
Bear and Tree Jumps
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of $n$ vertices, numbered $1$ through $n$. Limak recently learned how to jump. He can jump from a vertex to any...
It's a known problem to count the sum of distances for all pairs of vertices. For each edge, we should add to the answer the number of times this edge appears in a path between some two vertices. If $s_{v}$ denotes the size of the subtree of the vertex $v$ (we can first root the tree in $1$), we should add $s_{v} \cdot...
[ "dfs and similar", "dp", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; const int nax = 2e5 + 5; vector<int> edges[nax]; int count_subtree[nax][5]; int total_subtree[nax]; long long answer; int n, k; int subtract(int a, int b) { return ((a - b) % k + k) % k; } void dfs(int a, int par, int depth) { count_subtree[a][depth % k] = total_subtr...
771
D
Bear and Company
Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible. Limak has a string $s$...
Letters different than 'V' and 'K' are indistinguishable, so we can treat all of them as the same letter 'X'. We will try to build the final string from left to right Let $dp[v][k][x]$ denote the number of moves needed to move first $v$ letters 'V', first $k$ letters 'K' and first $x$ letters 'X' to the beginning of th...
[ "dp" ]
2,500
#include <bits/stdc++.h> using namespace std; int n; vector<int> V, K, X; // lists of indices with 'V', 'K' and other letters void read() { cin >> n; string s; cin >> s; for(int i = 0; i < n; ++i) { if(s[i] == 'V') V.push_back(i); else if(s[i] == 'K') K.push_back(i); else X.push_back(i); } } c...
771
E
Bear and Rectangle Strips
Limak has a grid that consists of $2$ rows and $n$ columns. The $j$-th cell in the $i$-th row contains an integer $t_{i, j}$ which can be positive, negative or zero. A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to $0$. Limak wants to choose some nice rectangles...
There are three types of rectangles: in the top row, in the bottom row, and in both rows (with height 2). For each type, and for each starting index $i$ we can quite easily find the first possible ending index - it's the first index on the right with the same prefix sum of numbers (it means that the difference of prefi...
[ "dp", "greedy" ]
3,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; void maxi(int & a, int b) { a = max(a, b); } vector<ll> candidate[2][2]; int n; vector<int> answer; vector<vector<vector<int>>> extensions; void consider(int one, int two, int score) { maxi(answer[max(one, two)], score); extensions[min(one,...
771
F
Bear and Isomorphic Points
Bearland is a big square on the plane. It contains all points with coordinates not exceeding $10^{6}$ by the absolute value. There are $n$ houses in Bearland. The $i$-th of them is located at the point $(x_{i}, y_{i})$. The $n$ points are distinct, but some subsets of them may be collinear. Bear Limak lives in the fi...
If $p_{1}$ is collinear with some two other points, we should print $0$. Now let's assume that no two points are collinear with $p_{1}$. The naive solution is to iterate over $O(n^{2})$ pairs of points. For each pair of points there is a line going through them both, and we know that the new placement of $p_{1}$ should...
[ "geometry", "two pointers" ]
3,300
#include <bits/stdc++.h> using namespace std; #include <bits/stdc++.h> using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge {c b, e; }; sim > rge<...
772
A
Voltage Keepsake
You have $n$ devices that you want to use simultaneously. The $i$-th device uses $a_{i}$ units of power per second. This usage is continuous. That is, in $λ$ seconds, the device will use $λ·a_{i}$ units of power. The $i$-th device currently has $b_{i}$ units of power stored. All devices can store an arbitrary amount o...
First, let's deal with the infinite case. If the supply of power is at least as big as the sum of demands, we can keep all devices alive indefinitely. Otherwise, let's binary search for the result. We can do binary search since if we can keep all devices alive for $E$ seconds, we can keep it alive for any time less tha...
[ "binary search", "math" ]
1,800
#include <stdio.h> #include <algorithm> #include <assert.h> using namespace std; typedef long long ll; typedef long double ld; // Adjust MAXN for bounds const ll MAXN=1e5+4; // MAXV is the max amount of time we can take const ld MAXV=1e18; ll a[MAXN],b[MAXN]; ld exhaust[MAXN]; int n; ll P; bool f(ld imid) { ld needsum...
772
B
Volatile Kite
You are given a convex polygon $P$ with $n$ distinct vertices $p_{1}, p_{2}, ..., p_{n}$. Vertex $p_{i}$ has coordinates $(x_{i}, y_{i})$ in the 2D plane. These vertices are listed in clockwise order. You can choose a real number $D$ and move each vertex of the polygon a distance of at most $D$ from their original pos...
First, let's restate the problem as the minimum distance D needed to make the polygon nonconvex. We can notice we can achieve this by by changing one angle of the polygon nonconvex. So, that involves moving at most 3 points. Let's take a look at the following picture: Here, A,B,C denote consecutive vertices on our poly...
[ "geometry" ]
1,800
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
772
C
Vulnerable Kerbals
You are given an integer $m$, and a list of $n$ distinct integers between $0$ and $m - 1$. You would like to construct a sequence satisfying the properties: - Each element is an integer between $0$ and $m - 1$, inclusive. - All prefix products of the sequence modulo $m$ are distinct. - No prefix product modulo $m$ ap...
Let's consider a directed graph with $m$ nodes, labeled from $1$ to $m$, where there is an edge between nodes $i$ and node $j$ if there exists a number $x$ such that $i x\equiv j{\mathrm{~mod~}}m$. Now, we can notice there is an edge between node $i$ and node $j$ if and only if $gcd(n, i)$ divides $gcd(n, j)$. So, ther...
[ "constructive algorithms", "dp", "graphs", "math", "number theory" ]
2,300
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOExcept...
772
D
Varying Kibibits
You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Denote this list of integers as $T$. Let $f(L)$ be a function that takes in a non-empty list of integers $L$. The function will output another integer as follows: - First, all integers in $L$ are padded with leading zeros so they are all the same length as the m...
There are two approaches. One is inclusion exclusion. The other is a modification of the fast walsh hadamard transform. Inclusion Exclusion: Let's change definition of G(x) so that f(S) >= x rather than f(S) = x. Here "y >= x" means that if y and x are considered as strings, then each digit in a particular position in ...
[ "bitmasks", "dp" ]
2,700
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
772
E
Verifying Kingdom
\textbf{This is an interactive problem.} The judge has a hidden rooted full binary tree with $n$ leaves. A full binary tree is one where every node has either $0$ or $2$ children. The nodes with $0$ children are called the leaves of the tree. Since this is a full binary tree, there are exactly $2n - 1$ nodes in the tr...
Consider building the tree leaf by leaf. The base case of two leaves is trivial. Now, suppose want to add another leaf $w_{i}$. We can define the "centroid" as a tree such that after removing the centroid, all remaining connected components has at most half the number of leaves (note this is different from the standard...
[ "binary search", "divide and conquer", "interactive", "trees" ]
3,200
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Input...
773
A
Success Rate
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made $y$ submissions, out of which $x$ have been successful. Thus, your current success rate on Codeforces is equal to $x / y$. Your favorite rational number in the $[0;1]$ range is $p / q$. Now you wonder: wha...
This problem can be solved using binary search without any special cases. You can also solve it using a formula, handling a couple of special cases separately. If our success rate is $p / q$, it means we have $pt$ successful submissions out of $qt$ for some $t$. Since $p / q$ is already irreducible, $t$ has to be a pos...
[ "binary search", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int x, y, p, q; cin >> x >> y >> p >> q; if (p == 0) { cout << (x == 0 ? 0 : -1) << endl; continue; } if (p == q) { cout << (x == y ? 0 : -1) << endl; continue; } int ...
773
B
Dynamic Problem Scoring
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends...
Dynamic problem scoring used to be used more often in Codeforces rounds, including some tournament rounds like VK Cup 2015 Finals. Once you read the problem statement carefully, the problem itself isn't overly difficult. Consider new accounts Vasya puts into play. Correct solutions to which problems does he submit from...
[ "brute force", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 123456; const int m = 5; const int k = 6; int a[N][m]; int score[N]; int cost[m]; int solved[m]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", a[i] + j); if (a[i][j] != -1...
773
C
Prairie Partition
It can be shown that any positive integer $x$ can be uniquely represented as $x = 1 + 2 + 4 + ... + 2^{k - 1} + r$, where $k$ and $r$ are integers, $k ≥ 0$, $0 < r ≤ 2^{k}$. Let's call that representation \underline{prairie partition} of $x$. For example, the prairie partitions of $12$, $17$, $7$ and $1$ are: \begin{...
This kind of partition sometimes shows up in solutions to knapsack problems with multiple items of the same type. Let's say we want to check if the answer can be $m$. That means we have to construct $m$ chains of powers of 2 like $1, 2, 4, ..., 2^{k - 1}$ (possibly with different values of $k$), and then assign at most...
[ "binary search", "constructive algorithms", "greedy", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX = 66; int power[MAX + 10]; int between[MAX + 10]; int extra[MAX + 10]; int ende[MAX + 10]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { long long foo; cin >> foo; int cc = 0; bool good = true; while (foo > 1) { ...
773
D
Perishable Roads
In the country of Never, there are $n$ cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as $\textstyle{\frac{n(n-1)}{2}}$ roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and b...
This is my favorite problem in this contest. Several clever observations make its solution really simple. First important observation helps understand the optimal structure of the signpost directions. Suppose there are two cities A and B with the signposts directed to the same city C. Without loss of generality, suppos...
[ "dp", "graphs", "shortest paths" ]
2,700
#include <bits/stdc++.h> using namespace std; const long long inf = (long long) 1e18; const int N = 2010; int a[N][N]; long long d[N]; bool used[N]; int main() { // reading input data int n; scanf("%d", &n); for (int i = 0; i < n; i++) { a[i][i] = 0; for (int j = i + 1; j < n; j++) { scanf("%...
773
E
Blog Post Rating
It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time — its \underline{community rating}. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by ...
There are several different solutions to this problem, I'll describe one of them. First, we have to determine the optimal rating order for a set of users. Using an exchange argument, it can be shown that to maximize the final community rating the users should rate the blog post in non-decreasing order of their estimate...
[ "data structures", "sortings" ]
3,000
#include <bits/stdc++.h> using namespace std; inline int signum(int x) { return (x < 0 ? -1 : (x > 0 ? 1 : 0)); } const int inf = (int) 1e9; const int N = 500010; pair <int, int> a[N]; int pos[N]; pair <int, int> mn[4 * N]; int add[4 * N]; void push(int x) { add[x + x] += add[x]; mn[x + x].first += add[x];...
773
F
Test Data Generation
Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness. For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows: {The first line contains a single integer $n$ ($1 ≤ n ≤ max_...
This problem was inspired by division 1 problem A from Codeforces Round #201, which I tested: http://codeforces.com/contest/346/problem/A. Several hours before the round, I noticed that all test cases except for the examples were generated randomly. Moreover, there were three cases with $max_{n} = 10$ and $max_{a} = 10...
[ "combinatorics", "divide and conquer", "dp", "fft", "math", "number theory" ]
3,400
#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) (x...
776
A
A Serial Killer
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
You just have to store the current two strings. This can simply be done by replacing the string to be deleted with the new string. This can be done in O(n)
[ "brute force", "implementation", "strings" ]
900
#include <algorithm> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #ifdef PRINT...
776
B
Sherlock and his girlfriend
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought $n$ pieces of jewelry. The $i$-th piece has price equal to $i + 1$, that is, the prices of the jewelry are $2, 3, 4, ... n + 1$. Watson gave Sherlock a challenge to color these jewelry pieces suc...
Hint: Observe that if $i + 1$ is prime, then only would the pieces having their prices as the multiples of $i + 1$ would have to be of a different color. Editorial: We are required to color the jewelry pieces such that for every jewelry piece $i$ having a price $i + 1$, all the pieces whose prices are prime divisors of...
[ "constructive algorithms", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; int sieve[100005]; int main() { int i, n, j; cin>>n; for(i=2; i<=n+1; i++) { if(!sieve[i]) for(j=2*i; j<=n+1; j+=i) sieve[j]=1; } if(n>2) cout<<"2\n"; else cout<<"1\n"; for(i=2; i<=n+1; i++) { if(!sieve[i]) cout<<"1 "; else cout<<"2 "; ...
776
C
Molly's Chemicals
Molly Hooper has $n$ different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The $i$-th of them has affection value $a_{i}$. Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total...
Hint: The number of possible powers will be less than 50 for any $k$. Editorial: We are going to loop over all possible non-negative powers of $k$. Since the maximum possible value of subarray sum can be $10^{5} \times 10^{9} = 10^{14}$, there can be at most $\lfloor\log_{2}10^{14}\rfloor+1$ possible powers that can ...
[ "binary search", "brute force", "data structures", "implementation", "math" ]
1,800
#include <algorithm> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #ifdef PRINT...
776
D
The Door Problem
Moriarty has trapped $n$ people in $n$ distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are $m$ switches. Each switch control doors of some rooms, but each door is control...
Hint : Try to model the situation as a graph with rooms as edges and switches as nodes. Editorial : All rooms are represented as edges. Mark the edges as $1$ if the room is open else mark the edge as closed. The answer will be "YES" if you can color the graph in such a manner that the edges having value $0$ have both n...
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
2,000
#include <bits/stdc++.h> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) #define bitcount __builtin_popcountll #define mod 1000000007 #define N 1000009 #define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ss(s) cin>>s; #define si(x) scanf("%d",&x); #define sl(x) cin>>x; #define pb pus...
776
E
The Holmes Children
The Holmes children are fighting over who amongst them is the cleverest. Mycroft asked Sherlock and Eurus to find value of $f(n)$, where $f(1) = 1$ and for $n ≥ 2$, $f(n)$ is the number of distinct ordered positive integer pairs $(x, y)$ that satisfy $x + y = n$ and $gcd(x, y) = 1$. The integer $gcd(a, b)$ is the grea...
Hint: For $n = 10$, the pairs satisfying the conditions are $(1, 9), (3, 7), (7, 3), (9, 1)$. The first members of each pair form the set ${1, 3, 7, 9}$. Similarly, for $n = 12$, the corresponding set is ${1, 5, 7, 11}$. Also, observe that $f(n) = n - 1$ whenever $n$ is a prime. Editorial: Given, $x+y=N{\mathrm{~and~}}...
[ "math", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; #define ll long long #define MOD 1000000007 #define ll long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S ...
776
F
Sherlock's bet to Moriarty
Sherlock met Moriarty for a final battle of wits. He gave him a regular $n$ sided convex polygon. In addition to it, he gave him certain diagonals to form regions on the polygon. It was guaranteed that the diagonals did not intersect in interior points. He took each of the region and calculated its importance value. I...
Hint: Observe that if we consider all regions as nodes for a graph and connect two regions if they share an edge (in the form of sharing a diagonal), we will get a tree. Editorial: Use a greedy approach to form a tree from the given polygon. Let us take one diagonal between vertex $a$ and $b$ $(b > a)$. Let us define a...
[ "constructive algorithms", "data structures", "divide and conquer", "geometry", "graphs", "implementation", "trees" ]
2,800
#include<bits/stdc++.h> using namespace std; #define sd(x) scanf("%d",&x) #define slld(x) scanf("%lld",&x) #define ss(x) scanf("%s",x) #define ll long long #define mod 1000000007 #define bitcount __builtin_popcountll #define pb push_back #define fi first #define se second #define mp make_pair #define pi pair<int,int...
776
G
Sherlock and the Encrypted Data
Sherlock found a piece of encrypted data which he thinks will be useful to catch Moriarty. The encrypted data consists of two integer $l$ and $r$. He noticed that these integers were in hexadecimal form. He takes each of the integers from $l$ to $r$, and performs the following operations: - He lists the distinct digi...
Hint: This problem can be solved using dynamic programming approach by maintain dp for mask of digits appearing in the number($mask1$) along with position in the number($l$) and mask of last $16$ bits($mask2$) of the number formed upto $l$. Editorial: Observe that only the most significant bit of the $mask1$ is require...
[ "bitmasks", "combinatorics", "dp" ]
2,900
#include<bits/stdc++.h> using namespace std; #define sd(x) scanf("%lld",&x) #define slld(x) scanf("%lld",&x) #define ss(x) scanf("%s",x) #define ll long long #define mod 65536 #define bitcount __builtin_popcountll #define pb push_back #define fi first #define se second #define mp make_pair #define pi pair<int,int> l...
777
A
Shell Game
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess...
Fix the initial numeration of shells. Consider function $p(i, j)$ to be the index of the shell located at position $j$ after $i$ moves. $p(0) = {0, 1, 2}$ $p(1) = {1, 0, 2}$ $p(2) = {1, 2, 0}$ $p(3) = {2, 1, 0}$ $p(4) = {2, 0, 1}$ $p(5) = {0, 2, 1}$ $p(6) = {0, 1, 2}$ Thus, after $6$ movements all shells will get back ...
[ "constructive algorithms", "implementation", "math" ]
1,000
null
777
B
Game of Credit Cards
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite $n$-digit credit card. Then both players name the digits written on the...
First we want to consider a strategy that minimizes the amount of flicks Moriarty will receive from Sherlock. This is similar to loosing as few rounds as possible. He can use digit 0 can be used to not loose against digit 0, digit 1 to not loose against digits 0 and 1 and so on. Thus, Moriarty should try all digits fro...
[ "data structures", "dp", "greedy", "sortings" ]
1,300
null
777
C
Alyona and Spreadsheet
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of $n$ rows and $m$ columns. By $a_{i, j}$ we will denote the integer located at the $i$-th row and the $j$-th column. We say that the table...
For each cell $(i, j)$ compute value $up(i, j)$ equal to maximum $r$, such that table is non-decreasing in row $j$ if we keep only rows from $i$ to $r$ inclusive. This values can be computed in $O(nm)$ time using the following formulas: $up(i, j) = up(i + 1, j) + 1$, if $i < n$ and $a_{i, j} < a_{i + 1, j}$; $up(i, j) ...
[ "binary search", "data structures", "dp", "greedy", "implementation", "two pointers" ]
1,600
null
777
D
Cloud of Hashtags
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashta...
It is possible to solve this problem in many ways. One of them was to iterate over all strings in reversed order and to try to leave the longest possible prefix of each string greedily without breaking the statement. Let's prove this solution formally. Note that the set of possible lengths of some string $s_{i}$ in a c...
[ "binary search", "greedy", "implementation", "strings" ]
1,800
null
777
E
Hanoi Factory
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strang...
To start with make the following observation: if two rings $i$ and $j$ have equal outer radiuses $b_{i} = b_{j}$ they can be merged in one ring of the same outer radius, inner radius equal to $min(a_{i}, a_{j})$ and height equal to $h_{i} + h_{j}$. Using the observation we transform our problem to the one with distinct...
[ "brute force", "data structures", "dp", "greedy", "sortings" ]
2,000
null
778
A
String Game
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word $t$ and wants to get the word $p$ out of it. Nastya removes letters in a cert...
In this problem we have to find the last moment of time, when $t$ has $p$ as a subsequence. If at some moment of time $p$ is a subsequence of $t$ then at any moment before, $p$ is also its subsequence. That's why the solution is binary search for the number of moves, Nastya makes. For binary search for a moment of time...
[ "binary search", "greedy", "strings" ]
1,700
null
778
B
Bitwise Formula
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer $m$, bit depth of the game, which means that all numbers in the game will consist of $m$ bits. Then he asks Peter to choose some $m$-bit number. After ...
Note that changing $i$-th bit of chosen number doesn't change any bits of any of the variables other than $i$-th one. Also note that the total number of values is greater, as more variables have 1 at $i$-th position. Let's solve for every bit independently: learn, what is the value of $i$-th bit of chosen number. We ca...
[ "bitmasks", "brute force", "dfs and similar", "expression parsing", "implementation" ]
1,800
null
778
C
Peterson Polyglot
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters. Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his lang...
While erasing letters on position $p$, trie changes like the following: all the edges from one fixed vertex of depth $p$ are merging into one. You can see it on the picture in the sample explanation. After merging of the subtrees we have the only tree - union of subtrees as the result. Consider the following algorithm....
[ "brute force", "dfs and similar", "dsu", "hashing", "strings", "trees" ]
2,500
null
778
D
Parquet Re-laying
Peter decided to lay a parquet in the room of size $n × m$, the parquet consists of tiles of size $1 × 2$. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again ...
Let's assume that the width of the rectangle is even (if not, flip the rectangle). Convert both start and final configurations into the configuration where all tiles lie horizontally. After that, since all the moves are reversible, simply reverse the sequence of moves for the final configuration. How to obtain a config...
[ "constructive algorithms" ]
2,700
null
778
E
Selling Numbers
Boris really likes numbers and even owns a small shop selling interesting numbers. He has $n$ decimal numbers $B_{i}$. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values $c_{d}$, where $c_{d}$ is the cost of the digit $d$. Of course, Boris is interested in that numbers h...
Because the target value for this problem is calculated independently for all digits, we'll use the dynamic programming approach. Define $dp_{k, C}$ as the maximum possible cost of digits after we processed $k$ least significant digits in $A$ and $C$ is the set of numbers having the carry in current digit. This informa...
[ "dp", "sortings" ]
3,000
null
779
A
Pupils Redistribution
In Berland each high school student is characterized by academic performance — integer value between $1$ and $5$. In high school 0xFF there are two groups of pupils: the group $A$ and the group $B$. Each group consists of exactly $n$ students. An academic performance of each student is known — integer value between $1...
To solve this problem let's use array $cnt[]$. We need to iterate through first array with academic performances and for current performance $x$ let's increase $cnt[x]$ on one. In the same way we need to iterate through the second array and decrease $cnt[x]$ on one. If after that at least one element of array $cnt[]$ i...
[ "constructive algorithms", "math" ]
1,000
null
779
B
Weird Rounding
Polycarp is crazy about round numbers. He especially likes the numbers divisible by $10^{k}$. In the given number of $n$ Polycarp wants to remove the least number of digits to get a number that is divisible by $10^{k}$. For example, if $k = 3$, in the number 30020 it is enough to delete a single digit (2). In this cas...
To solve this problem we need to make $k$ zeroes in the end of number $n$. Let's look on the given number as on the string and iterate through it beginning from the end (i.e. from the low order digit). Let $cnt$ equals to the number of digits which we reviewed. If the current digit does not equal to zero we need to inc...
[ "brute force", "greedy" ]
1,100
null
779
C
Dishonest Sellers
Igor found out discounts in a shop and decided to buy $n$ items. Discounts at the store will last for a week and Igor knows about each item that its price now is $a_{i}$, and after a week of discounts its price will be $b_{i}$. Not all of sellers are honest, so now some products could be more expensive than after a we...
To solve this problem we need at first to sort all items in increasing order of values $a_{i} - b_{i}$. Then let's iterate through sorted array. If for the current item $x$ we did not buy $k$ items now and if after discounts it will cost not more than now, we need to buy it now and pay $a_{x}$, in the other case we nee...
[ "constructive algorithms", "greedy", "sortings" ]
1,200
null
780
A
Andryusha and Socks
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has $n$ distinct pairs of socks which are initially in a bag. The pairs are numbered from $1$ to $n$. Andryusha wants to put paired socks together and put them in the wardrobe. He takes th...
This is a simple implementation problem. Store an array for whether a sock of each type is currently on the table, along with the total number of socks, and the largest number encountered. It is now easy to process socks one by one and maintain everything. Complexity: $O(n)$ time and memory.
[ "implementation" ]
800
null
780
B
The Meeting Place Cannot Be Changed
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are $n$ friends, and $i$-th of them is standing at the point $x_{i}$ meters and can move with any speed no greater...
We will apply binary search to solve this problem. Inside the binary search we have to check if it is possible to meet within $t$ seconds. In this time, $i$-th friend can get anywhere within the segment $[x_{i} - tv_{i}, x_{i} + tv_{i}]$. For the meeting to be possible, there must be a point common to all these segment...
[ "binary search" ]
1,600
null
780
C
Andryusha and Colored Balloons
Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of $n$ squares connected with $(n - 1)$ bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a col...
If $v$ is a vertex of degree $d$, then the answer is at least $d + 1$. Indeed, any two neighbours of $v$ can be connected by a path of length three via vertex $v$. Also, $v$ lies on a common three-vertex path with any of its neighbours (possibly using a non-neighbour vertex). It follows that $v$ and all of its neighbou...
[ "dfs and similar", "graphs", "greedy", "trees" ]
1,600
null
780
D
Innokenty and a Football League
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of \textbf{three letters}. Each club's full name consist ...
Let us write $a_{i}$ and $b_{i}$ for first and second options for $i$-th club name. If all $a_{i}$ are distinct, we can assign all of them to be club names without conflict. Otherwise, suppose that for clubs $i$, $j$ we have $a_{i} = a_{j}$, hence we can't use them simultaneously. Note that, say, choosing $a_{i}$ and $...
[ "2-sat", "graphs", "greedy", "implementation", "shortest paths", "strings" ]
1,900
null
780
E
Underground Lab
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil cor...
Let's start a DFS at any vertex of the graph, and produce an Euler tour - the order of vertices visited by a DFS, where each vertex $v$ is written down every time DFS visits it (in particular, when a recursive call made from $v$ terminates). Note that the Euler tour has exactly $2n - 1$ entries in it, hence it would be...
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,100
null
780
F
Axel and Marston in Bitland
A couple of friends, Axel and Marston are travelling across the country of Bitland. There are $n$ towns in Bitland, with some pairs of towns connected by one-directional roads. Each road in Bitland is either a pedestrian road or a bike road. There can be multiple roads between any pair of towns, and may even be a road ...
Let us write $A_{i}$ for the binary string obtained after $i$ inverse-append steps, for example, $A_{0} = 0$, $A_{1} = 01$, and so on. Let us also write $B_{i}={\overline{{A_{i}}}}$. By definition we must have $A_{i+1}=A_{i}B_{i}$, and $B_{i+1}=B_{i}A_{i}$. Let us store matrices $P_{k}$ and $Q_{k}$, with entries $P_{k}...
[ "bitmasks", "dp", "graphs", "matrices" ]
2,400
null
780
G
Andryusha and Nervous Barriers
Andryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has $w$ columns numbered from $1$ to $w$ from left to right, and $h$ rows numbered from $1$ to $h$ from the bottom to the top. Further, there are barriers in some of board rows. There are $n...
Solution 1: Let us move a sweep-line from the bottom to the top, and say that $i$-th barrier is active if the current $y$-coordinate satisfies $u_{i} \le y \le u_{i} + s_{i}$. If we want to find the result of dropping a ball in column $x$ at a certain moment, we have to find the highest active barrier that covers $...
[ "data structures", "dp" ]
2,700
null
780
H
Intranet of Buses
A new bus route is opened in the city $\mathbb{N}$. The route is a closed polygon line in the place, with all segments parallel to one of the axes. $m$ buses will operate on the route. All buses move in a loop along the route in the same direction with equal constant velocities (stopping times are negligible in this pr...
Let us do a binary search on the answer. Inside it, we have to check if at any time moment bus pairs 1 and 2, 2 and 3, ..., $n$ and 1 are within distance $x$ of each other simultaneously. Let $p(t)$ be the location of the bus 1 (that departed at time 0) at time $t$. Let us call a time moment $t$ good, if we have $||p(t...
[ "binary search", "geometry", "implementation", "two pointers" ]
3,100
null
785
A
Anton and Polyhedrons
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - Tetrahedron. Tetrahedron has $4$ triangular faces. - Cube. Cube has $6$ square faces. - Octahedron. Octahedron has $8$ triangular faces. - Dodecahedron. Dodecahedron has $12$ pentagonal faces. - Icosah...
I think there's nothing to explain in this problem. Just check the polyhedron type, determine its number of faces and sum these numbers. Time complexity is $O(n)$.
[ "implementation", "strings" ]
800
vals = { 'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20 } n = int(input()) ans = 0 for i in range(0, n): ans += vals[input()] print(ans)
785
B
Anton and Classes
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes. Anton has $n$ variants when he will attend chess classes, $i$-th variant is given by a period of time $(l_{1, i}, r_{1, i})$. Also he has $m$ variants when he will attend programming c...
At first, let's determine what classes Anton will attend first - chess classes or programming classes. Consider the case when Anton attends chess classes first and then attends programming classes. It's not hard to observe that in this case it's better to take the chess classes variant in which the right range is as mo...
[ "greedy", "sortings" ]
1,100
infinity = 1234567890 minR1 = minR2 = infinity maxL1 = maxL2 = -infinity n = int(input()) for i in range(0, n): (l, r) = map(int, input().split()) maxL1 = max(maxL1, l) minR1 = min(minR1, r) m = int(input()) for i in range(0, m): (l, r) = map(int, input().split()) maxL2 = max(maxL2, l) minR2 = min(minR2, r) res =...
785
C
Anton and Fairy Tale
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale: "Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that ba...
At first, let's make the following assumption: if a sparrow cannot eat a grain because the barn is empty, the number of grains in the barn becomes negative. It's easy to see that the answer doesn't change because of this. Now, let's observe the number of grains before sparrows come. At first, the barn remains full for ...
[ "binary search", "math" ]
1,600
(n, m) = map(int, input().split()) if n <= m: print(n) else: aM = m n -= m (l, r) = (0, int(2e9)) while l < r: m = (l + r) // 2; val = m * (m+1) // 2; if val >= n: r = m else: l = m+1 print(l + aM)
785
D
Anton and School - 2
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)). On the last lesson Anton learned about the regular simple bracket s...
At first, let's simplify the problem: let our string consists of $x + y$ characters, begins with $x$ characters "(" and ends with $y$ characters ")". How to find the number of RSBS in such string? Let's prove that this number is equal to $\textstyle(x+y)={\frac{(x+y)!}{x!.y!}}$. It's easy to observe that this formula a...
[ "combinatorics", "dp", "math", "number theory" ]
2,300
import java.io.*; import java.util.*; public class BracketsJava { public static int mod = (int)1e9 + 7; public static class ExtGcdResult { long x; long y; } public static long extGcd(long a, long b, ExtGcdResult res) { if (a == 0) { res.x = 0L; res.y = 1L; return b; } ExtGcdResult newRes = ...
785
E
Anton and Permutation
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of $n$ elements is a sequence of numbers ${a_{1}, a_{2}, ..., a_{n}}$, in which every number from $1$ to $n$ appears exactly once. One day Anton got a new permutation and started to play with it. He does the following oper...
At first observe that there is $0$ inversions in the initial permutation. Let's divide our queries in ${\sqrt{q}}$ blocks. Now learn how to answer all the queries in one block in $O(n+q+\sqrt{n q})$. At first, let's divide our positions in the permutation in fixed and mobile positions. Mobile positions are all the posi...
[ "brute force", "data structures" ]
2,200
import java.io.*; import java.util.*; public class NsqrtNlogNnetman implements Runnable { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in), 32768); tokeniz...
786
A
Berzerk
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are $n$ objects numbered from $1$ to $n$ arranged in a circle (in clockwise order). Object number $1$ is a black hole and...
For each state of monster ($2n$ possible states, the position and whose turn it is) we will determine if it will be won, lost, or stuck in loop (the player whose turn it is, will win, lose, or the game will never end if this state happens). For this purpose, first each state with monster on $1$ is lost. Then if we cons...
[ "dfs and similar", "dp", "games" ]
2,000
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
786
B
Legacy
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are $n$ planets in their universe numbered from $1$ to $n$. Rick is in planet number $s$ (the earth) and he doesn't know where Morty is. As we al...
Consider a weighted directed graph (initially it has $n$ vertices and no edges). We will construct a segment tree to handle queries of second type (and one for the third type but with similar approach). Build a segment tree on number $1, ..., n$. For each node of segment tree consider a vertex in the graph. For each le...
[ "data structures", "graphs", "shortest paths" ]
2,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
786
C
Till I Collapse
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated $n$ Mr. Meeseeks, standing in a line numbered from $1$ to $n$. Each of them has his own color. $i$-th Mr. Meeseeks' color is $a_{i}$. Rick and Morty are gathering their army and they want to divide Mr. Mee...
Your task is to find the minimum number of parts needed to partition this such that each part contains no more than $k$ different numbers. For a fixed $k$, we can greedily find the answer. First, fix a maximal partition with at most $k$ different numbers in it, then a maximal after that and so on. If answer for $k$ is ...
[ "data structures", "divide and conquer" ]
2,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
786
D
Rap God
Rick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are "love rivals". Unity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics "R...
Use centroid-decomposition. In each decomposition: Assume $c$ is centroid of current subtree. Then for each vertex $v$ in current subtree, we want to find some part of answer for each query with $x = v$. More precisely, for each query $(x, y)$ that $x$ is in the current subtree (in the decomposition), we want to find t...
[ "data structures", "dfs and similar", "hashing", "strings", "trees" ]
3,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
786
E
ALT
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy. ALT has $n$ cities numbered from $1$ to $n$ and $n - 1$ bidirection...
If $n$ and $m$ were smaller: We construct a bipartite graph. For each citizen we consider a vertex in the first part, and for each guardian in the tree we consider a vertex in the second part. We put an edge between vertex $i$ from first part and $j$ from second part if and only if path $x_{i}$ to $y_{i}$ contains edge...
[ "data structures", "flows", "graphs", "trees" ]
3,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
787
A
The Monster
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times $b, b + a, b + 2a, b + 3a, ...$ and Morty screams at times $d, d + c, d + 2c, d + 3c, ...$. The Monster will catch them if at any point they scream at the same time, so ...
You need to find out if there are non-negative integers like $i$ and $j$ such $ai + b = cj + d$ and $i$ or $j$ (or both) is minimized. It's easy to show that if $a, b, c, d \le N$, and such $i$ and $j$ exist, then $i, j \le N$, so you can iterate over $i$ and check if such $j$ exists. Time complexity: ${\mathcal{O}...
[ "brute force", "math", "number theory" ]
1,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
787
B
Not Afraid
Since the giant heads have appeared in the sky all humanity is in danger, so \textbf{all} Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are $n$ parallel universes participating in this event ($n$ Ricks and $n$ Mortys). I. e. each of $n$ universes has ...
The problem says given a CNF formula, check if we can set value of literals such that the formula isn't satisfied. Answer is yes if and only if you can set values so that at least one clause isn't satisfied. It's easy to show that answer is yes if and only if there's at least one clause that for that clause there's no ...
[ "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i...
788
A
Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function $f$, which is defined ...
We can solve the problem for segments with odd and even $l$ separately. Let's build arrays $b$ ($b_{i} = |a_{i + 1} - a_{i}| \cdot ( - 1)^{i}$) and $c$ ($c_{i} = |a_{i + 1} - a_{i}| \cdot ( - 1)^{i + 1}$). Obviously, that segment with the greatest sum in array $b$ starts in some even index. In every segment starting in...
[ "dp", "two pointers" ]
1,600
null
788
B
Weird journey
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has $n$ cities connected with $m$ bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and en...
We can consider the system of towns and roads as a graph, where edges correspond to roads and vertexes to cities. Now, let's fix two edges, that will be visited once. All other edges we can split into two. Then, the good way in the old graph equivalents to any Euler path in the computed one. Widely known that Euler pat...
[ "combinatorics", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,100
null
788
C
The Great Mixing
Sasha and Kolya decided to get drunk with Coke, again. This time they have $k$ types of Coke. $i$-th type is characterised by its carbon dioxide concentration $\frac{d i_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\frac{p_{...
Let $\frac{p_{L}}{1000}$ - needed concentration and $s_{1}, s_{2}, ..., s_{m}$ - concentration of types we'll use. ${\frac{s_{1}+s_{2}+\cdot\cdot\cdot\cdot+s_{m}}{1000\cdot m}}={\frac{n}{1000}}$${\frac{s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}}{m}}=n$ $s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}=n\cdot m$ $s_{1}+s_{2}+\cdot\cdot\cdot\cd...
[ "dfs and similar", "graphs", "shortest paths" ]
2,300
null
788
D
Finding lines
After some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation $x = ...
First we solve another problem. Let we have points not straight lines, but points on one axis. Let $MAX = 10^{8}$, that is, the maximum coordinate. First, we find the left and right points. The left is ($- MAX + get( - MAX)$), and the right one ($MAX - get(MAX)$). Then we solve the problem recursively. There will be a ...
[ "constructive algorithms", "divide and conquer", "interactive" ]
3,000
null
788
E
New task
On the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of $5$ participants. The team of Uzhlyandia will consist of soldiers, because there are no gamers. Masha is a new minister of defense and gaming. The prime duty of the minister is to cal...
To begin with, we apply scaling to all numbers and replace each element of the array with its position in the sorted array. Count the answer for the original array. For each $i$, calculate smaller_pref$_{i}$ as the quantity of such $j$ that $j < i$, $a_{j} \le a_{i}$ and smaller_suf$_{i}$ - the number of such $j$ tha...
[ "data structures" ]
2,900
null
789
A
Anastasia and pebbles
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only \textbf{two pockets}. She can put at most $k$ pebbles in each pocket at the...
For every pebble type we can count the minimal number of pockets Anastasia need to collect all pebbles of this type. That's easy to notice that this number equals $\textstyle\left[{\frac{\boldsymbol{w_{j}}}{k}}\right]$. So the answer for the problem is $\textstyle\left[\frac{\sum_{i=1}^{n}|\frac{-i}{k}\vert}{2}\right]$...
[ "implementation", "math" ]
1,100
null
789
B
Masha and geometric depression
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression $b$ defined by two integers $b_{1}$ and $q$. Remind that a geometric progression is a sequence of integers $b_{1}, b_{2}, b_{3}, ...$, where for each $i > 1$ the respective term satisfi...
We need to handle following cases in the solution: $|b_{1}| > l$ - answer is 0. $b_{1} = 0$ - if 0 is present in array $a$ than answer is 0, else $inf$. $q = 1$ - if $b_{1}$ is present in array $a$ than answer is 0, else $inf$. $q = - 1$ - if both $b_{1}$ and $- b_{1}$ are present in array $a$ than answer is 0, otherwi...
[ "brute force", "implementation", "math" ]
1,700
null
791
A
Bear and Big Brother
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh $a$ and $b$ respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's we...
This problem is simple: just multiply $a$ by $3$ and $b$ by $2$ until $a > b$. Output the number of operations. You will not need more than $6$ iterations.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int a, b; cin >> a >> b; int answer = 0; while(a <= b) { a *= 3; b *= 2; ++answer; } printf("%d\n", answer); }
792
A
New Bus Route
There are $n$ cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers $a_{1}, a_{2}, ..., a_{n}$. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport d...
At first let's notice that if there exists such triple $a_{i}$, $a_{j}$ and $a_{k}$ that $a_{i} < a_{j} < a_{k}$, then $|a_{k} - a_{i}| > |a_{j} - a_{i}|$ and $|a_{k} - a_{i}| > |a_{k} - a_{j}|$. Thus we can sort all numbers and check only adjacent ones. There are exactly $n - 1$ of such pairs. The only thing left is t...
[ "implementation", "sortings" ]
1,100
null
792
B
Counting-out Rhyme
$n$ children are standing in a circle and playing the counting-out game. Children are numbered clockwise from $1$ to $n$. In the beginning, the first child is considered the leader. The game is played in $k$ steps. In the $i$-th step the leader counts out $a_{i}$ people in clockwise order, starting from the next person...
The task was just about implementing algorithm described in statement. This is one of many possible ways of doing this. Firstly you should notice that doing $a_{i}$ iterations in $i$-th step is equal to doing $a_{i}$ $mod$ $(n - i)$ iterations ($0$-based numbering). That is less than $n$. Now fill array of length $n$ w...
[ "implementation" ]
1,300
null
792
C
Divide by Three
A positive integer number $n$ is written on a blackboard. It consists of not more than $10^{5}$ digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible. The number is called beautiful if it consists of at least one digit, doesn't have lead...
Let's declare a function which takes number as a string and erases minimal number of digits in substring from $2$-nd to last character to obtain beautiful number. Note that if the answer for given string exists, then this function will erase no more than $2$ digits. If the number is divisible by $3$ then sum of its dig...
[ "dp", "greedy", "math", "number theory" ]
2,000
null
792
D
Paths in a Complete Binary Tree
$T$ is a complete binary tree consisting of $n$ vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So $n$ is a number such t...
In this editorial $x$ represents the number of vertex we are currently in. Let $k$ be the maximum integer number such that $x$ is divisible by $2^{k}$ (or the number of zeroes at the end of the binary representation of $x$). It is easy to prove that if $k = 0$, then $x$ is a leaf; if $k = 1$, then both children of $x$ ...
[ "bitmasks", "trees" ]
1,900
null
792
E
Colored Balls
There are $n$ boxes with colored balls on the table. Colors are numbered from $1$ to $n$. $i$-th box contains $a_{i}$ balls, all of which have color $i$. You have to write a program that will divide all balls into sets such that: - each ball belongs to exactly one of the sets, - there are no empty sets, - there is no ...
If we want to divide all balls from some box into $k$ sets with sizes $x$ and $x + 1$ (and there are $a_{i}$ balls in this box), then either $k\leq{\sqrt{a_{i}}}$ or $x\leq{\sqrt{a_{i}}}$. So the solution will be like that: Iterate over the possible sizes of sets $x$ (from $1$ to $|{\sqrt{a_{1}}}|$, or to some constant...
[ "greedy", "math", "number theory" ]
2,500
null
792
F
Mages and Monsters
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values $x_{i}$ and $y_{i}$ — damage per second and mana cost per second, respectiv...
Let's represent spells as points on cartesian plane. If we consider three spells $A$, $B$ and $C$ such that $A_{x} \le B_{x} \le C_{x}$ and $B$ is above $AC$ on the cartesian plane or belongs to it, then we don't need to use spell $B$ because we can replace it with a linear combination of spells $A$ and $C$ without...
[ "data structures", "geometry" ]
3,100
null
793
A
Oleg and shares
Oleg the bank client checks share prices every day. There are $n$ share prices he is interested in. Today he observed that each second exactly one of these prices decreases by $k$ rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. ...
Let's notice that as prices can only decrease and answer should be minimum possible, all prices should become equal to minimum among given prices. Formally, answer is $\sum_{i=1}^{n}{\frac{a_{i}-\operatorname*{min}a_{1},......a_{r}}{k}}$, if exists no such $i$ that $(a_{i}-\operatorname*{min}a_{1},\ldots,a_{n}){\mathrm...
[ "implementation", "math" ]
900
null
793
B
Igor and his way to work
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel,...
This problem has many solutions. The simplest of them is the following. Let's go over all cells where we can get before or after the first turn using simple recursive brute force. For every cell we should check if there exists a path from current cell to Igor's office. We can do it using prefix sums or even naively. Ot...
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
1,600
"#include <bits/stdc++.h>\n#define left lolkek\n \nusing namespace std;\n \nint n, m;\nvector<int> dx = {-1, 1, 0, 0};\nvector<int> dy = {0, 0, -1, 1};\nvector<char> dir = {'L', 'R', 'U', 'D'};\nvector<vector<int>> grid;\nvector<vector<int>> left;\nvector<vector<int>> up;\nint si = 0;\nint sj = 0;\nint ti = 0;\nint tj ...
793
C
Mice problem
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them. The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located i...
If at least one point will go on the border of rectangle then answer is <<$- 1$>>. For every point there exists (or doesn't exist) some segment of time when it's inside the rectangle. Then let's seperatly find segment when $x$ belongs to $(x_{1};x_{2})$ and $y$ inside $(y_{1};y_{2})$. Then we can intersect them and get...
[ "geometry", "implementation", "math", "sortings" ]
2,300
null
793
D
Presents in Bankopolis
Bankopolis is an incredible city in which all the $n$ crossroads are located on a straight line and numbered from $1$ to $n$ along it. On each crossroad there is a bank office. The crossroads are connected with $m$ oriented bicycle lanes (the $i$-th lane goes from crossroad $u_{i}$ to crossroad $v_{i}$), the difficult...
At any time Oleg can make correct move to crossroad from two segments: from crossroad $v$ he can go to crossroads from segment $[a;v - 1]$ or from segment $[v + 1;b]$. After we go from crossroad v to some crossroad u from segment $[a;v - 1]$ there appear two new segments: $[a;u - 1]$ and $[u + 1;v - 1]$. If we go from ...
[ "dp", "graphs", "shortest paths" ]
2,100
null
793
E
Problem of offices
Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices. Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offic...
Formal statement: we have a rooted tree, let it contain $m$ leaves. We can reorder sons of any vertex. We have to reorder tree in such way that while doing Eulerian tour (from vertex we go to it's first son, then to it's second son etc.) between visiting $a$ and $b$ we will visit exactly ${\frac{m}{2}}-1$ leaves, and s...
[ "constructive algorithms", "dfs and similar", "dp", "trees" ]
2,900
null
793
F
Julia the snail
After hard work Igor decided to have some rest. He decided to have a snail. He bought an aquarium with a slippery tree trunk in the center, and put a snail named Julia into the aquarium. Igor noticed that sometimes Julia wants to climb onto the trunk, but can't do it because the trunk is too slippery. To help the sna...
At first, let's solve this task with $O(r - l)$ time complexity for each query. For each $i$, let's store $back_{i}$ if there is exists a segment [$back_{i}$; $i$] (there's at most one such segment for every $i$). For query [$l$, $r$], let's go from $l$ to $r$, storing rightmost $x$, that is reachable from $l$ (at star...
[ "data structures", "divide and conquer", "dp" ]
3,000
null
793
G
Oleg and chess
Oleg the bank client solves an interesting chess problem: place on $n × n$ chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell. Remind that a rook standing in the cell $(a, b)$ beats a rook standing in the cell $(x, y)$ if and only if $a = x$ or $b...
Naive solution: Make bipartite graph, there is edge $i \rightarrow j$ only if cell $(i, j)$ is free. Then answer is maximum matching. But this solution time complexity is $O(n^{3})$ To get faster solution, let's cut our field into rectangles that are free of occupied cells. We will go from left to right wth line swee...
[ "data structures", "divide and conquer", "flows", "graph matchings" ]
3,400
null
794
A
Bank Robbery
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the $i$-th safe f...
This is a simple implementation problem. We iterate through all banknotes one by one and check if Oleg can take each of them. If a banknote is at position $x$, then Oleg can take it if and only if $b < x < c$. This can be checked in $O(1)$ time. Thus, the total complexity is $O(n)$. Note that the information on the sta...
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
794
B
Cutting Carrot
Igor the analyst has adopted $n$ little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into $n$ pieces of equal area. Formally, the carrot can be viewed as an isosceles tria...
Let's find the value of $x_{i}$ explicitly. Suppose we make the $i$-th cut and distance $x_{i}$ from the apex. Then, the ratio of similitude of the isosceles triangle with apex equal to the apex of the carrot and the base equal to the $i$-th cut and the whole carrot is $\scriptstyle{\frac{\pi_{h}}{h}}$. Since the area ...
[ "geometry", "math" ]
1,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
794
C
Naming Company
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of $n$ letters. Oleg and Igor ...
First, it is clear that Oleg will place $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$ letters and Igor will place $\textstyle{\left[{\frac{n}{2}}\right]}$ letters. Next, it is clear that Oleg and Igor will both choose their smallest and biggest letters respectively to place in the final string. Thus, we now conside...
[ "games", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
794
D
Labelling Cities
Oleg the bank client lives in Bankopolia. There are $n$ cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from $1$ to $n$. There are a total of $m$ roads in Bankopolia, the $i$-th road connects cities $u_{i}$ and $v_{i}$. It is guaranteed that from each...
Add each vertex to its own adjacency list. Now, we claim that if it is possible to label the cities to satisfy the problem conditions, then it is possible to do so so that for every two cities with the same adjacency list, they're labelled with the same number. Indeed, if they have the same adjacency list, they must be...
[ "dfs and similar", "graphs", "hashing" ]
2,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<in...
794
E
Choosing Carrot
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are $n$ carrots arranged in...
First, we solve the problem when no one has any extra turns. Suppose we're binary searching the answer. Let all the numbers $ \ge x$ be equal to $1$ and all the numbers $< x$ be equal to $0$. Both players can remove one number from one end of the row. The goal of the first player is to let the remaining number be $1$ ...
[ "games", "math" ]
2,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
794
F
Leha and security system
Bankopolis, the city you already know, finally got a new bank opened! Unfortunately, its security system is not yet working fine... Meanwhile hacker Leha arrived in Bankopolis and decided to test the system! Bank has $n$ cells for clients' money. A sequence from $n$ numbers $a_{1}, a_{2}, ..., a_{n}$ describes the amo...
We use a segment tree to solve this problem. For each node, it is sufficient to store two arrays : $sum[i]$, denoting the total contribution of the digit $i$ in the current segment (if a digit is in the tens digit then it contributes $10$ to the sum and etc...), and also $nxt[i]$, what all the digits $i$ in the current...
[ "data structures" ]
2,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
794
G
Replace All
Igor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem: Given two strings $x$ and $y$ which consist of the English letters 'A' and 'B' only, a pair of strings $(s, t)$ is called \underline{good} if: - $s...
First, we solve the problem when there're no question marks, i.e. we find a way to calculate the number of good pairs of strings fast for a constant pair of strings $A$ and $B$. Call a pair of strings $(S, T)$ where $|S| \le |T|$ coprime if $S = T$ or $S$ is a prefix of $T$, and if $T = S + X$, then $(X, S)$ is also ...
[ "combinatorics", "dp", "math" ]
3,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll...
796
A
Buying A House
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. The girl lives in house $m$ of a village. There are $n$ houses in that village, lining in a straight line from left to right: house $1$, house $2$, ..., house $n$. The village is also well-structured: ho...
This is a simple implementation problem. Let the $ans$ be infinity initially. Iterate through the houses. Suppose we are considering house $i$, update the $ans$ if and only if 1) $a_{i} \neq 0$, 2) $a_{i} \le k$, and 3) $|i - m|$ < $ans$. The answer is $10 * ans$. This solution runs in $O(n)$.
[ "brute force", "implementation" ]
800
"#include <stdio.h>\n\nint min(int a, int b){ return a < b ? a : b; }\nint abs(int x){ return x < 0 ? -x : x; }\n\nint main(){\n int n, m, k;\n scanf(\"%d%d%d\", &n, &m, &k);\n int res = 1e9;\n for(int i=1; i<=n; i++){\n int a;\n scanf(\"%d\", &a);\n if(a != 0 && a <= k) res = min(res, ...
796
B
Find The Bone
Zane the wizard is going to perform a magic show shuffling the cups. There are $n$ cups, numbered from $1$ to $n$, placed along the $x$-axis on a table that has $m$ holes on it. More precisely, cup $i$ is on the table at the position $x = i$. The problematic bone is initially at the position $x = 1$. Zane will confus...
This is another implementation problem. Let's create an array $a$ of length $n$ (with initial values set to $0$), and set $a_{i}$ = $1$ only for the positions $x = i$ where there is a hole. If there is a hole at $x$ $=$ $1$, obviously, the answer is $1$, because the ball must fall onto the ground before any operation i...
[ "implementation" ]
1,300
"#include <stdio.h>\n\nint isHole[1000005];\n\nint main(){\n int n, m, k;\n scanf(\"%d%d%d\", &n, &m, &k);\n for(int i=0; i<m; i++){\n int h;\n scanf(\"%d\", &h);\n isHole[h] = 1;\n }\n int pos = 1;\n for(int i=0; i<k; i++){\n int u, v;\n scanf(\"%d%d\", &u, &v);\n ...
796
C
Bank Hacking
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are $n$ banks, numbered from $1$ to $n$. There are also $n - 1$ wires connecting the b...
First, note that the input graph is a tree. Let $m$ be the greatest value of $a_{i}$ (that is, $max(a_{1}, a_{2}, ..., a_{n})$). Observe that the answer can be $m$, $m + 1$, or $m + 2$ only. Why? It is because each bank's strength can be increased at most twice, once by a neighboring bank, and once by a semi-neighborin...
[ "constructive algorithms", "data structures", "dp", "trees" ]
1,900
"#include <stdio.h>\n#include <vector>\nusing namespace std;\n\nint a[300005];\nvector<int> way[300005];\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n int maxval=-1e9;\n for(int i=1; i<=n; i++) scanf(\"%d\", &a[i]), maxval = max(maxval, a[i]);\n for(int i=0; i<n-1; i++){\n int u, v;\n scan...
796
D
Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be pos...
A greedy solution shutting down either every d roads or when a police station is encountered, although seems pretty nice, turns out to be incorrect. Consider performing a breadth first search (BFS) with "cities with a police station" as starting vertices, and shutting down the road when it leads to a visited vertex (ci...
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees" ]
2,100
"#include <stdio.h>\n#include <queue>\n#include <vector>\nusing namespace std;\n\nqueue<pair<int, int>> q;\nvector<pair<int, int>> way[300005];\nint v[300005];\nint res[300005];\n\nint main(){\n int n, k, d;\n scanf(\"%d%d%d\", &n, &k, &d);\n for(int i=0; i<k; i++){\n int p;\n scanf(\"%d\", &p);\...
796
E
Exam Cheating
Zane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help. There are $n$ questions, numbered from $1$ to $n$. Question $i$ comes before question $i + 1$ ($1 ≤ i < n$). Each of the questions cannot be guessed on, due to the huge penalty for w...
This problem can be solved using dynamic programming. First, observe that it is never suboptimal to look as many consecutive questions as possible. That is, just look $k$ consecutive questions whenever you decide to glance, unless it exceeds the corner (question $n$). Let $dp[i][j][a][b]$ denote the number of questions...
[ "binary search", "dp" ]
2,400
"#include <stdio.h>\n\nint A[1005], B[1005];\nint dp[2][1005][55][55];\n\nint max(int a, int b){ return a > b ? a : b; }\n\nint main(){\n int n, p, k;\n scanf(\"%d%d%d\", &n, &p, &k);\n if(k == 0){ printf(\"0\"); return 0; }\n if(p > 2*((n+k-1)/k)) p = 2*((n+k-1)/k);\n int r;\n scanf(\"%d\", &r);\n ...
796
F
Sequence Recovery
Zane once had a good sequence $a$ consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ — but he has lost it. A sequence is said to be good if and only if all of its integers are non-negative and do not exceed $10^{9}$ in value. However, Zane remembers having played around with his sequence by applying $m$ operations...
First, let's find the maximum value each integer can be. Chronologically considering the operations, you can see that once an integer is involved in type 2 operation, future type 1 operations can tell nothing about its initial value. You can find naively find the maximum value each integer can be in $O(nm)$, but that's...
[ "bitmasks", "data structures", "greedy" ]
2,800
"#include <stdio.h>\n#include <algorithm>\n#include <map>\nusing namespace std;\n\nint n;\nint type[300005], a[300005], b[300005], c[300005];\nint res[300005];\nmap<int, int> occ;\n\n// Segment Tree 1\n\nint t[600005];\n\nint findmax(int p){\n int res=2e9;\n for (p+=n; p; p>>=1) res = min(res, t[p]);\n return ...
797
A
k-Factorization
Given a positive integer $n$, find $k$ integers (not necessary distinct) such that all these integers are strictly greater than $1$, and their product is equal to $n$.
There are many approaches to this problem. You can, for example, factorize $n$, store all multipliers in a list, and while size of this list is greater than $k$, take any two elements of this list and replace them with their product. If the initial size of this list is less than $k$, then answer is -1.
[ "implementation", "math", "number theory" ]
1,100
null