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 ⌀ |
|---|---|---|---|---|---|---|---|
610 | E | Alphabet Permutations | You are given a string $s$ of length $n$, consisting of first $k$ lowercase English letters.
We define a $c$-repeat of some string $q$ as a string, consisting of $c$ copies of the string $q$. For example, string "acbacbacbacb" is a $4$-repeat of the string "acb".
Let's say that string $a$ contains string $b$ as a sub... | Consider slow solution: for operations of the first type reassign all letters, for operations of the second type let's iterate over the symbols in $s$ from left to right and maintain the pointer to the current position in alphabet permutation. Let's move the pointer cyclically in permutation until finding the current s... | [
"data structures",
"strings"
] | 2,500 | null |
611 | A | New Year and Days | Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.
Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.
Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ... | There are two ways to solve this problem. The first is to hard-code numbers of days in months, check the first day of the year and then iterate over days/months - The second way is to check all possible cases by hand. The 2016 consists of 52 weeks and two extra days. The answer for "x of week" will be either 52 or 53. ... | [
"implementation"
] | 900 | "// Days (A), by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nint t[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n\nint main() {\n\tint x;\n\tscanf(\"%d\", &x);\n\tchar sl[15];\n\tscanf(\"%s\", sl);\n\tscanf(\"%s\", sl);\n\tif(sl[0] == 'w') {\n\t int current = 5;\n\t int ans = 0;\n\t f... |
611 | B | New Year and Old Property | The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — $2015_{10} = 11111011111_{2}$. Note that he doesn't care about the number of zeros in the decimal representation... | Each number with exactly one zero can be obtained by taking the number without any zeros (e.g. $63_{10} = 111111_{2}$) and subtracting some power of two, e.g. $63_{10} - 16_{10} = 111111_{2} - 10000_{2} = 101111_{2}$. Subtracting a power of two changes one digit from '1' to '0' and this is what we want. But how can we ... | [
"bitmasks",
"brute force",
"implementation"
] | 1,300 | "// One zero, by Errichto\n// O(log^2(n))\n#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tlong long a, b;\n\tscanf(\"%lld%lld\", &a, &b);\n\tint c = 0;\n\tfor(int i = 0; (1LL << i) / 2 <= b; ++i)\n\t\tfor(int j = 0; j <= i - 2; ++j) {\n\t\t\tlong long x = (1LL << i) - 1 - (1LL << j);\n\t\t\tc += a <= ... |
611 | C | New Year and Domino | They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.
Limak is a little polar bear who loves to play. He has recently got a rectangular grid with $h$ rows and $w$ columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#').... | How would we solve this problem in $O(wh + q)$ if a domino would occupy only one cell? Before reading queries we would precalculate $dp[r][c]$ - the number of empty cells in a "prefix" rectangle with bottom right corner in a cell $r, c$. Then the answer for rectangle $r1, c1, r2, c2$ is equal to $dp[r2][c2] - dp[r2][c1... | [
"dp",
"implementation"
] | 1,500 | "// Domino (C), by Errichto\n// AC, O(wh + q)\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 2005;\nchar sl[nax][nax];\n// horizontal and vertical\nint hor[nax][nax], ver[nax][nax];\n\nint main() {\n\tint w, h;\n\tscanf(\"%d%d\", &h, &w);\n\tfor(int y = 0; y < h; ++y) scanf(\"%s\", sl[y]);\n\tfor(int... |
611 | D | New Year and Ancient Prophecy | Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of $n$ digits. The first digit isn't zero. Limak thinks that it's a list of some... | By ${x... y}$ I will mean the number defined by digits with indices $x, x + 1, ..., y$. Let $dp[b][c]$ define the number of ways to split some prefix (into increasing numbers) so that the last number is ${b... c}$ We will try to calculate it in $O(n^{2})$ or $O(n^{2}\log{n})$. The answer will be equal to the sum of val... | [
"dp",
"hashing",
"strings"
] | 2,000 | "// Ancient Prophecy (D), by Errichto\n// AC, O(n^2)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\n\nconst int nax = 5005;\nconst int mod = 1e9 + 7;\nconst int inf = 1e9 + 120;\n\nint t[nax];\nchar sl[na... |
611 | E | New Year and Three Musketeers | Do you know the story about the three musketeers? Anyway, you must help them now.
Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength $a$, Borthos strength $b$, and Caramis has strength $c$.
The year 2015 is almost over and there ar... | The answer is $- 1$ only if there is some criminal stronger than $a + b + c$. Let's deal with this case and then let's assume that $a \le b \le c$. Let's store all criminal- s in a set (well, in a multiset). Maybe some criminals can be defeated only by all musketeers together. Let's count and remove them. Then, may... | [
"data structures",
"greedy",
"sortings"
] | 2,400 | "// Musketeers\n// AC, O(n log(n))\n// by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 1e6 + 5;\nconst int inf = 1e9 + 5;\nint m[3];\nmultiset<int> enemies;\n\nvoid greedy(int atLeast, int extra, int & ans) {\n\twhile(!enemies.empty()) {\n\t\tauto it = enemies.end();\n\t\t--it;\n\t\tif(*it... |
611 | F | New Year and Cleaning | Limak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with $h$ rows and $w$ columns. Each cell is an empty square.
He is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot.
A cleaning robot h... | Let's not care where we start. We will iterate over robot's moves. Let's say the first moves are LDR. The very first move 'L' hits a wall only if we started in the first column. Let's maintain some subrectangle of the grid - starting cells for which we would still continue cleaning. After the first move our subrectangl... | [
"binary search",
"implementation"
] | 2,500 | "// Cleaning Robot (F), by Errichto\n// AC, O(w+h+n)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\ntypedef long long ll;\n\nconst int nax = 5e5 + 5;\nconst int mod = 1e9 + 7;\nchar sl[nax];\n\nint n;\nin... |
611 | G | New Year and Cake | Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes.
As you may know, a New Year cake is a strictly convex polygon with $n$ vertices.
Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking the... | We are given a polygon with vertices $P_{1}, P_{2}, ..., P_{n}$. Let $Poly(i, j)$ denote the doubled area of a polygon with vertices $P_{i}, P_{i + 1}, P_{i + 2}, ..., P_{j - 1}, P_{j}$. While implementing you must remember that indices are in a circle (there is $1$ after $n$) but I won't care about it in this editoria... | [
"geometry",
"two pointers"
] | 2,900 | "// Cake, by Errichto\n// intended, O(n)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\ntypedef long long ll;\n\nconst int nax = 1e6 + 15;\nconst int mod = 1e9 + 7;\n\nstruct P {\n\tll x, y;\n\tll operato... |
611 | H | New Year and Forgotten Tree | A tree is a connected undirected graph with $n - 1$ edges, where $n$ denotes the number of vertices. Vertices are numbered $1$ through $n$.
Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tr... | There are at most $k = 6$ groups of vertices. Each grouped is defined by the number of digits of its vertices. It can be probed that you can choose one vertex (I call it "boss") in each group and then each edge will be incident with at least one boss. We can iterate over all $k^{k - 2}$ possible labeled trees - we must... | [
"constructive algorithms",
"flows",
"graphs"
] | 3,200 | "// Forgotten tree (H), by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\n\nchar sl[10];\nint e[10][10], e_memo[10][10];\nvector<int> group[10];\nint boss[10];\n\ntypedef vector<pair<int,int>> Tr... |
612 | A | The Text Splitting | You are given the string $s$ of length $n$ and the numbers $p, q$. Split the string $s$ to pieces of length $p$ and $q$.
For example, the string "Hello" for $p = 2$, $q = 3$ can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string $s$ to the strings o... | Let's fix the number $a$ of strings of length $p$ and the number $b$ of strings of length $q$. If $a \cdot p + b \cdot q = n$, we can build the answer by splitting the string $s$ to $a$ parts of the length $p$ and $b$ parts of the length $q$, in order from left to right. If we can't find any good pair $a, b$ then the a... | [
"brute force",
"implementation",
"strings"
] | 1,300 | null |
612 | B | HDD is Outdated Technology | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s... | You are given the permutation $f$. Let's build another permutation $p$ in the following way: $p_{fi} = i$. So the permutation $p$ defines the number of sector by the number of fragment. The permutation $p$ is called inverse permutation to $f$ and denoted $f^{ - 1}$. Now the answer to problem is $\textstyle\sum_{i=1}^{n... | [
"implementation",
"math"
] | 1,200 | null |
612 | C | Replace To Make Regular Bracket Sequence | You are given string $s$ consists of opening and closing brackets of four kinds <>, {{}}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {{}, but you can't replace it by ) or >.
The following definitio... | If we forget about bracket kinds the string $s$ should be RBS, otherwise the answer doesn't exist. If the answer exists each opening bracket matches to exactly one closing bracket and vice verse. Easy to see that if two matching brackets have the same kind we don't need to replace them. In other case we can change the ... | [
"data structures",
"expression parsing",
"math"
] | 1,400 | null |
612 | D | The Union of k-Segments | You are given $n$ segments on the coordinate axis Ox and the number $k$. The point is satisfied if it belongs to at least $k$ segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others. | Let's create two events for each segment $l_{i}$ is the time of the segment opening and $r_{i}$ is the time of the segment closing. Let's sort all events by time, if the times are equal let's sort them with priority to opening events. In C++ it can be done with sorting by standard comparator of vector<pair<int, int>> e... | [
"greedy",
"sortings"
] | 1,800 | null |
612 | E | Square Root of Permutation | A permutation of length $n$ is an array containing each integer from $1$ to $n$ exactly once. For example, $q = [4, 5, 1, 2, 3]$ is a permutation. For the permutation $q$ the square of permutation is the permutation $p$ that $p[i] = q[q[i]]$ for each $i = 1... n$. For example, the square of $q = [4, 5, 1, 2, 3]$ is $p ... | Consider some permutation $q$. Let's build by it the oriented graph with edges $(i, q_{i})$. Easy to see (and easy to prove) that this graph is the set of disjoint cycles. Now let's see what would be with that graph when the permutation will be multiplied by itself: all the cycles of odd length would remain so (only th... | [
"combinatorics",
"constructive algorithms",
"dfs and similar",
"graphs",
"math"
] | 2,200 | null |
612 | F | Simba on the Circle | You are given a circular array with $n$ elements. The elements are numbered from some element with values from $1$ to $n$ in clockwise order. The $i$-th cell contains the value $a_{i}$. The robot Simba is in cell $s$.
Each moment of time the robot is in some of the $n$ cells (at the begin he is in $s$). In one turn th... | The author solution for this problem uses dynamic programming. I think that this problem can't be solved by greedy ideas. Let's calculate two dp's: $z1_{i}$ is the answer to the problem if all numbers less than $a_{i}$ are already printed, but the others are not; and $z2_{i}$ is the answer to the problem if all numbers... | [
"dp"
] | 2,600 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
613 | A | Peter and Snow Blower | Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it... | Consider distances between the point $P$ and all points of the polygon. Let $R$ be the largest among all distances, and $r$ be the smallest among all distances. The swept area is then a ring between circles of radii $R$ and $r$, and the answer is equal to $ \pi (R^{2} - r^{2})$. Clearly, $R$ is the largest distance be... | [
"binary search",
"geometry",
"ternary search"
] | 1,900 | null |
613 | B | Skills | Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly $n$ skills. Each skill is represented by a non-negative integer $a_{i}$ — the current skill level. All skills have the same maximum level $A$.
A... | Let's save the original positions of skills and then sort the skills in non-increasing order (almost decreasing) by current level. We can always restore original order after. Imagine that we have decided that we want to use the minimum level $X$ and now we're choosing which skills we should bring to the maximum. At fir... | [
"binary search",
"brute force",
"dp",
"greedy",
"sortings",
"two pointers"
] | 1,900 | null |
613 | C | Necklace | Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).
... | Surprisingly, the nice cuts can't be put randomly. Let's take a look on the first picture above (red lines represent nice cut points). But since the necklace is symmetrical relative to nice cuts, the cut points are also symmetrical relative to nice cuts, so there is one more cut (see picture two). Repeating this proces... | [
"constructive algorithms",
"math"
] | 2,500 | null |
613 | D | Kingdom and its Cities | Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom curren... | Obviously, the answer is -1 iff two important cities are adjacent. If there was a single query, can we answer it in $O(n)$ time? Let's choose a root arbitrarily. We can note there is an optimal answer that erases two types of vertices: vertices that lie on a vertical path between two important vertices, or LCA of some ... | [
"dfs and similar",
"divide and conquer",
"dp",
"graphs",
"sortings",
"trees"
] | 2,800 | null |
613 | E | Puzzle Lover | Oleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below.
The puzzle field consists of tw... | The key observation: any way to cross out the word $w$ looks roughly as follows: That is, there can be following parts: go back $a$ symbols in one row, then go forward $a$ symbols in the other row (possibly $a = 0$) go forward with arbitrarily up and down shifts in a snake-like manner go forward $b$ symbols in one row,... | [
"dp",
"hashing",
"strings"
] | 3,200 | null |
614 | A | Link/Cut Tree | Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the $expose$ procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agre... | You had to print all numbers of form $k^{x}$ for non-negative integers $x$ that lie with the range $[l;r]$. A simple cycle works: start with $1 = k^{0}$, go over all powers that do not exceed $r$ and print those which are at least $l$. One should be careful with 64-bit integer overflows: consider the test $l = 1$, $r =... | [
"brute force",
"implementation"
] | 1,500 | null |
614 | B | Gena's Code | It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | You were asked to print the product of $n$ large numbers, but it was guaranteed that at least $n - 1$ are beautiful. It's not hard to see that beautiful numbers are 0 and all powers of 10 (that is, 1 followed by arbitrary number of zeros). If there is at least one zero among the given numbers, the product is 0. Otherwi... | [
"implementation",
"math"
] | 1,400 | null |
615 | A | Bulbs | Vasya wants to turn on Christmas lights consisting of $m$ bulbs. Initially, all bulbs are turned off. There are $n$ buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
I... | Let's make a counter of number of buttons that switch every lamp off. If there is a lamp with zero counter, output NO, otherwise YES. | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
int n, m;
cin >> m >> n;
vector<int> cnt(n);
while (m--) {
int k;
cin >> k;
vector<int> ys(k);
for (auto &y : ys) {
cin >> y;
cnt[y - 1]++;
}
}
for... |
615 | B | Longtail Hedgehog | This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of $n$ points connected by $m$ segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a... | Way of solving - dynamic programming. We are given a graph of n vertices and m edges. We will calculate dp[i] - a maximum length of tail that is ending in i-th vertex. We can simply update dp by checking all the edges from i-th vertex(which are leading to vertices with bigger number), and trying to update them. When we... | [
"dp",
"graphs"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
typedef long long ll;
const int maxN = 1 << 17;
int dp[maxN];
vector<int> g[maxN];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
while(m--) {
int v, u;
cin >>... |
615 | C | Running Track | A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.
First, he wants to construct the running track with coating $t$. On planet AMI-1511 the coating of the t... | The idea is that if can make a substring t[i, j] using k coatings, then we can also make a substring t[i + 1, j] using k coatings. So we should use the longest substring each time. Let n = |s|, m = |t|. On each stage we will search for the longest substring in s and s_reversed to update the answer. We can do it in seve... | [
"dp",
"greedy",
"strings",
"trees"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
const int maxC = 'z' - 'a' + 1;
struct Node {
int next[maxC];
int l, r;
Node() {
memset(this, 0, sizeof(*this));
}
};
struct Trie {
vector<Node> T;
Trie() {
... |
615 | D | Multipliers | Ayrat has number $n$, represented as it's prime factorization $p_{i}$ of size $m$, i.e. $n = p_{1}·p_{2}·...·p_{m}$. Ayrat got secret information that that the product of all divisors of $n$ taken modulo $10^{9} + 7$ is the password to the secret data base. Now he wants to calculate this value. | Let d(x) be a number of divisors of x, and f(x) be the product of divisors. Let $x = p_{1}^{ \alpha 1}p_{2}^{ \alpha 2}... p_{n}^{ \alpha n}$, then $d(x) = ( \alpha _{1} + 1) \cdot ( \alpha _{2} + 1)... ( \alpha _{n} + 1)$ $f(x)=x^{\frac{d(x)}{2}}$. There is $\textstyle{\frac{d(x)}{2}}\right\}$ pairs of divisors of typ... | [
"math",
"number theory"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
typedef long long ll;
const ll MOD = (ll)1e9 + 7;
ll binPow(ll a, ll q, ll MOD) {
a %= MOD;
if (q == 0) return 1;
return ((q % 2 == 1 ? a : 1) * binPow(a * a, q / 2, MOD)) % MOD;
}
... |
615 | E | Hexagons | Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined:
Ayrat is searching through the field. He started at point $(0, 0)$ and is mo... | Let's see how the coordinates are changing while we move from current cell to one of the 6 adjacent cells - let's call this 6 typed of moves. If we know the number of moves of each type on our way, then we know the coordinates of the end of the way. We will divide the way into rings. Let's count the number of moves of ... | [
"binary search",
"implementation",
"math"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
pair<ll, ll> solve(ll n) {
ll j = 0, cur = 0;
ll x = 0, y = 0;
vector<ll> dx = {1, -1, -2, -1, 1, 2};
vector<ll> dy = {2, 2, 0, -2, -2, 0};
vector<ll> cnt = {1, 0, 1, 1, 1, 1};
ll l ... |
616 | A | Comparing Two Long Integers | You are given two very long integers $a, b$ (leading zeroes are allowed). You should check what number $a$ or $b$ is greater or determine that they are equal.
The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.
As input/output can reac... | Note that solutions in Java with BigInteger class or input() function in Python2 will fail in this problem. The reason is the next: standard objects stores numbers not in decimal system and need a lot of time to convert numbers from decimal system. Actually they are working in $O(n^{2})$, where $n$ is the legth of the ... | [
"implementation",
"strings"
] | 900 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
616 | B | Dinner with Emma | Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.
Munhattan consists of $n$ streets and $m$ avenues. There is exactly one restaurant on the intersection of each street and avenue. The stree... | Firstly you should find the minimum value in each row and after that you should find the maximum value over that minimums. It's corresponding to the strategy of Jack and Emma. Complexity: $O(nm)$. | [
"games",
"greedy"
] | 1,000 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
616 | C | The Labyrinth | You are given a rectangular field of $n × m$ cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that... | Let's enumerate all the connected components, store their sizes and for each empty cell store the number of it's component. It can be done with a single dfs. Now the answer for some impassable cell is equal to one plus the sizes of all different adjacent connected components. Adjacent means the components of cells adja... | [
"dfs and similar"
] | 1,600 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
616 | D | Longest k-Good Segment | The array $a$ with $n$ integers is given. Let's call the sequence of one or more consecutive elements in $a$ segment. Also let's call the segment k-good if it contains no more than $k$ different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output... | This problem is given because on the Codeforces pages we often see questions like "What is the method of the two pointers?". This problem is a typical problem that can be solved using two pointers technique. Let's find for each left end $l$ the maximal right end $r$ that $(l, r)$ is a $k$-good segment. Note if $(l, r)$... | [
"binary search",
"data structures",
"two pointers"
] | 1,600 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
616 | E | Sum of Remainders | Calculate the value of the sum: $n$ mod $1$ + $n$ mod $2$ + $n$ mod $3$ + ... + $n$ mod $m$. As the result can be very large, you should print the value modulo $10^{9} + 7$ (the remainder when divided by $10^{9} + 7$).
The modulo operator $a$ mod $b$ stands for the remainder after dividing $a$ by $b$. For example $10$... | Unfortunately my solution for this problem had overflow bug. It was fixed on contest. Even so I hope you enjoyed the problem because I think it's very interesting. Let's transform the sum $\sum_{i=1}^{m}n\ m o d\ i=\sum_{i=1}^{m}\left(n-\lfloor{\frac{n}{i}}\rfloor i\right)=m n-\sum_{i=1}^{m}\lfloor{\frac{n}{i}}\rfloor ... | [
"implementation",
"math",
"number theory"
] | 2,200 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
616 | F | Expensive Strings | You are given $n$ strings $t_{i}$. Each string has cost $c_{i}$.
Let's define the function of string $s:f(s)=\sum_{i=1}^{n}c_{i}\cdot p_{s,i}\cdot|s$, where $p_{s, i}$ is the number of occurrences of $s$ in $t_{i}$, $|s|$ is the length of the string $s$. Find the maximal value of function $f(s)$ over all strings.
Not... | This problem was prepared by Grigory Reznikow vintage_Vlad_Makeev. His solution uses suffix array. This problem is a typical problem for some suffix data structure. Four competitors who solved this problem during the contest used suffix automaton and one competitor used suffix tree. My own solution used suffix tree so ... | [
"data structures",
"sortings",
"string suffix structures",
"strings"
] | 2,700 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
617 | A | Elephant | An elephant decided to visit his friend. It turned out that the elephant's house is located at point $0$ and his friend's house is located at point $x(x > 0)$ of the coordinate line. In one step the elephant can move $1$, $2$, $3$, $4$ or $5$ positions forward. Determine, what is the minimum number of steps he need to ... | It's optimal to do the biggest possible step everytime. So elephant should do several steps by distance 5 and one or zero step by smaller distance. Answer equals to $\left[{\frac{x}{5}}\right]$ | [
"math"
] | 800 | #include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
cout << (x + 4) / 5 << '\n';
} |
617 | B | Chocolate | Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain \textbf{exactly} one nut and any break line goes between two adjacent pieces.
You are asked to calculate the number of wa... | We are given array which contains only ones and zeroes. We must divide it on parts with only one 1. Tricky case: when array contains only zeroes answer equals to 0. In general. Between two adjacent ones we must have only one separation. So, answer equals to product of values $pos_{i} - pos_{i - 1}$ where $pos_{i}$ is p... | [
"combinatorics"
] | 1,300 | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int prev = -1;
long long result = 0;
for (int i = 0; i < n; i++) {
int v;
cin >> v;
if (v == 1) {
if (prev == -1) {
result = 1;
} else {
result *... |
617 | C | Watering Flowers | A flowerbed has many flowers and two fountains.
You can adjust the water pressure and set any values $r_{1}(r_{1} ≥ 0)$ and $r_{2}(r_{2} ≥ 0)$, giving the distances at which the water is spread from the first and second fountain respectively. You have to set such $r_{1}$ and $r_{2}$ that all the flowers are watered, t... | First radius equals to zero or distance from first fountain to some flower. Let's iterate over this numbers. Second radius equals to maximal distance from second fountain to flower which doesn't belong to circle with first radius. Now we should choose variant with minimal $r_{1}^{2} + r_{2}^{2}$. Bonus: It's $O(n^{2})$... | [
"implementation"
] | 1,600 | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
ll square(int x) {
return x * (ll) x;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n, x1, y1, x2, y2;
cin >> n >> x1 >> y1 >> x2 >> y2;
vector< pair<ll, ll> > dist(n);
... |
617 | D | Polyline | There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this p... | Answer equals to one if all coordinates x or y of points are same. When answer equals to two? Let's iterate over all pairs of points. Let first point in pair is beginning of polyline, second point is end. Only one or two such polylines with answer two exist. If third point is on the polyline it belongs to rectangle wit... | [
"constructive algorithms",
"implementation"
] | 1,700 | #include <iostream>
using namespace std;
int x[3], y[3];
bool is_between(int a, int b, int c) {
return min(a, b) <= c && c <= max(a, b);
}
bool f(int i, int j, int k) {
return (x[k] == x[i] || x[k] == x[j]) && is_between(y[i], y[j], y[k]) ||
(y[k] == y[i] || y[k] == y[j]) && is_between(x[i], ... |
617 | E | XOR and Favorite Number | Bob has a favorite number $k$ and $a_{i}$ of length $n$. Now he asks you to answer $m$ queries. Each query is given by a pair $l_{i}$ and $r_{i}$ and asks you to count the number of pairs of integers $i$ and $j$, such that $l ≤ i ≤ j ≤ r$ and the xor of the numbers $a_{i}, a_{i + 1}, ..., a_{j}$ is equal to $k$. | We have array $a$. Let's calculate array $pref$ ($pref[0] = 0$, $p r e f[i]=p r e f[i-1]\oplus a[i]$). Xor of subarray $a[l...r]$ equals to $p r e f[l-1]\oplus p r e f[r]$. So query (l, r) is counting number of pairs $i$, $j$ ($l - 1 \le i < j \le r$) $p r e f[i]\oplus p r e f[j]=k$. Let we know answer for query (l... | [
"data structures"
] | 2,200 | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int BLOCK_SIZE = 316; //sqrt(1e5)
struct Query {
int left, right, number;
bool operator < (const Query other) const {
return right < other.right;
}
};
int cnt[1 << 20];
long long result = 0;
int favourite... |
618 | A | Slime Combining | Your friend recently gave you some slimes for your birthday. You have $n$ slimes all initially with value $1$.
You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other $n - 1$ slimes one by one. When you add a slime, you place it at the right of... | We can simulate the process described in the problem statement. There are many possible implementations of this, so see the example code for one possible implementation. This method can take O(n) time. However, there is a faster method. It can be shown that the answer is simply the 1-based indices of the one bits in th... | [
"implementation"
] | 800 | n = int(raw_input())
print " ".join(str(i+1) for i in range(20,-1,-1) if (n&(1<<i)) > 0) |
618 | B | Guess the Permutation | Bob has a permutation of integers from $1$ to $n$. Denote this permutation as $p$. The $i$-th element of $p$ will be denoted as $p_{i}$. For all pairs of distinct integers $i, j$ between $1$ and $n$, he wrote the number $a_{i, j} = min(p_{i}, p_{j})$. He writes $a_{i, i} = 0$ for all integer $i$ from $1$ to $n$.
Bob g... | One solution is to look for the column/row that contains only 1s and 0s. We know that this index must be the index for the element 1. Then, we can repeat this for 2 through n. See the example code for more details. The runtime of this solution is O(n^3). However, there is an easier solution. One answer is to just take ... | [
"constructive algorithms"
] | 1,100 | import sys
f = sys.stdin
n = int(f.readline())
arr = [max(map(int, f.readline().split())) for i in range(n)]
arr[arr.index(n-1)] = n
print " ".join(map(str,arr)) |
618 | C | Constellation | Cat Noku has obtained a map of the night sky. On this map, he found a constellation with $n$ stars numbered from $1$ to $n$. For each $i$, the $i$-th star is located at coordinates $(x_{i}, y_{i})$. No two stars are located at the same position.
In the evening Noku is going to take a look at the night sky. He would li... | There are many possible solutions to this problem. The first solution is to choose any nondegenerate triangle. Then, for each other point, if it is inside the triangle, we can replace one of our three triangle points and continue. We only need to make a single pass through the points. We need to be a bit careful about ... | [
"geometry",
"implementation"
] | 1,600 | import sys
import random
from fractions import gcd
f = sys.stdin
n = int(f.readline())
x,y = zip(*[map(int, f.readline().split()) for i in range(n)])
st = random.randint(0, n-1)
dist = [(x[i]-x[st])*(x[i]-x[st])+(y[i]-y[st])*(y[i]-y[st]) for i in range(n)]
def getSlope(x1,y1):
g = gcd(abs(x1),abs(y1))
x1,y1 = x1/... |
618 | D | Hamiltonian Spanning Tree | A group of $n$ cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are $\textstyle{\frac{n(n-1)}{2}}$ roads in total. It takes exactly $y$ seconds to traverse \textbf{any} single road.
A spanning tree is a set of roads containing exactly $n - 1$ roads such that... | This is two separate problems: One where X > Y and when X <= Y. Suppose X > Y. Then, we can almost always choose a path that avoides any spanning tree edges. There is one tricky case, which is the case of a star graph. To prove the above statement, we know a tree is bipartite, so let's choose a bipartition X,Y. As long... | [
"dfs and similar",
"dp",
"graph matchings",
"greedy",
"trees"
] | 2,200 | import java.io.*;
import java.util.*;
public class HamiltonianTree {
private static InputReader in;
private static PrintWriter out;
public static ArrayList<Integer>[] graph;
public static void main (String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out, true);
in... |
618 | E | Robot Arm | Roger is a robot. He has an arm that is a series of $n$ segments connected to each other. The endpoints of the $i$-th segment are initially located at points $(i - 1, 0)$ and $(i, 0)$. The endpoint at $(i - 1, 0)$ is colored red and the endpoint at $(i, 0)$ is colored blue for all segments. Thus, the blue endpoint of t... | We can view a segment as a linear transformation in two stages, first a rotation, then a translation. We can describe a linear transformation with a 3x3 matrix, so for example, a rotation by theta is given by the matrix {{cos(theta), sin(theta), 0}, {-sin(theta), cos(theta), 0}, {0, 0, 1}} and a translation by L units ... | [
"data structures",
"geometry"
] | 2,500 | #include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
#define pb... |
618 | F | Double Knapsack | You are given two multisets $A$ and $B$. Each multiset has exactly $n$ integers each between $1$ and $n$ inclusive. Multisets may contain multiple copies of the same number.
You would like to find a nonempty subset of $A$ and a nonempty subset of $B$ such that the sum of elements in these subsets are equal. Subsets ar... | Let's replace "set" with "array", and "subset" with "consecutive subarray". Let $a_{i}$ denote the sum of the first $i$ elements of $A$ and $b_{j}$ be the sum of the first $j$ elements of $B$. WLOG, let's assume $a_{n} \le b_{n}$. For each $a_{i}$, we can find the largest $j$ such that $b_{j} \le a_{i}$. Then, the ... | [
"constructive algorithms",
"two pointers"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
void printAns(int i, int j) {
printf("%d\n", j-i);
for (int k = i+1; k <= j; k++) {
if (k != i+1) printf(" ");
printf("%d", k+1);
}
printf("\n");
}
void solve(int n, int x[], int y[], bool swap) {
long long xs = 0, ys = 0;
int j... |
618 | G | Combining Slimes | Your friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value $1$ and $2$, and you decide to invent a game using these slimes.
You initialize a row with $n$ empty spaces. You also choose a number $p$ to be used in the game. Then, you will perform the following steps whi... | The probability that we form a slime with value $i$ roughly satisfies the recurrence p(i) = p(i-1)^2, where p(1) and p(2) are given as base cases, where they are at most 999999999/1000000000. Thus, for i bigger than 50, p(i) will be extremely small (about 1e-300), so we can ignore values bigger than 50. Let a[k][i] be ... | [
"dp",
"math",
"matrices",
"probabilities"
] | 3,300 | import java.io.*;
import java.util.*;
public class SlimeCombiningLinear {
private static InputReader in;
private static PrintWriter out;
public static double EPS = 1e-15;
public static int maxp = 50;
public static void main (String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(Sy... |
620 | A | Professor GukiZ's Robot | Professor GukiZ makes a new robot. The robot are in the point with coordinates $(x_{1}, y_{1})$ and should go to the point $(x_{2}, y_{2})$. In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the $8$ directions. Find the minim... | Easy to see that the answer is $max(|x_{1} - x_{2}|, |y_{1} - y_{2}|)$. Complexity: $O(1)$. | [
"implementation",
"math"
] | 800 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
620 | B | Grandfather Dovlet’s calculator | Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display).
Max starts to type all the values from $a$ to $b$. After typing each number Max resets the calculator. Find the tota... | Let's simply iterate over all the values from $a$ to $b$ and add to the answer the number of segments of the current value $x$. To count the number of segments we should iterate over all the digits of the number $x$ and add to the answer the number of segments of the current digit $d$. These values can be calculated by... | [
"implementation"
] | 1,000 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
620 | C | Pearls in a Row | There are $n$ pearls in a row. Let's enumerate them with integers from $1$ to $n$ from the left to the right. The pearl number $i$ has the type $a_{i}$.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maxim... | Let's solve the problem greedily. Let's make the first segment by adding elements until the segment will be good. After that let's make the second segment in the same way and so on. If we couldn't make any good segment then the answer is $- 1$. Otherwise let's add all uncovered elements at the end to the last segment. ... | [
"greedy"
] | 1,500 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
620 | D | Professor GukiZ and Two Arrays | Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a $s_{a}$ as close as possible to the sum of the elements in the array b $s_{b}$. So he wants to minimize the value $v = |s_{a} - s_{b}|$.
In one operation professor can swap some element from the array a ... | We can process the cases of zero or one swap in $O(nm)$ time. Consider the case with two swaps. Note we can assume that two swaps will lead to move two elements from $a$ to $b$ and vice versa (in other case it is similar to the case with one swap). Let's iterate over all the pairs of the values in $a$ and store them in... | [
"binary search",
"two pointers"
] | 2,200 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
620 | E | New Year Tree | The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with $n$ vertices and root in the vertex $1$.
You should process the queries of the two types:
- Cha... | Let's run dfs on the tree and write out the vertices in order of their visisiting by dfs (that permutation is called Euler walk). Easy to see that subtree of any vertex is a subsegment of that permutation. Note that the number of different colours is $60$, so we can store the set of colours just as mask of binary bits ... | [
"bitmasks",
"data structures",
"trees"
] | 2,100 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
620 | F | Xors on Segments | You are given an array with $n$ integers $a_{i}$ and $m$ queries. Each query is described by two integers $(l_{j}, r_{j})$.
Let's define the function $f(u,v)=u\oplus(u+1)\oplus.\ldots\oplus v$. The function is defined for only $u ≤ v$.
For each query print the maximal value of the function $f(a_{x}, a_{y})$ over all ... | We gave bad constraints to this problem so some participants solved it in $O(n^{2} + m)$ time. Note that $f(x,y)=f(0,x-1)\oplus f(0,y)$. The values $f(0, x)$ can be simply precomputed. Also you can notice that the value $f(0, x)$ is equal to $x, 1, x + 1, 0$ depending on the value $x$ modulo $4$. Let's use Mo's algorit... | [
"data structures",
"strings",
"trees"
] | 2,800 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
621 | A | Wet Shark and Odd and Even | Today, Wet Shark is given $n$ integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by $2$) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the $n$ integers, the sum is an even integer $0$. | First, if the sum of all the numbers is already even, then we do nothing. Otherwise, we remove the smallest odd number. Since, if the sum is odd, we need to remove a number with the same parity to make the sum even. Notice it's always bad to remove more odd numbers, and it does nothing to remove even numbers. | [
"implementation"
] | 900 | null |
621 | B | Wet Shark and Bishops | Today, Wet Shark is given $n$ bishops on a $1000$ by $1000$ grid. Both rows and columns of the grid are numbered from $1$ to $1000$. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this ... | Let's start with two bishops (x1, y1) and (x2, y2). Notice that if (x1, y1) attacks (x2, y2), either x1 + y1 == x2 + y2 OR x1 - y1 == x2 - y2. So, for each bishop (x, y), we will store x + y in one map and x - y in another map. | [
"combinatorics",
"implementation"
] | 1,300 | null |
621 | C | Wet Shark and Flowers | There are $n$ sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks $i$ and $i + 1$ are neighbours for all $i$ from $1$ to $n - 1$. Sharks $n$ and $1$ are neighbours too.
Each shark will grow some number of flowers $s_{i}$. For $i$-th shark value $s_{i}$ is random integer equip... | Let $f(x)$ be the probability that the product of the number of flowers of sharks $x$ and $(x+1)\mod n$ is divisible by $p$. We want the expected value of the number of pairs of neighbouring sharks whose flower numbers are divisible by $p$. From linearity of expectation, this is equal to the probabilities that each pai... | [
"combinatorics",
"math",
"number theory",
"probabilities"
] | 1,700 | null |
621 | D | Rat Kwesh and Cheese | Wet Shark asked Rat Kwesh to generate three positive real numbers $x$, $y$ and $z$, from $0.1$ to $200.0$, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have \textbf{exactly one} digit after the decimal point.
Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat... | The tricky Rat Kwesh has finally made an appearance; it is time to prepare for some tricks. But truly, we didn't expect it to be so hard for competitors though. Especially the part about taking log of a negative number. We need a way to deal with $x^{yz}$ and $x^{yz}$. We cannot directly compare them, $200^{200200}$ is... | [
"brute force",
"constructive algorithms",
"math"
] | 2,400 | null |
621 | E | Wet Shark and Blocks | There are $b$ blocks of digits. Each one consisting of the same $n$ digits, which are given to you in the input. Wet Shark must choose \textbf{exactly one} digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit $1$ from the first block and digit $2... | First, let us build an X by X matrix. We will be applying matrix exponentiation on this matrix. For each modulo value T from 0 to X - 1, and each value in the array with index i between 1 and n, we will do: matrix[T][(10 * T + arr[i]) % X]++. This is because, notice that for each block we allow one more way to go betwe... | [
"dp",
"matrices"
] | 2,000 | null |
622 | A | Infinite Sequence | Consider the infinite sequence of integers: $1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5...$. The sequence is built in the following way: at first the number $1$ is written out, then the numbers from $1$ to $2$, then the numbers from $1$ to $3$, then the numbers from $1$ to $4$ and so on. Note that the sequence contain... | Let's decrease $n$ by one. Now let's determine the block with the $n$-th number. To do that let's at first subtract $1$ from $n$, then subtract $2$, then subtract $3$ and so on until we got negative $n$. The number of subtractions will be the number of the block and the position in the block will be the last nonnegativ... | [
"implementation",
"math"
] | 1,000 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
622 | B | The Time | You are given the current time in $24$-hour format hh:mm. Find and print the time after $a$ minutes.
Note that you should find only the time after $a$ minutes, see the examples to clarify the problem statement.
You can read more about $24$-hour format here https://en.wikipedia.org/wiki/24-hour_clock. | In this problem we can simply increase $a$ times the current time by one minute (after each increasing we should check the hours and the minutes for overflow). Another solution is to use the next formulas as the answer: $x=h\cdot60+m+a,\ h^{\prime}=\left[{\frac{x}{60}}\right]\ m o d\ 24,m^{\prime}=x\ m o d\ 60$. Comple... | [
"implementation"
] | 900 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
622 | C | Not Equal on a Segment | You are given array $a$ with $n$ integers and $m$ queries. The $i$-th query is given with three integers $l_{i}, r_{i}, x_{i}$.
For the $i$-th query find any position $p_{i}$ ($l_{i} ≤ p_{i} ≤ r_{i}$) so that $a_{pi} ≠ x_{i}$. | This problem can be solved differently. For example you can use some data structures or sqrt-decomposition technique. But it is not required. We expected the following simple solution from the participants. Let's preprocess the following values $p_{i}$ - the position of the first element to the left from the $i$-th ele... | [
"data structures",
"implementation"
] | 1,700 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
622 | D | Optimal Number Permutation | You have array $a$ that contains all integers from $1$ to $n$ twice. You can arbitrary permute any numbers in $a$.
Let number $i$ be in positions $x_{i}, y_{i}$ ($x_{i} < y_{i}$) in the permuted array $a$. Let's define the value $d_{i} = y_{i} - x_{i}$ — the distance between the positions of the number $i$. Permute th... | Let's build the answer with the sum equal to zero. Let $n$ be even. Let's place odd numbers in the first half of the array: the number $1$ in the positions $1$ and $n$, the number $3$ in the positions $2$ and $n - 1$ and so on. Similarly let's place even numbers in the second half: the number $2$ in the position $n + 1... | [
"constructive algorithms"
] | 1,900 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
622 | E | Ants in Leaves | Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.
You are given a tree with $n$ vertices and a root in the vertex $1$. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were i... | Easy to see that the answer is equal to the answer over all sons of the root plus one. Now let's solve the problem independently for each son $v$ of the root. Let $z$ be the array of the depths of all leaves in the subtree of the vertex $v$. Let's sort $z$. Statement 1: it's profitable to lift the leaves in order of th... | [
"dfs and similar",
"greedy",
"sortings",
"trees"
] | 2,200 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
622 | F | The Sum of the k-th Powers | There are well-known formulas: $\sum_{i=1}^{n}i=1+2+\cdot\cdot\cdot+n={\frac{n(n+1)}{2}}$, $\sum_{i=1}^{n}i^{2}=1^{2}+2^{2}+\cdot\cdot\cdot+n^{2}={\frac{n(2n+1)(n+1)}{6}}$, $\sum_{i=1}^{n}i^{3}=1^{3}+2^{3}+\cdot\cdot\cdot+n^{3}=\left({\frac{n(n+1)}{2}}\right)^{2}$. Also mathematicians found similar formulas for higher ... | Statement: the function of the sum is a polynomial of degree $k + 1$ over variable $n$. This statement can be proved by induction (to make step you should take the derivative). Denote $P_{x}$ the value of the sum for $n = x$. We can easily calculate the values of $P_{x}$ for $x$ from $0$ to $k + 1$ in $O(klogk)$ time. ... | [
"math"
] | 2,600 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
623 | A | Graph and String | One day student Vasya was sitting on a lecture and mentioned a string $s_{1}s_{2}... s_{n}$, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph $G$ with the following properties:
- $G$ has exactly $n$ vertices, numb... | Note that all vertices "b" are connected with all other vertices in the graph. Find all such vertices and mark them as "b". Now we need to find any unlabeled vertex $V$, mark it with "a" character. Unlabeled vertices connected with $V$ should be also labeled as "a". All other vertices we can label as "c" Finally we nee... | [
"constructive algorithms",
"graphs"
] | 1,800 | null |
623 | B | Array GCD | You are given array $a_{i}$ of length $n$. You may consecutively apply two operations to this array:
- remove some subsegment (continuous subsequence) of length $m < n$ and pay for it $m·a$ coins;
- change some elements of the array by at most $1$, and pay $b$ coins for each change.
Please note that each of operation... | At least one of ends ($a_{1}$ or $a_{n}$) is changed by at most 1. It means that if gcd > 1 then it divides on of prime divisors of either $a_{1} - 1$, $a_{1}$, $a_{1} + 1$, $a_{n} - 1$, $a_{n}$ or $a_{n} + 1$. We will iterate over these primes. Suppose prime $p$ is fixed. For each number we know that it's either divis... | [
"dp",
"greedy",
"number theory"
] | 2,300 | null |
623 | C | Electric Charges | Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals.
A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: a... | First of all consider cases where all points are projected to the same axis. (In that case answer is difference between maximum and minimum of this coordinate). Now consider leftmost and rightmost points among projected to $x$ axis. Let $x_{L}$ and $x_{R}$ are their $x$-coordinates. Notice that points with x-coordinate... | [
"binary search",
"dp"
] | 2,900 | null |
623 | D | Birthday | A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. $n$ friends came by, and after a typical party they decided to play blind man's buff.
The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several ... | Let's denote $q_{i} = 1 - p_{i}$. Main idea: first of all guess each friend once, then maximize probability to end game on current step. Let's simulate first 300000 steps, and calculate $\textstyle\sum t\cdot(P r(t)-P r(t-1))$. $P r(t)=\prod(1-q_{i}^{k_{i}})$, where $k_{i}$ - how many times we called $i$-th friend ($\t... | [
"greedy",
"math",
"probabilities"
] | 2,700 | null |
623 | E | Transforming Sequence | Let's define the transformation $P$ of a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ as $b_{1}, b_{2}, ..., b_{n}$, where $b_{i} = a_{1} | a_{2} | ... | a_{i}$ for all $i = 1, 2, ..., n$, where $|$ is the bitwise OR operation.
Vasya consequently applies the transformation $P$ to all sequences of length $n$ consist... | First observation is that if the sequence of prefix xors is strictly increasing, than on each step $a_{i}$ has at least one new bit comparing to the previous elements. So, since there are overall $k$ bits, the length of the sequence can't be more than $k$. So, if $n > k$, the answer is 0. Let's firstly solve the task w... | [
"combinatorics",
"dp",
"fft",
"math"
] | 3,300 | null |
624 | A | Save Luke | Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates $0$ and $L$, and they move towards each othe... | Width of free space is decreasing by $v_{1} + v_{2}$ per second. It means that it'll decrease from $L$ to $d$ in $t={\frac{L-d}{v_{1}+v_{2}}}$ seconds. The moment when width gets a value of $d$ is the last when Luke is alive so $t$ is the answer. | [
"math"
] | 800 | null |
624 | B | Making a String | You are given an alphabet consisting of $n$ letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
- the $i$-th letter occurs in the string no more than $a_{i}$ times;
- the number of occurrences of each letter in the string must be \textbf{distinct} for a... | Sort array in descending order. Iterate over all letters, First letter is added $c_{1} = a_{1}$ times, each other letter is added $c_{i} = min(a_{i}, c_{i - 1})$. Don't forget that if some letter is not added at all, then all next letters are not added too. | [
"greedy",
"sortings"
] | 1,100 | null |
625 | A | Guest From the Past | Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.
Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas... | If we have at least $b$ money then cost of one glass bottle is $b - c$. This means that if $a \le b - c$ then we don't need to buy glass bottles, only plastic ones, and the answer will be $\left\lfloor{\frac{n}{a}}\right\rfloor$. Otherwise we need to buy glass bottles while we can. So, if we have at least $b$ money, ... | [
"implementation",
"math"
] | 1,700 | null |
625 | B | War of the Corporations | A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | Lets find leftmost occurrence of the second word in the first one. We need to add # to remove this occurrence, so where we would like to put it? Instead of the last symbol of this occurrence to remove as many others as we can. After that we will continue this operation after the new # symbol. Simplest implementation of... | [
"constructive algorithms",
"greedy",
"strings"
] | 1,200 | null |
625 | C | K-special Tables | People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of $k$-special tables. In case you f... | Lets fill our table row by row greedily. We want to have maximal possible number on k-th place in the first row. After it we need at least $n - k$ numbers greater than ours, so its maximum value is $n^{2} - (n - k)$. If we select it then we are fixing all numbers after column $k$ in the first row from $n^{2} - (n - k)$... | [
"constructive algorithms",
"implementation"
] | 1,300 | null |
625 | D | Finals in arithmetic | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.
Let's denote a flip operation of an integer as follows: number is considered... | Lets say that input has length of $n$ digits, then size of answer can be $n$ if we didn't carry 1 to the left out of addition, and $n - 1$ otherwise. Lets fix length $m$ of our answer and denote $i$-th number in the representation as $a_{i}$. Then we know $(a_{1}+a_{m})\mathrm{~mod~}10$ from the rightmost digit of the ... | [
"constructive algorithms",
"implementation",
"math"
] | 2,400 | null |
625 | E | Frog Fights | Ostap Bender recently visited frog farm and was inspired to create his own frog game.
Number of frogs are places on a cyclic gameboard, divided into $m$ cells. Cells are numbered from $1$ to $m$, but the board is cyclic, so cell number $1$ goes right after the cell number $m$ in the direction of movement. $i$-th frog ... | We want to efficiently simulate the process from the problem statement. Lets have a data structure with times of key events that could've happened during simulation (some frog removed other frog from the board). Lets remove earliest event from our data structure and apply it to the board, make a critical jump. After th... | [
"data structures",
"greedy"
] | 2,800 | null |
626 | A | Robot Sequence | Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of $n$ commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the s... | We can simulate Calvin's path on each substring, and check if he returns to the origin. Runtime: $O(n^{3})$ | [
"brute force",
"implementation"
] | 1,000 | null |
626 | B | Cards | Catherine has a deck of $n$ cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:
- take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color;
- take any two (not necessarily adjacen... | Note that if we have exactly one card of each color, we can always make all three options (by symmetry). Thus, if we have at least one of each color, or at least two of each of two colors, we can make all three options. The remaining cases are: if we only have one color, that's the only possible final card; if we have ... | [
"constructive algorithms",
"dp",
"math"
] | 1,300 | null |
626 | C | Block Towers | Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. $n$ of the students use pieces made of two blocks and $m$ of the students use pieces made of three blocks.
The students don’t want to use too many blocks, but they also want to be ... | There are a variety of ways to do this problem. Here is one way: if the answer is $X$, there must be at least $n$ multiples of $2$ below $X$, at least $m$ multiples of $3$ below $X$, and at least $n + m$ multiples of $2$ or $3$ below $X$. These conditions are actually sufficient, so we need to find the smallest $X$ suc... | [
"brute force",
"greedy",
"math",
"number theory"
] | 1,600 | null |
626 | D | Jerry's Protest | Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing $n$ balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to... | We do this algorithm in two phases: first, we compute the probability distribution of the difference between the winner and loser of each round. This takes $O(n^{2})$ time. Then, we can iterate over the 2 differences which Andrew wins by and compute the probability that Jerry has a greater total using with suffix sums.... | [
"brute force",
"combinatorics",
"dp",
"probabilities"
] | 1,800 | null |
626 | E | Simple Skewness | Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of $n$ (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.
The mean of a collection is the average of its elements. The median of a col... | We can show that any subset with maximal simple skewness should have odd size (otherwise we drop the larger middle element: this decreases the median by more than it decreases the mean, assuming the mean is larger than the median). Let's fix the median at $x_{i}$ (in the sorted list), and set the size of the set to $2j... | [
"binary search",
"math",
"ternary search"
] | 2,400 | null |
626 | F | Group Projects | There are $n$ students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the $i$-th student $a_{i}$ minutes to finish his/her independent piece.
If students work at differe... | This is a dynamic programming problem. Notice that the total imbalance of the groups only depends on which students are the maximum in each group and which are the minimum in each group. We thus can think of groups as intervals bounded by the minimum and maximum student. Moreover, the total imbalance is the sum over al... | [
"dp"
] | 2,400 | null |
626 | G | Raffles | Johnny is at a carnival which has $n$ raffles. Raffle $i$ has a prize with value $p_{i}$. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket ... | First, note that the marginal utility of each additional ticket in a single raffle is decreasing. Thus, to solve the initial state, we can use a heap data structure to store the optimal raffles. Now, after each update, we can show that the distribution should not change by much. In particular, after one ticket is added... | [
"data structures",
"dp",
"greedy",
"math"
] | 3,100 | null |
627 | A | XOR Equation | Two \textbf{positive} integers $a$ and $b$ have a sum of $s$ and a bitwise XOR of $x$. How many possible values are there for the ordered pair $(a, b)$? | For any two integers $a$ and $b$, we have $s=a+b=(a\oplus b)+(a\aleph b)*2$, where $a\oplus b$ is the xor and $a&b$ is the bitwise AND. This is because $\mathbb{C}$ is non-carrying binary addition. Thus, we can find $a&b = (s - x) / 2$ (if this is not an integer, there are no solutions). Now, for each bit, we have $4$ ... | [
"dp",
"math"
] | 1,700 | null |
627 | B | Factory Repairs | A factory produces thimbles in bulk. Typically, it can produce up to $a$ thimbles a day. However, some of the machinery is defective, so it can currently only produce $b$ thimbles each day. The factory intends to choose a $k$-day period to do maintenance and construction; it cannot produce any thimbles during this time... | Using two binary-indexed trees, we can maintain the prefix and suffix sums of the amounts we can produce with maximum production rates of $B$ and $A$, respectively. Then we can just query the binary-indexed trees to find the maximum possible production given the start and end of the repairs. Runtime: $O(q\log(n))$. | [
"data structures"
] | 1,700 | null |
627 | C | Package Delivery | Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point $0$ on a number line, and the district center is located at the point $d$.
Johnny's truck has a gas tank that holds exactly $n$ liters, and his tank is initially full. As he drives, the truck con... | We solve this with a greedy algorithm: for each gas station, we fill our tank to $min(n, d)$ liters of gasoline, where $d$ is the distance to the next gas station with cheaper (or equal) gas. This is optimal, as, if we can make it to a station with cheaper gas without buying expensive gas, we should (and fill up our ta... | [
"data structures",
"divide and conquer",
"greedy"
] | 2,200 | null |
627 | D | Preorder Test | For his computer science class, Jacob builds a model tree with sticks and balls containing $n$ nodes in the shape of a tree. Jacob has spent $a_{i}$ minutes building the $i$-th ball in the tree.
Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough... | We binary search on the answer, so we need to answer queries of the following form: is the a depth-first search traversal such that the first $k$ vertices all have value at least $v$? We can answer this with a greedy tree-DP: for each subtree, we compute whether or not all its vertices have value at least $v$, and if n... | [
"binary search",
"dfs and similar",
"dp",
"graphs",
"greedy",
"trees"
] | 2,600 | null |
627 | E | Orchestra | Paul is at the orchestra. The string section is arranged in an $r × c$ rectangular grid and is filled with violinists with the exception of $n$ violists. Paul really likes violas, so he would like to take a picture including at least $k$ of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. ... | We can think of a rectangle in the grid as a pair of an $(xlo, xhi)$ interval and a $(ylo, yhi)$ interval. Suppose we fix the $x$-interval and want to determine the number of corresponding $y$ intervals which create rectangles containing at least $k$ violists. Given a sorted list of the $y$-coordinates of all violists ... | [
"two pointers"
] | 3,000 | null |
627 | F | Island Puzzle | A remote island chain contains $n$ islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of $n - 1$ bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island... | First, if we never move the empty pedestal through any cycle, then moving the empty pedestal to and from any given position cannot change the location of the statues, as performing a move in the opposite direction as the previous undoes the previous move. Thus, in our graph with one cycle, we can only do the following ... | [
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 3,400 | null |
628 | A | Tennis Tournament | A tennis tournament with $n$ participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.
The tournament takes place in the following way (below, $m$ is the number of the participants of the current round):
- let $k$ be the maximal power of the number $2$... | Here you can simply model the process. Or you can note that after each match some player drops out. In total $n - 1$ players will drop out. So the first answer is $(n - 1) * (2b + 1)$. Obviously the second answer is $np$. Complexity: $O(log^{2}n)$, $O(logn)$ or $O(1)$ depends on the realization. | [
"implementation",
"math"
] | 1,000 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
628 | B | New Skateboard | Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which... | The key observation is that the number is divisible by $4$ if and only if its last two digits forms a number divisible by $4$. So to calculate the answer at first we should count the substrings of length one. Now let's consider pairs of consecutive digits. If they forms a two digit number that is divisible by $4$ we sh... | [
"dp"
] | 1,300 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
628 | C | Bear and String Distance | Limak is a little polar bear. He likes \textbf{nice} strings — strings of length $n$, consisting of lowercase English letters only.
The distance between two letters is defined as the difference between their positions in the alphabet. For example, $\operatorname{dist}(\mathbf{c},\mathbf{e})=\operatorname{dist}(\mathbf... | There is no solution if the given required distance is too big. Let's think what is the maximum possible distance for the given string $s$. Or the more useful thing - how to construct a string $s'$ to maximize the distance? We can treat each letter separately and replace it with the most distant letter. For example, we... | [
"greedy",
"strings"
] | 1,300 | "// Bear and String Distance, by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 1e6 + 5;\nchar s[nax];\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tscanf(\"%s\", s);\n\tfor(int i = 0; i < n; ++i) {\n\t\t// we want to change s[i]\n\t\tchar best_letter = s[i]; // by default we d... |
628 | D | Magic Numbers | Consider the decimal presentation of an integer. Let's call a number d-magic if digit $d$ appears in decimal presentation of the number on even positions and nowhere else.
For example, the numbers $1727374$, $17$, $1$ are 7-magic but $77$, $7$, $123$, $34$, $71$ are not 7-magic. On the other hand the number $7$ is 0-m... | Denote the answer to the problem $f(a, b)$. Note that $f(a, b) = f(0, b) - f(0, a - 1)$ or what is the same $f(a, b) = f(0, b) - f(0, a) + g(a)$, where $g(a)$ equals to one if $a$ is a magic number, otherwise $g(a)$ equals to zero. Let's solve the problem for the segment $[0, n]$. Here is described the standard techniq... | [
"dp"
] | 2,200 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
628 | E | Zbazi in Zeydabad | A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).
The country Zeydabad is a rectangular table consisting of $n$ rows and $m$ columns. Each cell on the country is either 'z' or '.'.
The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern"s in the country. A ... | The problem was suggested by Ali Ahmadi Kuzey. Let's precalculate the values $zl_{ij}, zr_{ij}, zld_{ij}$ - the maximal number of letters 'z' to the left, to the right and to the left-down from the position $(i, j)$. It's easy to do in $O(nm)$ time. Let's fix some cell $(i, j)$. Consider the value $c = min(zl_{ij}, zld... | [
"data structures",
"implementation"
] | 2,300 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#d... |
628 | F | Bear and Fair Set | Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.
It's a well-known fact that Limak, as e... | At the beginning, to make things simpler, we should add a query (hint) with $upTo = b, quantity = n$, and then sort queries by $upTo$. Sorted queries (hints) divide interval $[1, b]$ into $q$ disjoint intervals. For each interval we know how many elements should be there. Let's build a graph and find a max flow there. ... | [
"flows",
"graphs"
] | 2,500 | "// Bear and Fair Set, by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int K = 5;\n\nvoid NO() {\n\tputs(\"unfair\");\n\texit(0);\n}\n\nint main() {\n\tint n, b, q;\n\tscanf(\"%d%d%d\", &n, &b, &q);\n\tvector<pair<int,int>> w;\n\tw.push_back(make_pair(b, n));\n\twhile(q--) {\n\t\tint a, b;\n\t\tscan... |
629 | A | Far Relative’s Birthday Cake | Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a $n × n$ square consisting of equal squares with side length $1$. Each square is either empty or consists of a single chocolate. They bought the cake and randomly start... | Consider that we have $row_{i}$ chocolates in the $i'th$ row and $col_{i}$ chocolates in the $i'th$ column. The answer to the problem would be: $\sum_{i=1}^{n}{\binom{r o w_{i}}{2}}+{\binom{c o l_{i}}{2}}$. It is obvious that every pair would be calculated exactly once (as we have no more than one chocolate in the same... | [
"brute force",
"combinatorics",
"constructive algorithms",
"implementation"
] | 800 | // TODO : Choose an Appropriate Name!!
// We're not here because we're free. We're here because we are not free.
// The Matrix Reloaded (2003)
#include <bits/stdc++.h>
using namespace std;
#define MohammadAmin main()
#define mpair make_pair
#define endl "
"
#define c_false ios_base::sync_with_stdio(false... |
629 | B | Far Relative’s Problem | Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has $n$ friends and each of them can come to the party in a specific range of days of the year from $a_{i}$ to $b_{i}$. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird ... | Consider that we have $boy_{i}$ males in the $i'th$ day of the year and $girl_{i}$ females in the $i'th$ day of the year. These arrays can be filled easily when you are reading the input (See the code). Then for the $i'th$ day of the year, we could have $2$ * $min$($boy_{i}$ , $girl_{i}$) people which could come to the... | [
"brute force"
] | 1,100 | // TODO : Choose an Appropriate Name!!
// We're not here because we're free. We're here because we are not free.
// The Matrix Reloaded (2003)
#include <bits/stdc++.h>
using namespace std;
#define MohammadAmin main()
#define mpair make_pair
#define endl "
"
#define c_false ios_base::sync_with_stdio(false... |
629 | C | Famil Door and Brackets | As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length $n$ more than any other strings!
The sequence of round brackets is called valid if and only if:
- ... | This problem can be solved with dynamic programming: $1$. Calculate $dp_{i, j}$ : How many sequences of brackets of length $i$ has balance $j$ and intermediate balance never goes below zero (They form a prefix of a valid sequence of brackets). $2$. For the given sequence of length $n$ calculate the resulting balance $a... | [
"dp",
"strings"
] | 2,000 | // TODO : Choose an Appropriate Name!!
// We're not here because we're free. We're here because we are not free.
// The Matrix Reloaded (2003)
#include <bits/stdc++.h>
using namespace std;
#define MohammadAmin main()
#define mpair make_pair
#define endl "
"
#define c_false ios_base::sync_with_stdio(false... |
629 | D | Babaei and Birthday Cake | As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.
Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has $n$ simple cakes and he is going to make a special ... | First of all, we calculate the volume of each cake: $v_{i}$ = $ \pi \times h_{i} \times r_{i}^{2}$. Now consider the sequence $v_{1}$, $v_{2}$, $v_{3}$, ..., $v_{n}$ : The answer to the problem is the maximum sum of elements between all increasing sub-sequences of this sequence. How do we solve this? First to get ... | [
"data structures",
"dp"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define MohammadAmin main()
#define mpair make_pair
#define endl "
"
#define c_false ios_base::sync_with_stdio(false); cin.tie(0)
#define pushb push_back
#define pushf push_front
#define popb pop_back
#define popf pop_front
#define sz(a) (int)(a).size()
#define all(a) (a)... |
629 | E | Famil Door and Roads | Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are $n$ intersections in the city connected by $n - 1$ bidirectional roads.
There are $m$ friends of Famil Door living in the city. The $i$-th friend lives at the intersection $u_{i}$ and works at the i... | First of all, we assume that the tree is rooted! For this problem, first we need to compute some values for each vertex $u$: $qd_{u}$ and $qu_{u}$, $cnt_{u}$ , $par_{u, i}$ and $h_{u}$. $qd_{u}$ equals to the expected value of length of paths which start from vertex $u$, and ends in $u$'s subtree and also has length at... | [
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"probabilities",
"trees"
] | 2,300 | // TODO : Choose an Appropriate Name!!
// We're not here because we're free. We're here because we are not free.
// The Matrix Reloaded (2003)
#include <bits/stdc++.h>
using namespace std;
#define MohammadAmin main()
#define mpair make_pair
#define endl "
"
#define c_false ios_base::sync_with_stdio(false... |
630 | A | Again Twenty Five! | The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number $5$ to the power of $n$ and get last two digits of the number. Yes, of course, $n$ can be rather big, and one cannot find the power ... | The problem of getting the last two digits is equivalent to the problem of getting the number modulo $100$. So we need to calculate $\scriptstyle{{\hat{\mathbb{P}}}^{n}}\mathrm{~IIDd}\mathrm{~}|\mathbb{O}$. According to the rules of modular arithmetic $(a\cdot b)\,\,\,\,\mathrm{mod}\,\,c=((a\,\,\,\mathrm{mod}\,\,c)\cdo... | [
"number theory"
] | 800 | null |
630 | B | Moore's Law | The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.
Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately ev... | Every second the number is multiplied by $1.000000011$. Multiplication several times to the same number is equivalent to exponentiation. So the formula is $n \cdot 1.000000011^{t}$ ($1.000000011$ raised to the power of $t$ and then multiplied to $n$). In a program one should not use a loop to calculate power as it is t... | [
"math"
] | 1,200 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.