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 ⌀ |
|---|---|---|---|---|---|---|---|
583 | B | Robot's Task | Robot Doc is located in the hall, with $n$ computers stand in a line, numbered from left to right from $1$ to $n$. Each computer contains \textbf{exactly one} piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the $i$-th of them, the robot nee... | It is always optimal to pass all the computers in the row, starting from $1$-st to $n$-th, then from $n$-th to first, then again from first to $n$-th, etc. and collecting the information parts as possible, while not all of them are collected. Such way gives robot maximal use of every direction change. $O(n^{2})$ soluti... | [
"greedy",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const int N = 5000;
int n, a[N];
int main() {
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
int s = 0, res = 0;
while (true) {
for (int i = 0; i < n; ++i)
if (a[i] <= s) a[i] = n + 1, s++;
if (s == n) break;
res... |
584 | A | Olesya and Rodion | Olesya loves numbers consisting of $n$ digits, and Rodion only likes numbers that are divisible by $t$. Find some number that satisfies both of them.
Your task is: given the $n$ and $t$ print an integer strictly larger than zero consisting of $n$ digits that is divisible by $t$. If such number doesn't exist, print $ -... | Two cases: $t = 10$ and $t \neq 10$. If $t = 10$ then there are two cases again :). If $n = 1$ then answer is $- 1$ (because there is not any digit divisible by $t$). If $n > 1$, then answer, for example, is '1111...110' (contains $n - 1$ ones). If $t < 10$ then answer, for example, is 'tttttttt' (it, obviously, divi... | [
"math"
] | 1,000 | null |
584 | B | Kolya and Tanya | Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are $3n$ gnomes sitting in a circle. Each gnome can have from $1$ to $3$ coins. Let's number the places in the order they occur in ... | The number of ways to choose $a_{i}$ (without any conditions) - $3^{3n}$. Let $A$ be the number of ways to choose $a_{i}$ with condition that in every triangle gnomes have $6$ coins. Then answer is $3^{3n} - A$. Note that we can separate all gnomes on n independent triangles ($i$-th triangle contains of $a_{i}$, $a_{i ... | [
"combinatorics"
] | 1,500 | null |
584 | C | Marina and Vasya | Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly $t$ characters. Help Vasya find at least one such string.
More formally, you are given two strings $s_{1}$, $s_{2}$ of length $n$ and number $t$. Let's denote as $f(a, b)$ the number of characters in wh... | Let's find a string that will be equal to $s1$ in $k = n - t$ positions and equal to $s2$ in $k = n - t$ positions. Let's denote $q$ = quantity of $i$ that $s1_{i} = s2_{i}$. If $k \le q$, then let's take $k$ positions such that $s1_{pos} = s2_{pos}$ and put in answer the same symbols. Then put in other $n - k$ posit... | [
"constructive algorithms",
"greedy",
"strings"
] | 1,700 | null |
584 | D | Dima and Lisa | Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an \textbf{odd} numer $n$. Find a set of numbers $p_{i}$ ($1 ≤ i ≤ k$), such that
- ... | There is a fact that the distance between adjacent prime numbers isn't big. For $n = 10^{9}$ maximal distanse is $282$. So let's find maximal prime $p$, such that $p < n - 1$ (we can just decrease n while it's not prime(we can check it in $O({\sqrt{n}})$)). We know that $n - p < 300$. Now we have even (because $n$ and ... | [
"brute force",
"math",
"number theory"
] | 1,800 | null |
584 | E | Anton and Ira | Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.
More formally, we have two permutations, $p$ and $s$ of numbers from $1$ to $n$. We can swap $p_{i}$ a... | We can consider that we pay $2|i - j|$ coins for swap (we can divide answer in the end). Then we can consider that we pay $|i - j|$ coins for moving $p_{i}$ and $|i - j|$ for moving $p_{j}$. So, if $x$ was on position $i$ and then came to position $j$, then we will pay at least $|i - j|$ coins. Then the answer is at le... | [
"constructive algorithms",
"greedy",
"math"
] | 2,300 | null |
585 | A | Gennady the Dentist | Gennady is one of the best child dentists in Berland. Today $n$ children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from $1$ to $n$ in the order they go in the line. Every child is associate... | Let's store for each child his current confidence value and a boolean indicating whether child had left the queue (or visited the dentist office) or not. Then one could easily process children one by one, considering only children who still are in the queue (using boolean array), and changing stored values. Such soluti... | [
"brute force",
"implementation"
] | 1,800 | null |
585 | B | Phillip and Trains | The mobile application store has a new game called "Subway Roller".
The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and $n$ columns. At the beginning of the game the hero is in some cell of the left... | One could consider a graph with vertices corresponding to every $(x, y)$ position. I should notice that train positions for each Phillip position are fully restorable from his $y$ coordinate. Edge between vertices $u$ and $v$ means that we could get from position corresponding to $u$ to position corresponding by $v$ in... | [
"dfs and similar",
"graphs",
"shortest paths"
] | 1,700 | null |
585 | C | Alice, Bob, Oranges and Apples | Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | Firstly, let's understand the process described in problem statement. If one would write a tree of a sum-pairs $(x, y)$ with letters $\mathrm{\boldmath~A~}$ and $\mathbf{\hat{B}}$, he would get the Stern-Brocot tree. Let the number of oranges be enumerator and the number of apples be denumerator of fraction. At every s... | [
"number theory"
] | 2,400 | null |
585 | D | Lizard Era: Beginning | In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has $n$ mandatory quests. To perform each of them, you need to take \textbf{exactly two} companions.
The attitude of each of the companions to the hero is an integer. Initially, the attitud... | To solve the problem we will use meet-in-the-middle approach. For $\textstyle{\left|{\frac{n}{2}}\right|}$ we should consider all $3^{\left[{\frac{n}{2}}\right]}$ variants. Let in some variant approval values of three companions are $a, b, c$ respectively. If we will consider some variant from other half (there are $3^... | [
"meet-in-the-middle"
] | 2,300 | null |
585 | E | Present for Vitalik the Philatelist | Vitalik the philatelist has a birthday today!
As he is a regular customer in a stamp store called 'Robin Bobin', the store management decided to make him a gift.
Vitalik wants to buy one stamp and the store will give him a non-empty set of the remaining stamps, such that the greatest common divisor (GCD) of the price... | Let's calculate the number of subsets with gcd equal to $1$ - value A. Let's do that using principle of inclusions-exclusions: firstly we say that all subsets is good. The total number of subsets is equal to $2^{n}$. Now let's subtract subsets with gcd divisible by $2$. The number of that subsets is equal to $2^{cnt2} ... | [
"combinatorics",
"math",
"number theory"
] | 2,900 | null |
585 | F | Digits of Number Pi | Vasily has recently learned about the amazing properties of number $π$. In one of the articles it has been hypothesized that, whatever the sequence of numbers we have, in some position, this sequence is found among the digits of number $π$. Thus, if you take, for example, the epic novel "War and Peace" of famous Russia... | Consider all substrings of string $s$ with length $\left\lfloor{\frac{d}{2}}\right\rfloor$. Let's add them all to trie data structure, calculate failure links and build automata by digits. We can do that in linear time using Aho-Korasik algorithm. Now to solve the problem we should calculate dp $z_{i, v, b1, b2, b}$. S... | [
"dp",
"implementation",
"strings"
] | 3,200 | null |
586 | A | Alena's Schedule | Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | To solve this problem one should remove all leading and trailing zeroes from array and then calculate the number of ones and number of zeroes neighboured by ones. The sum of this values is the answer for the problem. Complexity: $O(n)$. | [
"implementation"
] | 900 | null |
586 | B | Laurenty and Shop | A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.
The town where Laurenty lives in is not large. The houses in it are located in two rows, $n$ houses in each... | Let's call some path $i$th if we start it by going $i$ times left, then we cross the prospect and go left $n - 1 - i$ times again. Let $d_{i}$ be equal to the time we should wait on traffic lights while following $i$-th path. If we consider any way from the shop to home, it is equal (but reversed) to only path from hom... | [
"implementation"
] | 1,300 | null |
587 | A | Duff and Weight Lifting | Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of $i$-th of them is $2^{wi}$ pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to... | Problem is: you have to find the minimum number of $k$, such there is a sequence $a_{1}, a_{2}, ..., a_{k}$ with condition $2^{a1} + 2^{a2} + ... + 2^{ak} = S = 2^{w1} + 2^{w2} + ... + 2^{w2}$. Obviously, minimum value of $k$ is the number of set bits in binary representation of $S$ (proof is easy, you can prove it as ... | [
"greedy"
] | 1,500 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
587 | B | Duff in Beach | While Duff was resting in the beach, she accidentally found a strange array $b_{0}, b_{1}, ..., b_{l - 1}$ consisting of $l$ positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, $a_{0}, ..., a_{n - 1}$ that $b$ can be build from $a$ with formula: $b_{i} =... | If we fix $x$ and $b_{ix} mod n$, then problem will be solved (because we can then multiply it by the number of valid distinct values of $\textstyle{\left|{\frac{L}{n}}\right|}$). For the problem above, let $dp[i][j]$ be the number of valid subsequences of $b$ where $x = j$ and $\lfloor{\frac{i}{n}}\rfloor=0$ and $\ver... | [
"dp"
] | 2,100 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
587 | C | Duff in the Army | Recently Duff has been a soldier in the army. Malek is her commander.
Their country, Andarz Gu has $n$ cities (numbered from $1$ to $n$) and $n - 1$ bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.
There are also $m$ people living in Andarz Gu (numbered f... | Solution is something like the fourth LCA approach discussed here. For each $1 \le i \le n$ and $0 \le j \le lg(n)$, store the minimum 10 people in the path from city (vertex) $i$ to its $2^{j} - th$ parent in an array. Now everything is needed is: how to merge the array of two paths? You can keep the these 10 ... | [
"data structures",
"trees"
] | 2,200 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
587 | D | Duff in Mafia | Duff is one if the heads of Mafia in her country, Andarz Gu. Andarz Gu has $n$ cities (numbered from 1 to $n$) connected by $m$ bidirectional roads (numbered by $1$ to $m$).
Each road has a destructing time, and a color. $i$-th road connects cities $v_{i}$ and $u_{i}$ and its color is $c_{i}$ and its destructing time ... | Run binary search on the answer ($t$). For checking if answer is less than or equal to $x$ (check(x)): First of all delete all edges with destructing time greater than $x$. Now, if there is more than one pair of edges with the same color connected to a vertex(because we can delete at most one of them), answer is "No". ... | [
"2-sat",
"binary search"
] | 3,100 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
587 | E | Duff as a Queen | Duff is the queen of her country, Andarz Gu. She's a competitive programming fan. That's why, when he saw her minister, Malek, free, she gave her a sequence consisting of $n$ non-negative integers, $a_{1}, a_{2}, ..., a_{n}$ and asked him to perform $q$ queries for her on this sequence.
There are two types of queries:... | Lemma #1: If numbers $b_{1}, b_{2}, ..., b_{k}$ are $k$ Kheshtaks of $a_{1}, ..., a_{n}$, then $b_{1}\oplus b_{2}\oplus\ldots\oplus b_{k}$ is a Kheshtak of $a_{1}, ..., a_{n}$. Proof: For each $1 \le i \le k$, consider $mask_{i}$ is a binary bitmask of length $n$ and its $j - th$ bit shows a subsequence of $a_{1}, ... | [
"data structures"
] | 2,900 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
587 | F | Duff is Mad | Duff is mad at her friends. That's why she sometimes makes Malek to take candy from one of her friends for no reason!
She has $n$ friends. Her $i$-th friend's name is $s_{i}$ (their names are not necessarily unique). $q$ times, she asks Malek to take candy from her friends. She's angry, but also she acts with rules. W... | Use Aho-Corasick. Assume first of all we build the trie of our strings (function t). If $t(v, c) \neq - 1$ it means that there is an edge in the trie outgoing from vertex $v$ written $c$ on it. So, for building Aho-Corasick, consider $f(v)$ = the vertex we go into, in case of failure ($t(v, c) = - 1$). i.e the deepes... | [
"data structures",
"strings"
] | 3,000 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
588 | A | Duff and Meat | Duff is addicted to meat! Malek wants to keep her happy for $n$ days. In order to be happy in $i$-th day, she needs to eat exactly $a_{i}$ kilograms of meat.
There is a big shop uptown and Malek wants to buy meat for her from there. In $i$-th day, they sell meat for $p_{i}$ dollars per kilogram. Malek knows all number... | Idea is a simple greedy, buy needed meat for $i - th$ day when it's cheapest among days $1, 2, ..., n$. So, the pseudo code below will work: ans = 0 price = infinity for i = 1 to n price = min(price, p[i]) ans += price * a[i] Time complexity: ${\mathcal{O}}(n)$ | [
"greedy"
] | 900 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
588 | B | Duff in Love | Duff is in love with lovely numbers! A positive integer $x$ is called lovely if and only if there is no such positive integer $a > 1$ such that $a^{2}$ is a divisor of $x$.
Malek has a number store! In his store, he has only divisors of positive integer $n$ (and he has all of them). As a birthday present, Malek wants ... | Find all prime divisors of $n$. Assume they are $p_{1}, p_{2}, ..., p_{k}$ (in $O({\sqrt{n}})$). If answer is $a$, then we know that for each $1 \le i \le k$, obviously $a$ is not divisible by $p_{i}^{2}$ (and all greater powers of $p_{i}$). So $a \le p_{1} \times p_{2} \times ... \times p_{k}$. And we know... | [
"math"
] | 1,300 | "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) fo... |
590 | A | Median Smoothing | A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi... | We will call the element of a sequence stable, if it doesn't change after applying the algorithm of median smoothing for any number of times. Both ends are stable by the definition of the median smoothing. Also, it is easy to notice, that two equal consecutive elements are both stable. Now we should take a look at how ... | [
"implementation"
] | 1,700 | #include<bits/stdc++.h>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define MC(n,m) memcpy((n),(m),sizeof(n))
#define F first
#define S seco... |
590 | B | Chip 'n Dale Rescue Rangers | A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.
We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at poi... | If the velocity of the dirigible relative to the air is given by the vector $(a_{x}, a_{y})$, while the velocity of the wind is $(b_{x}, b_{y})$, the resulting velocity of the dirigible relative to the plane is $(a_{x} + b_{x}, a_{y} + b_{y})$. The main idea here is that the answer function is monotonous. If the dirigi... | [
"binary search",
"geometry",
"math"
] | 2,100 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define mt make_tuple
#def... |
590 | C | Three States | The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that on... | Affirmation. Suppose we are given an undirected unweighted connected graph and three distinct chosen vertices $u$, $v$, $w$ of this graph. We state that at least one minimum connecting network for these three vertices has the following form: some vertex $c$ is chosen and the resulting network is obtained as a union of ... | [
"dfs and similar",
"graphs",
"shortest paths"
] | 2,200 | //#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <string>
#include <cmath>
#include <cassert>
#include <ctime>
#include <algorithm>
#include <sstream>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <cstdlib>
#include <cstdi... |
590 | D | Top Secret Task | A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The proble... | If $s>{\frac{n(n-1)}{2}}$, than the sum of $k$ minimums is obviously an answer. Let $i_{1} < i_{2} <$ ... $< i_{k}$ be the indices of the elements that will form the answer. Note, that the relative order of the chosen subset will remain the same, as there is no reason to swap two elements that will both be included in ... | [
"dp"
] | 2,300 | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <cassert>
#include <ctime>
#include <string>
#include <queue>
using namespace std;
#ifdef _WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#en... |
590 | E | Birthday | Today is birthday of a Little Dasha — she is now 8 years old! On this occasion, each of her $n$ friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remain... | The given problem actually consists of two separate problems: build the directed graph of substring relation and find the maximum independent set in it. Note, that if the string $s_{2}$ is a substring of some string $s_{1}$, while string $s_{3}$ is a substring of the string $s_{2}$, then $s_{3}$ is a substring of $s_{1... | [
"graph matchings",
"strings"
] | 3,200 | #include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define TRACE(x) cout << #x << " = " << x << endl
#define _ << " _ " <<
typedef long long llint... |
591 | A | Wizards' Duel | Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length $l$. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of $p$ meters per second, and... | Let's start with determining the position of the first collision. Two impulses converge with a speed $p + q$, so the first collision will occur after $\frac{L}{p{\stackrel{\sim}{+}}q}$ seconds. The coordinate of this collision is given by the formula $x_{1}=p\cdot{\frac{L}{p+q}}$. Note, that the distance one impulse pa... | [
"implementation",
"math"
] | 900 | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define ll long long
#define inf 1e9
#define eps 1e-10
#define md
#define N
using namespace std;
int main()
{
double len,a,b;
scanf("%lf%lf%lf",&len,&a,&b);
printf("%lf\n",len*(a/(a+b)));
return 0;
}
|
591 | B | Rebranding | The name of one small but proud corporation consists of $n$ lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slog... | Trivial solution will just emulate the work of all designers, every time considering all characters of the string one by one and replacing all $x_{i}$ with $y_{i}$ and vice versa. This will work in $O(n \cdot m)$ and get TL. First one should note that same characters always end as a same characters, meaning the positio... | [
"implementation",
"strings"
] | 1,200 | #include <bits/stdc++.h>
#define fi first
#define sc second
using namespace std;
typedef pair<int,int> pi;
char s[300009];
char ch[30];
int main(){
int n,m;scanf("%d%d",&n,&m);
scanf("%s",s);
for(int i=0;i<26;i++)ch[i]=i+'a';
for(int i=0;i<m;i++){
char a,b;scanf(" %c %c",&a,&b);
for(... |
592 | A | PawnChess | Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed... | Player A wins if the distance of his nearest pawn to the top of the board is less than or equal to the distance of the Player's B nearest pawn to the bottom of the board (Note that you should only consider pawns that are not blocked by another pawns). | [
"implementation"
] | 1,200 | null |
592 | B | The Monster and the Squirrel | Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices $1, 2, ..., n$ in clockwise order. Then starting from the vertex $1$ she draws a ray in the direction of each other ve... | After drawing the rays from the first vertex $(n - 2)$ triangles are formed. The subsequent rays will generate independently sub-regions in these triangles. Let's analyse the triangle determined by vertices $1, i, i + 1$, after drawing the rays from vertex $i$ and $(i + 1)$ the triangle will be divided into $(n - i) + ... | [
"math"
] | 1,100 | null |
592 | C | The Big Race | Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of $L$ meters today.
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
While w... | Let D be the length of the racetrack, Since both athletes should tie $D\mathrm{\mod\}B=D\mathrm{\mod\}W$. Let $M = lcm(B, W)$, then $D = k \cdot M + r$. None of the athletes should give one step further, therefore $r \le min{B - 1, W - 1, T} = X$. $D$ must be greater than $0$ and less than or equal to $T$ so $- r / M... | [
"math"
] | 1,800 | null |
592 | D | Super M | Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of $n$ cities, connected by $n - 1$ bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to... | Observation 1: Ari should teleport to one of the attacked cities (it doesn't worth going to a city that is not attacked since then she should go to one of the attacked cities) Observation 2: The nodes visited by Ari will determine a sub-tree $T$ of the original tree, this tree is unique and is determined by all the pat... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 2,200 | null |
592 | E | BCPC | BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces.
BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team.
In BSU there ... | Let's represent the reading and writing speeds of the students as points in a plane. Two students $i, j$ are compatible if $ri' \cdot wj' - rj' \cdot wi' > 0$ this equation is identical to the cross product: $(ri', wi') \times (rj', wj') > 0$. Using this fact is easy to see that three students $i, j, k$ are compatibl... | [
"binary search",
"geometry",
"two pointers"
] | 2,700 | null |
593 | A | 2Char | Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi... | For each letter will maintain the total length of words ($cnt1_{ci}$), which found it was alone, and for each pair of letters will maintain the total length of words that contains only them ($cnt2_{ci, cj}$). For each row, count a number of different letters in it. If it is one, then add this letter to the length of th... | [
"brute force",
"implementation"
] | 1,200 | null |
593 | B | Anton and Lines | The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of $n$ lines defined by the equations $y = k_{i}·x + b_{i}$. It was necessary to determine whether there is at least one point of intersection of two of th... | Note that if $a$ s line intersects with the $j$ th in this band, and at $x = x_{1}$ $i$ th line is higher, at $x = x_{2}$ above would be $j$ th line. Sort by $y$ coordinate at $x = x_{1} + eps$, and $x = x_{2} - eps$. Verify that the order of lines in both cases is the same. If there is a line that its index in the for... | [
"geometry",
"sortings"
] | 1,600 | null |
593 | C | Beautiful Function | Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the i... | One of the answers will be the amount of such expressions for each circle in the coordinate $x$ and similarly coordinate $y$: $\lfloor{\frac{x_{i}}{2}}\rfloor\ast(1-a b s(t-i)+a b s(a b s(t-i)-1))$ For $a = 1$, $b = abs(t - i)$, it can be written as $\left\lfloor{\frac{x_{i}}{2}}\right\rfloor*(a-b+a b s(b-a))$ Consider... | [
"constructive algorithms",
"math"
] | 2,200 | null |
593 | D | Happy Tree Party | Bogdan has a birthday today and mom gave him a tree consisting of $n$ vertecies. For every edge of the tree $i$, some number $x_{i}$ was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, $m$ guests consecutively come to Bogdan's party. When the $i... | Consider the problem ignoring the second typed requests. We note that in the column where all the numbers on the edges of $>$ 1 maximum number of assignments to $x=\lfloor{\frac{x}{R_{e}}}\rfloor$ before $x$ will turn into $0$ is not exceeds $64$. Indeed, if all the $R_{v} = 2$, the number of operations can be assessed... | [
"data structures",
"dfs and similar",
"graphs",
"math",
"trees"
] | 2,400 | null |
593 | E | Strange Calculation and Cats | Gosha's universe is a table consisting of $n$ rows and $m$ columns. Both the rows and columns are numbered with consecutive integers starting with $1$. We will use $(r, c)$ to denote a cell located in the row $r$ and column $c$.
Gosha is often invited somewhere. Every time he gets an invitation, he first calculates th... | Learn how to solve the problem for small t. We use standard dynamic $dp_{x, y, t}$ = number of ways to get into the cell (x; y) at time t. Conversion is the sum of all valid ways to get into the cell (x; y) at time t - 1. Note that this dp can be counted by means of the construction of the power matrix. Head of the tra... | [
"dp",
"matrices"
] | 2,400 | null |
594 | A | Warrior and Archer | In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.
V... | Let's sort the points by increasing $x$ coordinate and work with sorted points array next. Let's suppose that after optimal playing points numbered $l$ and $r$ ($l < r$) are left. It's true that the first player didn't ban any of the points numbered $i$ $l < i < r$, otherwise he could change his corresponding move to p... | [
"games"
] | 2,300 | null |
594 | B | Max and Bike | For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.
He knows that this year $n$ competitions will take place. During the $i$-th competition the participant must as quickly as possible complete a ride along a straight... | The main proposition to solve this problem - in the middle of every competition the sensor must be or in the top point of the wheel or in the bottom point of the wheel. To calculate the answer we need to use binary search. If the center of the wheel moved on the distance $c$, then the sensor moved on the distance $c + ... | [
"binary search",
"geometry"
] | 2,500 | null |
594 | C | Edo and Magnets | Edo has got a collection of $n$ refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be \te... | Let's find the centers of every rectangle and multiple them of 2 (to make all coordinates integers).Then we need to by the rectangle door, which contains all dots, but the lengths of the sides of this door must be rounded up to the nearest integers. Now, let's delete the magnets from the door one by one, gradually the ... | [
"brute force",
"greedy",
"implementation",
"two pointers"
] | 2,300 | null |
594 | D | REQ | Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer $φ(n)$ is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number $1$ is coprime to all the positive integers and $φ(1) = 1$.
Now the teacher gave Vovochka ... | To calculate the answer on every query let's use the formula $\varphi(n)=n{\frac{p_{1}-1}{p_{1}}}\cdot{\frac{p_{2}-1}{p_{2}}}\cdot\cdot\cdot\cdot{\frac{p_{k}-1}{p_{k}}}$, where $p_{1}, p_{2}, ..., p_{k}$ - all prime numbers which divided $n$. We make all calculations by the module $10^{9} + 7$ Let's suppose that we sol... | [
"data structures",
"number theory"
] | 2,500 | null |
594 | E | Cutting the Line | You are given a non-empty line $s$ and an integer $k$. The following operation is performed with this line exactly once:
- A line is split into \textbf{at most} $k$ non-empty substrings, i.e. string $s$ is represented as a concatenation of a set of strings $s = t_{1} + t_{2} + ... + t_{m}$, $1 ≤ m ≤ k$.
- Some of stri... | Let's describe the greedy algorithm, which allows to solve the problem for every $k > 2$ for every string $S$. Let's think, that we always reverse some prefix of the string $S$ (may be with length equals to one). Because we want to minimize lexicographically the string it is easy to confirm that we will reverse such a ... | [
"string suffix structures",
"strings"
] | 3,100 | null |
595 | A | Vitaly and Night | One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of $n$ floors and $2·m$ windows on each floor. On each floor there are $m$ flats num... | It was easy realization problem. Let's increase the variable $i$ from 1 to n, and inside let's increase the variable $j$ from 1 to $2 \cdot m$. On every iteration we will increase the variable $j$ on 2. If on current iteration $a[i][j] = '1'$ or $a[i][j + 1] = '1'$ let's increase the answer on one. Asymptotic behavior ... | [
"constructive algorithms",
"implementation"
] | 800 | null |
595 | B | Pasha and Phone | Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly $n$ digits.
Also Pasha has a number $k$ and two sequences of length $n / k$ ($n$ is divisible by $k$) $a_{1}, a_{2}, ..., a_{n / k}$ and $b_{1}, b_{2}, ..., b_{n / k}$. Let's split th... | Let's calculate the answer to every block separately from each other and multiply the answer to the previous blocks to the answer for current block. For the block with length equals to $k$ we can calculate the answer in the following way. Let for this block the number must be divided on $x$ and must not starts with dig... | [
"binary search",
"math"
] | 1,600 | null |
596 | A | Wilbur and Swimming Pool | After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned... | It is a necessary and sufficient condition that we have exactly 2 distinct values for $x$ and $y$. If we have less than 2 distinct values for any variable, then there is no way to know the length of that dimension. If there are at least 3 distinct values for any variable, then that means more than 3 vertices lie on tha... | [
"geometry",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int n;
set<int> a, b;
int value(set<int>& s) {
return (*s.rbegin())-(*s.begin());
}
int main(void) {
cin >> n;
for (int i=0; i<n; i++) {
int x, y;
cin >> x >> y;
a.insert(x);
b.insert(y);
}
if (a.size()!=2 || b.size(... |
596 | B | Wilbur and Array | Wilbur the pig is tinkering with arrays again. He has the array $a_{1}, a_{2}, ..., a_{n}$ initially consisting of $n$ zeros. At one step, he can choose any index $i$ and either add $1$ to all elements $a_{i}, a_{i + 1}, ... , a_{n}$ or subtract $1$ from all elements $a_{i}, a_{i + 1}, ..., a_{n}$. His goal is to end u... | No matter what, we make $|b_{1}|$ operations to make $a_{1}$ equal to $b_{1}$. Once this is done, $a_{2}, a_{3}, ... a_{n} = b_{1}$. Then no matter what, we must make $|b_{2} - b_{1}|$ operations to make $a_{2}$ equal to $b_{2}$. In general, to make $a_{i} = b_{i}$ we need to make $|b_{i} - b_{i - 1}|$ operations, so i... | [
"greedy",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
#define MAX_N 200010
#define ll long long
using namespace std;
int n;
ll arr[MAX_N], tot=0;
int main(void) {
scanf("%d",&n);
for (int i=0; i<n; i++) {
scanf("%lld",arr+i);
if (i>0) tot+=abs(arr[i]-arr[i-1]);
else tot+=abs(arr[i]);
}
cout << tot << "\n... |
596 | C | Wilbur and Points | Wilbur is playing with a set of $n$ points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point ($x$, $y$) belongs to the set, then all points ($x'$, $y'$), such that $0 ≤ x' ≤ x$ and $0 ≤ y' ≤ y$ also belong to this set.
Now Wilbur wants to number the points in the set he... | Note that if there is an integer $d$ so that the number of $w_{i}$ equal to $d$ differs from the number of the given squares whose weight equals $d$, then the answer is automatically "NO". This can be easily checked by using a map for the $w_{i}$ and the weights of the squares and checking if the maps are the same. Thi... | [
"combinatorics",
"greedy",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
#define MAX_N 100010
using namespace std;
int n;
map<int,vector<pair<int,int> > > weights;
map<int,vector<int> > cnt;
pair<int,int> ans[MAX_N];
vector<int> diag[MAX_N];
int main(void) {
scanf("%d",&n);
for (int i=0; i<n; i++) {
int a, b;
scanf("%d %d",&a,&b);
... |
596 | D | Wilbur and Trees | Wilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down.
There are $n$ trees located at various positions on a line. Tree $i$ is located at position $x_{i}$. All the given positions of the trees are distinct.
The trees are equal, i.e. each tree has ... | Let us solve this problem using dynamic programming. First let us reindex the trees by sorting them by $x$-coordinate. Let $f(i, j, b_{1}, b_{2})$ where we would like to consider the problem of if we only have trees $i... j$ standing where $b_{1} = 1$ indicates that tree $i - 1$ falls right and $b_{1} = 0$ if it falls ... | [
"dp",
"math",
"probabilities",
"sortings"
] | 2,300 | #include <bits/stdc++.h>
#define MAX_N 2010
#define INF 500000000
using namespace std;
int n, h, arr[MAX_N], sz[2][MAX_N];
double dp[MAX_N][MAX_N][2][2], p;
double compute(int lef, int rig, int fl, int fr) {
// 0 means fall left, 1 means fall right
if (lef>rig) return 0;
if (dp[lef][rig][fl][fr]!=-1) re... |
596 | E | Wilbur and Strings | Wilbur the pig now wants to play with strings. He has found an $n$ by $m$ table consisting only of the digits from $0$ to $9$ where the rows are numbered $1$ to $n$ and the columns are numbered $1$ to $m$. Wilbur starts at some square and makes certain moves. If he is at square ($x$, $y$) and the digit $d$ ($0 ≤ d ≤ 9$... | Solution 1: Suppose that $s$ is a string in the query. Reverse $s$ and the direction of all the moves that can be made on the table. Note that starting at any point that is part of a cycle, there is a loop and then edges that go out of the loop. So, for every point, it can be checked by dfs whether the $s$ can be made ... | [
"dfs and similar",
"dp",
"graphs",
"strings"
] | 2,500 | #include <bits/stdc++.h>
#define MAX_N 210
#define SIGMA 10
#define MLEN 1000010
using namespace std;
int n, m, q, values[MAX_N*MAX_N];
int x[SIGMA], y[SIGMA], nxt[MAX_N*MAX_N];
bool in_cycle[MAX_N*MAX_N];
int vis[MAX_N*MAX_N], num_cyc=0, idx[MAX_N*MAX_N];
bool has[MAX_N*MAX_N][SIGMA], vis2[MAX_N*MAX_N];
int first_... |
599 | A | Patrick and Shopping | Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a $d_{1}$ meter long road between his house and the first shop and a $d_{2}$ meter long road between his house and the second shop. Also, there is a road ... | Everything that you needed to do - solve some similar cases. You need to check the following cases: Home $\to$ the first shop $\to$ the second shop $\to$ home Home $\to$ the first shop $\to$ the second shop $\to$ the first shop $\to$ home Home $\to$ the second shop $\to$ home $\to$ the first shop $\to$ home Home $\to$ ... | [
"implementation"
] | 800 | null |
599 | B | Spongebob and Joke | While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence $a_{1}, a_{2}, ..., a_{m}$ of length $m$, consisting of integers from $1$ to $n$, not necessarily distinct. Then he picked some sequence $f_{1}, f_{2}... | First of all, you should read the statement carefully. Then, for every element 1 $...$ $N$ create a list of integers from what we can get this number. After that you have to check some cases, before that create a special mark for answer Ambiguity: Let current element of the given array is $b_{i}$ If two or more element... | [
"implementation"
] | 1,500 | null |
599 | C | Day at the Beach | One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.
At the end of the day there were $n$ castles built by friends. Castles are numbered from $1$ to $n$, and th... | Let's take a minute to see how the best answer should look like. Let $H_{i}$ be a sorted sequence of $h_{i}$. Let $E$ - set of indices of the last elements of each block. Then $\dot{\mathbf{v}}$ $e$ $\underline{{\land}}$ $E$, first $e$ sorted elements of sequence $h_{i}$ are equal to the first $e$ elements of the seque... | [
"sortings"
] | 1,600 | null |
599 | D | Spongebob and Squares | Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly $x$ distinct squares in the table consisting of $n$ rows and $m$ columns. For example, in a $3 × 5$ table there are $15$ squares with side one, $8$ squares wit... | First of all, let's solve this problem for $n \le m$, and then just swap $n$ and $m$ and print the answer. Important! Not to print squares twice! We can use this formula for fixed $n$ & $m$ $(n \le m)$ for calculating the value of $x$. $x=\sum_{i=0}^{n-1}(n-i)*(m-i)\Leftrightarrow x=\textstyle{\sum_{i=0}^{n-1}(n*m-... | [
"brute force",
"math"
] | 1,900 | null |
599 | E | Sandy and Nuts | Rooted tree is a connected graph without any simple cycles with one vertex selected as a root. In this problem the vertex number $1$ will always serve as a root.
Lowest common ancestor of two vertices $u$ and $v$ is the farthest from the root vertex that lies on both the path from $u$ to the root and on path from $v$ ... | The solution for this problem is dynamic programming. Let $f_{root, mask}$ is the number of ways to build a tree with root in vertex $root$ using vertices from the mask $mask$ and all restrictions were met. For convenience we shall number the vertices from zero. The answer is $f_{0, 2^{n} - 1}$. Trivial states are the ... | [
"bitmasks",
"dp",
"trees"
] | 2,600 | null |
600 | A | Extract Numbers | You are given string $s$. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string $s$=";;" contains three empty words separated by ';'.
... | This is a technical problem. You should do exactly what is written in problem statement. | [
"implementation",
"strings"
] | 1,600 | null |
600 | B | Queries about less or equal elements | You are given two arrays of integers $a$ and $b$. For each element of the second array $b_{j}$ you should find the number of elements in array $a$ that are less than or equal to the value $b_{j}$. | Let's sort all numbers in a. Now let's iterate over elements of $b$ and for element $b_{j}$ find the index of lowest number that is greater than $b_{j}$. We can do that using binary search. That index will be the answer for value $b_{j}$. Complexity: $O(nlogn)$. | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | 1,300 | null |
600 | C | Make Palindrome | A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string $s$ consisting of lowercase Latin letters. At once you can choose any position in ... | Let's denote $cnt_{c}$ - the number of occurences of symbol $c$. Let's consider odd values $cnt_{c}$. Palindrome can not contain more than one symbol $c$ with odd $cnt_{c}$. Let's denote symbols with odd $cnt_{c}$ as $a_{1}, a_{2}...a_{k}$ (in alphabetical order). Let's replace any one of symbols $a_{k}$ with symbol $a... | [
"constructive algorithms",
"greedy",
"strings"
] | 1,800 | null |
600 | D | Area of Two Circles' Intersection | You are given two circles. Find the area of their intersection. | If the circles don't intersect than the answer is $0$. We can check that case with only integer calculations (simply by comparing the square of distance between centers with square of the sum of radiuses). If one of the circles is fully in other then the answer is the square of the smaller one. We can check this case a... | [
"geometry"
] | 2,000 | null |
600 | E | Lomsat gelral | You are given a rooted tree with root in vertex $1$. Each vertex is coloured in some colour.
Let's call colour $c$ dominating in the subtree of vertex $v$ if there are no other colours that appear in the subtree of vertex $v$ more times than colour $c$. So it's possible that two or more colours will be dominating in t... | The name of this problem is anagram for ''Small to large''. There is a reason for that :-) The author solution for this problem uses the classic technique for computing sets in tree. The simple solution is the following: let's find for each vertex $v$ the ''map<int, int>'' - the number of occurences for each colour, ''... | [
"data structures",
"dfs and similar",
"dsu",
"trees"
] | 2,300 | null |
600 | F | Edge coloring of bipartite graph | You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour. | Let's denote $d$ is the maximum degree of vertex in graph. Let's prove that the answer is $d$. We will build the constructive algorithm for that (it will be the solution to problem). Let's colour the edges one by one in some order. Let $(x, y)$ be the current edge. If there exist colour $c$ that is free in vertex $x$ a... | [
"graphs"
] | 2,800 | null |
601 | A | The Two Routes | In Absurdistan, there are $n$ towns (numbered $1$ through $n$) and $m$ bidirectional railways. There is also an absurdly simple road network — for each pair of different towns $x$ and $y$, there is a bidirectional road between towns $x$ and $y$ \textbf{if and only if} there is no railway between them. Travelling to a d... | The condition that the train and bus can't meet at one vertex except the final one is just trolling. If there's a railway $\textstyle1\,\,-\,\,N$, then the train can take it and wait in town $N$. If there's no such railway, then there's a road $\textstyle1\,\,-\,\,N$, the bus can take it and wait in $N$ instead. There'... | [
"graphs",
"shortest paths"
] | 1,600 | null |
601 | B | Lipshitz Sequence | A function $f:\mathbb{R}\rightarrow\mathbb{R}$ is called Lipschitz continuous if there is a real constant $K$ such that the inequality $|f(x) - f(y)| ≤ K·|x - y|$ holds for all $x,y\in\mathbb{R}$. We'll deal with a more... discrete version of this term.
For an array $\operatorname{h}[1..n]$, we define it's Lipschitz c... | Let $L_{1}(i,j)={\frac{|x_{i}-A_{i}|}{|i-j|}}$ for $i \neq j$. Key observation: it's sufficient to consider $j = i + 1$ when calculating the Lipschitz constant. It can be seen if you draw points $(i, A_{i})$ and lines between them on paper - the steepest lines must be between adjacent pairs of points. In order to pro... | [
"data structures",
"math"
] | 2,100 | null |
601 | C | Kleofáš and the n-thlon | Kleofáš is participating in an $n$-thlon - a tournament consisting of $n$ different competitions in $n$ different disciplines (numbered $1$ through $n$). There are $m$ participants in the $n$-thlon and each of them participates in all competitions.
In each of these $n$ competitions, the participants are given \underli... | As it usually happens with computing expected values, the solution is dynamic programming. There are 2 things we could try to compute: probabilities of individual overall ranks of Kleofáš or just some expected values. In this case, the latter option works. "one bit is 8 bytes?" "no, the other way around" "so 8 bytes is... | [
"dp",
"math",
"probabilities"
] | 2,300 | null |
601 | D | Acyclic Organic Compounds | You are given a tree $T$ with $n$ vertices (numbered $1$ through $n$) and a letter in each vertex. The tree is rooted at vertex $1$.
Let's look at the subtree $T_{v}$ of some vertex $v$. It is possible to read a string along each simple path starting at $v$ and ending at some vertex in $T_{v}$ (possibly $v$ itself). L... | The name is really almost unrelated - it's just what a tree with arbitrary letters typically is in chemistry. If you solved problem TREEPATH from the recent Codechef November Challenge, this problem should be easier for you - it uses the same technique, after all. Let's figure out how to compute $\operatorname{dif}(v)$... | [
"data structures",
"dfs and similar",
"dsu",
"hashing",
"strings",
"trees"
] | 2,400 | null |
601 | E | A Museum Robbery | There's a famous museum in the city where Kleofáš lives. In the museum, $n$ exhibits (numbered $1$ through $n$) had been displayed for a long time; the $i$-th of those exhibits has value $v_{i}$ and mass $w_{i}$.
Then, the museum was bought by a large financial group and started to vary the exhibits. At about the same... | In this problem, we are supposed to solve the 0-1 knapsack problem for a set of items which changes over time. We'll solve it offline - each query (event of type 3) is asked about a subset of all $N$ exhibits appearing on the input. Introduction If we just had 1 query and nothing else, it's just standard knapsack DP. W... | [
"data structures",
"dp"
] | 2,800 | null |
602 | A | Two Bases | After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers $X$ and $Y$ realised that they have different bases, which complicated their relations.
You're given a number $X$ represented in base $b_{x}$ and a number $Y$ represented in base $b_{y}$. Compare those two numbers. | It's easy to compare two numbers if the same base belong to both. And our numbers can be converted to a common base - just use the formulas $X\,=\,\sum_{i=1}^{N}\,x_{i}B_{x}^{N-i};\quad Y\,=\sum_{i=1}^{M}\,y_{i}B_{y}^{M-i}\,.$A straightforward implementation takes $O(N + M)$ time and memory. Watch out, you need 64-bit ... | [
"brute force",
"implementation"
] | 1,100 | null |
602 | B | Approximating a Constant Range | When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver... | Let's process the numbers from left to right and recompute the longest range ending at the currently processed number. One option would be remembering the last position of each integer using STL map<>/set<> data structures, looking at the first occurrences of $A_{i}$ plus/minus 1 or 2 to the left of the current $A_{i}$... | [
"dp",
"implementation",
"two pointers"
] | 1,400 | null |
603 | A | Alternative Thinking | Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length $n$. Each character of Kevin's string represents Kevin's score on one of the $n$ questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.
However, all is... | Hint: Is there any easy way to describe the longest alternating subsequence of a string? What happens at the endpoints of the substring that we flip? Imagine compressing each contiguous block of the same character into a single character. For example, the first sample case 10000011 gets mapped to 101. Then the longest ... | [
"dp",
"greedy",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int N, res = 1;
string S;
int main(){
cin >> N >> S;
for(int i = 1; i < N; i++){
res += (S[i] != S[i - 1]);
}
cout << min(res + 2, N) << '\n';
} |
603 | B | Moodular Arithmetic | As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers $k$ and $p$, w... | Hint: First there are special cases $k = 0$ and $k = 1$. After clearing these out, think about the following: given the value of $f(n)$ for some $n$, how many other values of $f$ can we find? We first have the degenerate cases where $k = 0$ and $k = 1$. If $k = 0$, then the functional equaton is equivalent to $f(0) = 0... | [
"combinatorics",
"dfs and similar",
"dsu",
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
int P, K;
int modpow(int a, int p){
if(p == 0) return 1;
return (long long) a * modpow(a, p - 1) % MOD;
}
int main(){
cin >> P >> K;
if(K == 0){
cout << modpow(P, P - 1) << '\n';
} else if(K == 1){
cout << modpow(P, P) << ... |
603 | C | Lieges of Legendre | Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are $n$ piles of cows, with the $i$-th pile containing $a_{i}$ cows. During each player's turn, that player calls upo... | Hint: Is there a way to determine the winner of a game with many piles but looking at only one pile at a time? We'll use the concepts of Grundy numbers and Sprague-Grundy's Theorem in this solution. The idea is that every game state can be assigned an integer number, and if there are many piles of a game, then the valu... | [
"games",
"math"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int pre[] = {0, 1, 0, 1, 2};
int N, K, A, res;
int grundy(int a){
if(K % 2 == 0){
if(a == 1) return 1;
if(a == 2) return 2;
return (a % 2) ^ 1;
} else {
if(a < 5) return pre[a];
if(a % 2 == 1) return 0;
return (grundy(a / 2) == 1 ? 2 : ... |
603 | D | Ruminations on Ruminants | Kevin Sun is ruminating on the origin of cows while standing at the origin of the Cartesian plane. He notices $n$ lines $\ell_{1},\ell_{2},\cdot\cdot\ell_{n}$ on the plane, each representable by an equation of the form $ax + by = c$. He also observes that no two lines are parallel and that no three lines pass through t... | Hint: It seems like this would be $O(n^{3})$ because of triples of lines. Can you reduce that with some geometric observations? Think of results from Euclidean geometry relating to 4 points lying on the same circle. First, we will prove a lemma, known as the Simson Line: Lemma: Given points $A, B, C, P$ in the plane wi... | [
"geometry",
"math"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
ll gcd(ll x, ll y){
for( ; y > 0; swap(x, y)) x %= y;
return x;
}
pll reduce(ll x, ll y){
ll g = gcd(abs(x), abs(y));
if(g != 0) x /= g, y /= g;
if((y < 0) || (y == 0 && x < 0)) x = -x, y = -y;
return make_pai... |
603 | E | Pastoral Oddities | In the land of Bovinia there are $n$ pastures, but no paths connecting the pastures. Of course, this is a terrible situation, so Kevin Sun is planning to rectify it by constructing $m$ undirected paths connecting pairs of distinct pastures. To make transportation more efficient, he also plans to pave some of these new ... | Hint: What is a necessary and sufficient condition for Kevin to be able to pave paths so that each edge is incident to an odd number of them? Does this problem remind you of constructing a minimum spanning tree? We represent this problem on a graph with pastures as vertices and paths as edges. Call a paving where each ... | [
"data structures",
"divide and conquer",
"dsu",
"math",
"trees"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
const int MAXM = 300005;
struct node{
node *l, *r, *p, *m;
int f, v, w, s, id;
node(int v, int w, int id) : l(), r(), p(), m(this), f(), v(v), w(w), s(w), id(id) {}
};
inline bool is_root(node *n){
return n -> p == NULL || n -> p -> l ... |
604 | A | Uncowed Forces | Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a... | Hint: Just do it! But if you're having trouble, try doing your computations using only integers. This problem is straightforward implementation---just code what's described in the problem statement. However, floating point error is one place where you can trip up. Avoid it by rounding (adding $0.5$ before casting to in... | [
"implementation"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int pt[5] = {500, 1000, 1500, 2000, 2500}; int tot = 0;
int m[10], w[10];
int main() {
for (int i = 1; i <= 5; ++i)
cin >> m[i];
for (int i = 1; i <= 5; ++i)
cin >> w[i];
int s, u; cin >> s >> u; tot = 100*s-50*u;
... |
604 | B | More Cowbell | Kevin Sun wants to move his precious collection of $n$ cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into $k$ boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than \textbf{two} cowbells i... | Hint: Try thinking about a sorted list of cowbells. What do we do with the largest ones? Intuitively, we want to use as many boxes as we can and put the largest cowbells by themselves. Then, we want to pair the leftover cowbells so that the largest sum of a pair is minimized.This leads to the following greedy algorithm... | [
"binary search",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
int N, K, S[MAXN], res;
int main(){
cin >> N >> K;
for(int i = 0; i < N; i++){
cin >> S[i];
res = max(res, S[i]);
}
for(int i = 0; i < N - K; i++){
res = max(res, S[i] + S[2 * (N - K) - 1 - i]);
}
cout << res << '\n';
} |
605 | A | Sorting Railway Cars | An infinitely long railway has a train consisting of $n$ cars, numbered from $1$ to $n$ (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and telep... | Let's suppose we removed from the array all that elements we would move. What remains? The sequence of the numbers in a row: a, a+1, \dots , b. The length of this sequence must be maximal to minimize the number of elements to move. Consider the array pos, where pos[p[i]] = i. Look at it's subsegment pos[a], pos[a+1], ... | [
"constructive algorithms",
"greedy"
] | 1,600 | null |
605 | B | Lazy Student | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin... | Let's order edges of ascending length, in case of a tie placing earlier edges we were asked to include to MST. Let's start adding them to the graph in this order. If we asked to include the current edge to MST, use this edge to llink 1st vertex with the least currently isolated vertex. If we asked NOT to include the cu... | [
"constructive algorithms",
"data structures",
"graphs"
] | 1,700 | null |
605 | C | Freelancer's Dreams | Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least $p$ experience points, and a desired flat in Moscow costs $q$ dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions t... | We can let our hero not to receive money or experience for some projects. This new opportunity does not change the answer. Consider the hero spent time T to achieve his dream. On each project he spent some part of this time (possibly zero). So the average speed of making money and experience was linear combination of s... | [
"geometry"
] | 2,400 | null |
605 | D | Board Game | You are playing a board card game. In this game the player has two characteristics, $x$ and $y$ — the white magic skill and the black magic skill, respectively. There are $n$ spell cards lying on the table, each of them has four characteristics, $a_{i}$, $b_{i}$, $c_{i}$ and $d_{i}$. In one move a player can pick one o... | Consider n vectors starting at points (a[i], b[i]) and ending at points (c[i], d[i]). Run BFS. On each of its stages we must able to perform such an operation: get set of vectors starting inside rectangle 0 <= x <= c[i], 0 <= y <= d[i] and never consider these vectors again. It can be managed like this. Compress x-coor... | [
"data structures",
"dfs and similar"
] | 2,500 | null |
605 | E | Intergalaxy Trips | The scientists have recently discovered wormholes — objects in space that allow to travel very long distances between galaxies and star systems.
The scientists know that there are $n$ galaxies within reach. You are in the galaxy number $1$ and you need to get to the galaxy number $n$. To get from galaxy $i$ to galaxy ... | The vertex is the better, the less is the expected number of moves from it to reach finish. The overall strategy is: if it is possible to move to vertex better than current, you should move to it, otherwise stay in place. Just like in Dijkstra, we will keep estimates of answer for each vertex, and fix these estimates a... | [
"probabilities",
"shortest paths"
] | 2,700 | null |
606 | A | Magic Spheres | Carl is a beginner magician. He has $a$ blue, $b$ violet and $c$ orange magic spheres. In one move he can transform two spheres \textbf{of the same color} into one sphere of any other color. To make a spell that has never been seen before, he needs at least $x$ blue, $y$ violet and $z$ orange spheres. Can he get them (... | Let's count how many spheres of each type are lacking to the goal. We must do at least that many transformations. Let's count how many spheres of each type are extra relative to the goal. Each two extra spheres give us an opportunity to do one transformation. So to find out how many transformations can be done from the... | [
"implementation"
] | 1,200 | null |
606 | B | Testing Robots | The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell $(x_{0}, y_{0})$ of a rectangular squared field of size $x × y$, after that a mine... | Let's prepare a matrix, where for each cell we will hold, at which moment the robot visits it for the first time while moving through its route. To find these values, let's follow all the route. Each time we move to a cell we never visited before, we must save to the corresponding matrix' cell, how many actions are don... | [
"implementation"
] | 1,600 | null |
607 | A | Chain Reaction | There are $n$ beacons located at distinct positions on a number line. The $i$-th beacon has position $a_{i}$ and power level $b_{i}$. When the $i$-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance $b_{i}$ inclusive. The beacon itself is not destroyed howev... | It turns out that it is actually easier to compute the complement of the problem - the maximum number of objects not destroyed. We can subtract this from the total number of objects to obtain our final answer. We can solve this problem using dynamic programming. Let $dp[x]$ be the maximum number of objects not destroye... | [
"binary search",
"dp"
] | 1,600 | "#include <iostream>\nusing namespace std;\nconst int maxn = 1e6 + 5;\n\nint n, b[maxn], dp[maxn];\n\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(NULL);\n cin >> n;\n for (int i = 0, a; i < n; i++) {\n cin >> a;\n cin >> b[a];\n }\n if (b[0] > 0) {\n dp[0] = 1;\n }\n... |
607 | B | Zuma | Genos recently installed the game Zuma on his phone. In Zuma there exists a line of $n$ gemstones, the $i$-th of which has color $c_{i}$. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones... | We use dp on contiguous ranges to calculate the answer. Let $D[i][j]$ denote the number of seconds it takes to collapse some range $[i, j]$. Let us work out a transition for this definition. Consider the left-most gemstone. This gemstone will either be destroyed individually or as part of a non-singular range. In the f... | [
"dp"
] | 1,900 | "#include<algorithm>\n#include<cstdio>\nusing namespace std;\nconst int maxn=505;\n\nint n, a[maxn], d[maxn][maxn];\n\nvoid read() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 0; i < n; i++) {\n\t\tscanf(\"%d\", a + i);\n\t}\n}\n\nvoid fun() {\n\tfor (int len = 1; len <= n; len++) {\n\t\tfor (int beg = 0, end = len - 1; end... |
607 | C | Marbles | In the spirit of the holidays, Saitama has given Genos two grid paths of length $n$ (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is $(0, 0) → (0, 1) → (0, 2) → (1... | Define the reverse of a sequence as the sequence of moves needed to negate the movement. For example, EEE and WWW are reverses, and WWSSSEE and WWNNNEE are reverses. I claim is impossible to get both balls to the end if and only if some suffix of the first sequence is the reverse of a suffix of the second sequence. Let... | [
"hashing",
"strings"
] | 2,500 | "import java.io.*;\n\npublic class Main {\n final static String dirs = \"NSEW\";\n\n public static void solve(Input in, PrintWriter out) throws IOException {\n int n = in.nextInt() - 1;\n String s1 = in.next();\n String s2 = in.next();\n StringBuilder sb = new StringBuilder();\n ... |
607 | D | Power Tree | Genos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree.
A Power Tree starts out as a single root vertex indexed $1$. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a... | Let's solve a restricted version of the problem where all queries are about the root. First however, let us define some notation. In this editorial, we will use $d(x)$ to denote the number of children of vertex $x$. If there is an update involved, $d(x)$ refers to the value prior to the update. To deal these queries, n... | [
"data structures",
"trees"
] | 2,600 | "//tonynater\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst ll mod = 1000000007;\n\nconst int maxn = 200010;\n\nint v[maxn], q, n = 1, qstore[maxn][2]; //input\n\nint parent[maxn]; //tree\nvector<int> children[maxn]; //tree\n\nint curtravpos, traversal[maxn], bounds[... |
607 | E | Cross Sum | Genos has been given $n$ distinct lines on the Cartesian plane. Let $\mathbf{Z}$ be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter.
Given a query point $(p, q)$, let ${\mat... | The problem boils down to summing the $k$ closest intersections to a given query point. We binary search on the distance $d$ of $k$th farthest point. For a given distance $d$, the number of points within distance $d$ of our query point is equivalent to the number of pairwise intersections that lie within a circle of ra... | [
"binary search",
"geometry"
] | 3,300 | "#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\nusing namespace std;\nconst int maxn = 5e4 + 5;\nconst long double pi = acos((long double)(-1));\n\nint n, m, beg[maxn], fen[2 * maxn], pos[maxn][2], prv[2 * maxn], nxt[2 * maxn];\nlong double x, y, a[maxn], b[maxn];\nv... |
608 | A | Saitama Destroys Hotel | Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from $0$ to $s$ and elevator initially starts on flo... | The minimum amount of time required is the maximum value of $t_{i} + f_{i}$ and $s$, where t_i and f_i are the time and the floor of the passenger respectively. The initial observation that should be made for this problem is that only the latest passenger on each floor matters. So, we can ignore all passengers that are... | [
"implementation",
"math"
] | 1,000 | "n,s = map(int, raw_input().split())\nans = s\nfor i in range(n):\n\tf,t = map(int, raw_input().split())\n\tans = max(ans, t+f)\nprint ans\n" |
608 | B | Hamming Distance Sum | Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string $s$ is denoted $|s|$. The Hamming distance between two strings $s$ and $t$ of equal length is defined as $\sum_{i=1}^{\left|0|}\left|s_{i}-t_{i}\right|$, where $s_{i}$ is the $i$-th character of $s$ and... | We are trying to find $\sum_{i=0}^{|b|-|a|-1}|a[j]-b[i+j]|$. Swapping the sums, we see that this is equivalent to $\sum_{j=0}^{|a|-1}\sum_{i=0}^{|b|-|a|}|a[j]-b[i+j]|$. Summing up the answer in the naive fashion will give an $O(n^{2})$ solution. However, notice that we can actually find $\sum_{i=0}^{|b|-|a|}|a|j\rangle... | [
"combinatorics",
"strings"
] | 1,500 | "#include <cstdlib>\n#include <iostream>\n#include <string>\nusing namespace std;\ntypedef long long ll;\nconst int MAXS = 200010;\n\nstring A, B;\nint F[MAXS][2];\n\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(NULL);\n cin >> A >> B;\n for (int i = 1; i <= B.size(); i++) {\n for (int j = ... |
609 | A | USB Flash Drives | Sean is trying to save a large file to a USB flash drive. He has $n$ USB flash drives with capacities equal to $a_{1}, a_{2}, ..., a_{n}$ megabytes. The file size is equal to $m$ megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. | Let's sort the array in nonincreasing order. Now the answer is some of the first flash-drives. Let's iterate over array from left to right until the moment when we will have the sum at least $m$. The number of elements we took is the answer to the problem. Complexity: $O(nlogn)$. | [
"greedy",
"implementation",
"sortings"
] | 800 | null |
609 | B | The Best Gift | Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are $n$ books on sale from one of $m$ genres.
In the bookshop, Jack decides to buy two books of different genres.
Based on the genre of books on sale in the shop, find th... | Let's denote $cnt_{i}$ - the number of books of $i$ th genre. The answer to problem is equals to $\sum_{i=1}^{m}\sum_{i=i+1}^{m}c n t_{i}\cdot c n t_{j}={\frac{n\!\cdot\!(n-1)}{2}}-\sum_{i=1}^{m}{\frac{c n t_{i}\cdot(c n t_{i}-1)}{2}}$. In first sum we are calculating the number of good pairs, while in second we are su... | [
"constructive algorithms",
"implementation"
] | 1,100 | null |
609 | C | Load Balancing | In the school computer room there are $n$ servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are $m_{i}$ tasks assigned to the $i$-th server.
In order to balance the load for each server, you want to reassign some tasks to make the differ... | Denote $s$ - the sum of elements in array. If $s$ is divisible by $n$ then the balanced array consists of $n$ elements $\mathbf{\Pi}_{n}^{S}$. In this case the difference between maximal and minimal elements is $0$. Easy to see that in any other case the answer is greater than $0$. On the other hand the array consists ... | [
"implementation",
"math"
] | 1,500 | null |
609 | D | Gadgets for dollars and pounds | Nura wants to buy $k$ gadgets. She has only $s$ burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for $n$ days. For each day you know the exchange rates ... | If Nura can buy $k$ gadgets in $x$ days then she can do that in $x + 1$ days. So the function of answer is monotonic. So we can find the minimal day with binary search. Denote $lf = 0$ - the left bound of binary search and $rg = n + 1$ - the right one. We will maintain the invariant that in left bound we can't buy $k$ ... | [
"binary search",
"greedy",
"two pointers"
] | 2,000 | null |
609 | E | Minimum spanning tree for each edge | Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains $n$ vertices and $m$ edges.
For each edge $(u, v)$ find the minimal possible weight of the spanning tree that contains the edge $(u, v)$.
The weight of the spanning tree is the sum of weights of all edges included in sp... | This problem was prepared by dalex. Let's build any MST with any fast algorithm (for example with Kruskal's algorithm). For all edges in MST the answer is the weight of the MST. Let's consider any other edge $(x, y)$. There is exactly one path between $x$ and $y$ in the MST. Let's remove mostly heavy edge on this path ... | [
"data structures",
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,100 | null |
609 | F | Frogs and mosquitoes | There are $n$ frogs sitting on the coordinate axis $Ox$. For each frog two values $x_{i}, t_{i}$ are known — the position and the initial length of the tongue of the $i$-th frog (it is guaranteed that all positions $x_{i}$ are different). $m$ mosquitoes one by one are landing to the coordinate axis. For each mosquito t... | Let's maintain the set of not eaten mosquitoes (for example with set in C++ or with TreeSet in Java) and process mosquitoes in order of their landing. Also we will maintain the set of segments $(a_{i}, b_{i})$, where $a_{i}$ is the position of the $i$-th frog and $b_{i} = a_{i} + l_{i}$, where $l_{i}$ is the current le... | [
"data structures",
"greedy"
] | 2,500 | null |
610 | A | Pasha and Stick | Pasha has a wooden stick of some positive integer length $n$. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be $n$.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to s... | If the given $n$ is odd the answer is 0, because the perimeter of any rectangle is always even number. If $n$ is even the number of rectangles which can be construct equals to $n / 4$. If $n$ is divisible by 4 we will count the square, which are deprecated, because we need to subtract 1 from the answer. Asymptotic beha... | [
"combinatorics",
"math"
] | 1,000 | null |
610 | B | Vika and Squares | Vika has $n$ jars with paints of distinct colors. All the jars are numbered from $1$ to $n$ and the $i$-th jar contains $a_{i}$ liters of paint of color $i$.
Vika also has an infinitely long rectangular piece of paper of width $1$, consisting of squares of size $1 × 1$. Squares are numbered $1$, $2$, $3$ and so on. Vi... | At first let's find the minimum in the given array and store it in the variable $minimum$. It is easy to understand, that we always can paint $n * minimum$ squares. So we need to find such a minimum in the array before which staying the most number of elements, which more than the minimum. In the other words we need to... | [
"constructive algorithms",
"implementation"
] | 1,300 | null |
610 | C | Harmony Analysis | The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find $4$ vectors in $4$-dimensional space, such that every coordinate of every... | Let's build the answer recursively. For $k = 0$ the answer is $- 1$ or $+ 1$. Let we want to build the answer for some $k > 0$. At first let's build the answer for $k - 1$. As the answer for $k$ let's take four copies of answer for $k - 1$ with inverting of values in last one. So we have some fractal with $2 \times 2... | [
"constructive algorithms"
] | 1,800 | null |
610 | D | Vika and Segments | Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew $n$ black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to $1$ square, that means every segment occupy some set of nei... | At first let's unite all segments which are in same verticals or horizontals. Now the answer to the problem is the sum of lengths of all segments subtract the number of intersections. Let's count the number of intersections. For this let's use the horizontal scan-line from the top to the bottom (is can be done with hel... | [
"constructive algorithms",
"data structures",
"geometry",
"two pointers"
] | 2,300 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.