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 ⌀ |
|---|---|---|---|---|---|---|---|
923 | E | Perpetual Subtraction | There is a number $x$ initially written on a blackboard. You repeat the following action a fixed amount of times:
- take the number $x$ currently written on a blackboard and erase it
- select an integer uniformly at random from the range $[0, x]$ inclusive, and write it on the blackboard
Determine the distribution of... | We can model this process as a Markov chain with $N + 1$ states with transition matrix $\frac{\|\mathbf{\hat{l}}\|\mathbf{\hat{l}}\mathbf{\hat{l}}}{\|\mathbf{\hat{l}}\|}_{\hat{l}}\mathbf{\hat{l}}$ The task is to find $R = A^{M} \cdot P$. A naive solution using Matrix exponentiation is obviously too slow, as it uses $O(... | [
"fft",
"math",
"matrices"
] | 3,100 | null |
923 | F | Public Service | There are $N$ cities in Bob's country connected by roads. Some pairs of cities are connected by public transport. There are two competing transport companies — \textbf{Boblines} operating buses and \textbf{Bobrail} running trains. When traveling from $A$ to $B$, a passenger always first selects the mode of transport (e... | For $k \ge 0$, we call graph $G$ a $k$-star, if we can remove $k$ vertices to form a star, and we cannot remove $k - 1$ vertices to form a star. In this terminology, a $0$-star is a star. It should be rather obvious that if one of the graphs is a 0-star, then the answer is clearly No. This is because the minimum degr... | [
"constructive algorithms",
"graphs",
"trees"
] | 3,200 | null |
924 | A | Mystical Mosaic | There is a rectangular grid of $n$ rows of $m$ initially-white cells each.
Arkady performed a certain number (possibly zero) of operations on it. In the $i$-th operation, a non-empty subset of rows $R_{i}$ and a non-empty subset of columns $C_{i}$ are chosen. For each row $r$ in $R_{i}$ and each column $c$ in $C_{i}$,... | No row or column can be selected more than once, hence whenever a row $r$ is selected in an operation, all cells in it uniquely determine the set of columns that need to be selected - let's call it $S_{r}$. Let's assume a valid set of operations exists. Take out any two rows, $i$ and $j$. If rows $i$ and $j$ are select... | [
"greedy",
"implementation"
] | 1,300 | #include <cstdio>
#include <algorithm>
#include <vector>
static const int MAXN = 1004;
static int n, m;
static bool g[MAXN][MAXN];
// c[i] = set of rows where the i-th column is coloured
static std::vector<int> c[MAXN];
static bool checked[MAXN] = { false };
int main()
{
scanf("%d%d", &n, &m); getchar();
for ... |
924 | B | Three-level Laser | An atom of element X can exist in $n$ distinct states with energies $E_{1} < E_{2} < ... < E_{n}$. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.
Three distinct states $i$, $j$ and $k$ are selected, where $i < j < k$. After that the following ... | First of all, you can note that for fixed $i$ and $k$ setting $j = i + 1$ is always the best choice. Indeed, if $X > Y$, then ${\frac{A-X}{B}}<{\frac{A-Y}{B}}$ for positive $B$. Then, let's fix $i$. Then $j = i + 1$, and what is the optimal $k$? We can define the energy loss as $l=1-\eta={\frac{E_{i}-E_{i}}{E_{i}-E}}$.... | [
"binary search",
"greedy",
"two pointers"
] | 1,600 | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#define forn(i, n) for(int i=0;i<n;++i)
#define fo... |
924 | C | Riverside Curio | Arkady decides to observe a river for $n$ consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water... | Define $t_{i}$ as the total number of marks (above or at or under the water level) on the $i$-th day. As $t_{i} = m_{i} + 1 + d_{i}$, minimizing $\textstyle\sum d_{i}$ is equivalent to minimizing $\textstyle\sum t_{i}$. For the $i$-th day we would like to find the minimum value of $t_{i}$. Needless to say $t_{i} \ge ... | [
"data structures",
"dp",
"greedy"
] | 1,700 | #include <cstdio>
#include <algorithm>
typedef long long int64;
static const int MAXN = 1e5 + 4;
static int n, m[MAXN];
static int t[MAXN];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &m[i]);
for (int i = n - 1, cur = 0; i >= 0; --i) {
cur = std::max(0, cur - 1);
... |
924 | D | Contact ATC | Arkady the air traffic controller is now working with $n$ planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point $0$ on it. The $i$-th plane, small enough to be represented by a point, currently has a coordinate of $x_{i}$ and is moving with speed $v_{i}$. It's guarante... | Stuck in tedious fractions produced by kinematic formulae? No, that's not the way to go. Forgetting about all physics, how does wind speed affect the time when a plane flies over the origin? Consider a plane flying from left to right, passing through the origin. Initially it has speed $v_{i} - w$ and meets the origin a... | [] | 2,500 | #include <cstdio>
#include <algorithm>
#include <utility>
typedef long long int64;
static const int MAXN = 1e5 + 4;
static const int MAXX = 1e8 + 4;
static int n, w;
static int x[MAXN], v[MAXN];
struct fraction {
template <typename T> static inline T gcd(const T a, const T b) {
return (b == 0) ? a : gcd(... |
924 | E | Wardrobe | Olya wants to buy a custom wardrobe. It should have $n$ boxes with heights $a_{1}, a_{2}, ..., a_{n}$, stacked one on another in some order. In other words, we can represent each box as a vertical segment of length $a_{i}$, and all these segments should form a single segment from $0$ to $\textstyle\sum_{i=1}^{n}a_{i}$ ... | The first idea of the author's solution is to reverse the problem: change $l$ to $H - r$ and $r$ to $H - l$, where $H$ is the total height of the wardrobe. Now an important box is counted in the answer if and only if its top edge is within the segment $[l, r]$. We'll see later the profit of this operation. Now, we'll b... | [
"dp",
"greedy"
] | 2,700 | /**
* This is a solution for problem wardrobe
* This is nk_ok.cpp
*
* @author: Nikolay Kalinin
* @date: Tue, 20 Mar 2018 21:48:33 +0300
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = ... |
924 | F | Minimal Subset Difference | We call a positive integer $x$ a $k$-beautiful integer if and only if it is possible to split the multiset of its digits in the decimal representation into two subsets such that the difference between the sum of digits in one subset and the sum of digits in the other subset is \textbf{less than or equal to} $k$. Each d... | Let $f(x)$ be the minimal subset difference mentioned in the problem statement. The problem seems like a regular digit DP problem. However, it's a bit hard to reduce the number of DP states. Let's take a careful consideration. For a given integer $x$, we can use knapsack DP to determine $f(x)$. Denote the sum of digits... | [
"dp"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxd = 10, maxl = 18, maxs = 81, BLEN = 5, BMSK = 31;
struct States {
vector<LL> keys, vals[maxd + 1];
void insert(LL key) {
keys.push_back(key);
}
void initialize(LL val = 0) {
sort(keys.begin(), keys.end());
keys.erase(unique(keys... |
925 | A | Stairs and Elevators | In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different fl... | First thing to mention is that we can use no more than one stairs or elevator per query. Indeed, optimal path is always a few sections horizontally, then a stair of elevator, then a few sections horizontally. Then, we can note that we can always use one of the nearest stairs/elevators to start/finish. Using this fact, ... | [
"binary search"
] | 1,600 | null |
925 | B | Resource Distribution | One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.
In order for production to work, it ... | Suppose that the load of the first service was divided among $k_1$ servers and the load of the second service was divided among $k_2$ servers. In such case first service will be running on $k_1$ servers of resource at least $p_1 = \lceil x_1 / k_1 \rceil$ and second service will be run on $k_2$ servers of resource at l... | [
"binary search",
"implementation",
"sortings"
] | 1,700 | null |
925 | C | Big Secret | Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer \sout{54} 42, but an increasing integer sequence $a_1, \ldots, a_n$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $b_1, \ldots, b_n$ using t... | Let's assume that we've found a suitable permutation of all numbers, except all occurences of the number $1$. When can we insert the $1$'s so that the new arrangement of numbers is again good? We can see that the XOR of all numbers before any occurence of the number $1$ must be even, so there should an even number of o... | [
"constructive algorithms",
"math"
] | 2,200 | null |
925 | D | Aztec Catacombs | Indiana Jones found ancient Aztec catacombs containing a golden idol. The catacombs consists of $n$ caves. Each pair of caves is connected with a two-way corridor that can be opened or closed. The entrance to the catacombs is in the cave $1$, the idol and the exit are in the cave $n$.
When Indiana goes from a cave $x$... | Let us formualate a problem in terms of graph theory and make some observation. Denote the start and the finish vertices as $s$ and $t$. Observation 1. If vertices $s$ and $t$ are connected with a simple path consisting of $k$ edges, then by the statement of the problem Indiana Johns may use it leading us to the answer... | [
"constructive algorithms"
] | 2,600 | null |
925 | E | May Holidays | It's May in Flatland, and there are $m$ days in this month. Despite the fact that May Holidays are canceled long time ago, employees of some software company still have a habit of taking short or long vacations in May.
Of course, not all managers of the company like this. There are $n$ employees in the company that fo... | In terms of trees we have a rooted tree whose vertices may be activated and deactivated, and each vertex has a limit for the number of deactivated vertices among its descendants. We are required to switch the state of some vertex, and after each query we report the number of activated vertices unsatisfied vertices. Let... | [
"data structures",
"trees"
] | 2,900 | null |
925 | F | Parametric Circulation | Vova has recently learned what a circulaton in a graph is. Recall the definition: let $G = (V, E)$ be a directed graph. A circulation $f$ is such a collection of non-negative real numbers $f_e$ ($e \in E$), that for each vertex $v \in V$ the following conservation condition holds:
$$\sum\limits_{e \in \delta^{-}(v)} f... | First, let's use the classical reduction of $lr$-circulation problem to the maximum flow problem. Consider a network $G' = (V \cup \{s, t\}, E')$ where for each $e = uv \in E$ there are three edges: $e_0 = uv$ with capacity $c_{e_0} = r_e - l_e$ $e_1 = sv$ with capacity $c_{e_1} = l_e$ $e_2 = ut$ with capacity $c_{e_2}... | [
"binary search",
"flows"
] | 3,100 | null |
928 | A | Login Verification | When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ... | At first let's format all existing logins. For each login we will do the following: change all uppercase letters on lowercase letters; change all letters o on the digit 0; change all letters i and l on the digit 1. If new login is equal to some of the formatted login, the user can not register new login. In the other c... | [
"*special",
"strings"
] | 1,200 | null |
928 | B | Chat | There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from $1$ ... | Let's use the dynamic. We will calculate the answer for the messages in the order of increasing their numbers. Let the current message has number $x$, then the answer was calculated for each $y$ from $1$ to $(x - 1)$ and equals to $cnt_{y}$. If there is no a link in the message $y$ then the answer for this message - is... | [
"*special",
"dp"
] | 1,400 | null |
930 | A | Peculiar apple-tree | In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are $n$ inflorescences, numbered from $1$ to $n$. Inflorescence number $1$ is situated near base of tree and any other inflorescence with number $i$ ($i > 1$) is situated at the t... | Firstly, let's formalize problem: we have tree with root in first inflorescence. Let's examine apples that can roll down to the base of tree in $t$-th moment of time. It is obvious this are apples initially situated in nodes at $t$ distance from root. Key idea of solution is that we can suppose that apples in nonroot n... | [
"dfs and similar",
"graphs",
"trees"
] | 1,500 | null |
930 | B | Game with String | Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string $s$, consisting of small English letters, and uniformly at random chooses an integer $k$ from a segment $[0, len(s) - 1]$. He tells Vasya this string $s$, and then shifts it $k$ letters to the left, i. e. creates a n... | Idea. Let's consider all possible $c_{1}$ that will be first in $t$. Then, let's consider all possible numbers of second letter that Vasya will ask about - this will be $d$. If pair of letters ($c_{1}$, $c_{2}$) occurs only once at $d$ distance, than if $c_{2}$ opens second time, Vasya will be able to determine shift. ... | [
"implementation",
"probabilities",
"strings"
] | 1,600 | null |
930 | C | Teodor is not a liar! | Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge $[1;m]$ segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodo... | Idea. The main idea is that set of point $x_{i}$ is bad(meaning that Sasha can't be sure, that Teodor hasn't lied, relying only on this information) $\iff c n t(x_{i})$ satisfies the following property: $\begin{array}{c}{{\exists i:1\ \le\ i\le n\circ n t(x_{1})\ \le\ c n t(x_{2})\ \le\ \cdot\cdot\cdot\ \le\ c n t(x_{i... | [
"data structures",
"dp"
] | 1,900 | null |
930 | D | Game with Tokens | Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates $x$ and $y$.
The players take turn making moves, white starts. On each turn, a player moves \textbf{all} tokens of their color by $1$ to up, down, l... | Note that if black and white chip are placed in the beginning in points ${x, y}$ with the same parity of $x + y$ then black chip can't be on the manhattan distance $1$ from white chip before white's move. So black chip can't block white chip and can't somehow affect the game. We can solve the problem independently for ... | [
"data structures",
"games",
"implementation"
] | 2,500 | null |
930 | E | Coins Exhibition | Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from $1$ to $k$, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.
Arkady and Kirill made some photos of the coins, each photo contained a segment of ne... | Denote obverse-up coin as $0$ and reverse-up coin as $1$. Then we are to compute the number of binary strings of length $k$ such that $n$ of the given segments have atleast one $0$ and other $m$ ones - atleast one $1$. Let $dp[i][l_{0}][l_{1}]$ be the number of binary strings of length $i$ such that the last zero is at... | [
"data structures",
"dp",
"math"
] | 2,900 | null |
931 | A | Friends Meeting | Two friends are on the coordinate axis $Ox$ in points with integer coordinates. One of them is in the point $x_{1} = a$, another one is in the point $x_{2} = b$.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes accordi... | At first understand the fact that friend should make their moves one be one and the friend who initially was left should move to the right and other friend should move to the left. Let $len = |a - b|$. Then the first friend will make $cntA = len / 2$ moves, and the second friend - $cntB = len - len / 2$ moves. So the a... | [
"brute force",
"greedy",
"implementation",
"math"
] | 800 | null |
931 | B | World Cup | The last stage of Football World Cup is played using the play-off system.
There are $n$ teams left in this stage, they are enumerated from $1$ to $n$. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with th... | Initially, we need to understand the following fact. Since the number of teams in each round is even, $n$ should be a power of two. We will solve the problem for the 0-indexing commands, so we decrease the given $a$ and $b$ on one. For each round we will determine the number of the match, in which the teams with initia... | [
"constructive algorithms",
"implementation"
] | 1,200 | null |
931 | C | Laboratory Work | Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value $n$ times, and then compute the average value to lower the error.
Kirill has already made his measurements, and has got the following integer values: $x_{1}$, $x_{2}$, ..., $x_{n}$. It is important that the values ... | The average value of Anya measurements should be equal to the average value of Kirill's measurements, so the sum of all Anya measurements should be equal to the sum of all Kirill dimensions. Let the minimum number in the Kirill's measurements is $min$ and the maximum - $max$. Then, if $(max - min)$ is less than or equa... | [
"implementation",
"math"
] | 1,700 | null |
932 | A | Palindromic Supersequence | You are given a string $A$. Find a string $B$, where $B$ is a palindrome and $A$ is a subsequence of $B$.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequ... | Let $reverse(s)$ be the reverse of string $s$. Now, $s + reverse(s)$ will always have $s$ as a subsequence (as first half) and it is a palindrome with size less than $10^{4}$. So, it may be one of the possible solutions. | [
"constructive algorithms"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<s;
reverse(s.begin(),s.end());
cout<<s;
return 0;
} |
932 | B | Recursive Queries | Let us define two functions $f$ and $g$ on positive integer numbers.
\begin{center}
$f(n)=\mathrm{product~of~non}{\mathrm{-zero~digits~of~}}n$$g(n)={\binom{n}{g(f(n))}}\quad{\begin{array}{l l}{{\mathrm{if~}}n<10}\\ {{\mathrm{otherwise}}}\end{array}}$
\end{center}
You need to process $Q$ queries. In each query, you wi... | If we can show that for all integers $n \ge 10$, we have $n > f(n)$ then we can use bottom up dp for calculating $g(n)$ for all the integers $1 \le n \le 10^{6}$ in $O(n)$. And as $1 \le g(n) \le 9$, using partial sum arrays for each possible value of $g(n)$, we can answer the queries in $O(1)$. For the proof... | [
"binary search",
"data structures",
"dfs and similar"
] | 1,300 | #include "bits/stdc++.h"
#ifdef PRINTERS
#include "printers.hpp"
using namespace printers;
#define tr(a) cerr<<#a<<" : "<<a<<endl
#else
#define tr(a)
#endif
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
... |
932 | C | Permutation Cycle | For a permutation $P[1... N]$ of integers from $1$ to $N$, function $f$ is defined as follows:
\begin{center}
$f(i,j)={\binom{P[i]}{f(P[i],j-1)}}\quad\quad{\mathrm{if~}}j=1$
\end{center}
Let $g(i)$ be the minimum positive integer $j$ such that $f(i, j) = i$. We can show such $j$ always exists.
For given $N, A, B$, f... | For $f(i, j) = i$ and $g(i) = k$, there must exist a cycle of length $k$ beginning from index $i$ and ending at the same index $i$ of permutation $P$. While generating a permutation $P$, we are constrained to generate cycles of length either $A$ or $B$ as $g(i)$ for all $1 \le i \le N$ must be equal to either of th... | [
"brute force",
"constructive algorithms"
] | 1,600 | #include "bits/stdc++.h"
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define h... |
932 | D | Tree | You are given a node of the tree with index $1$ and with weight $0$. Let $cnt$ be the number of nodes in the tree at any instant (initially, $cnt$ is set to $1$). Support $Q$ queries of following two types:
- $\mathrm{i}\ \mathrm{R}\ \mathrm{W}:$ Add a new node (index $cnt + 1$) with weight $W$ and add edge between no... | The main idea is that we will use binary lifting. Twice. Let's consider the following $O(Q \times N)$ algorithm - for every vertex $u$ (when inserted) find the closest vertex $v$ above it with $w[v] \ge w[u]$. Lets have an array $nxt[]$, such that $nxt[u] = v$. Then the query will be done by simply jumping to the v... | [
"binary search",
"dp",
"trees"
] | 2,200 | #include "bits/stdc++.h"
#ifdef PRINTERS
#include "printers.hpp"
using namespace printers;
#define tr(a) cerr<<#a<<" : "<<a<<endl
#else
#define tr(a)
#endif
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#... |
932 | E | Team Work | You have a team of $N$ people. For a particular task, you can pick any non-empty subset of people. The cost of having $x$ people for the task is $x^{k}$.
Output the sum of costs over all non-empty subsets of people. | The required sum can be expressed as $\sum_{r=1}^{n}{\binom{n}{r}}r^{k}$. $f(x)=(1+x)^{n}=\sum_{r=0}^{n}{\binom{n}{r}}x^{r}$ Differentiating the above equation and multiplying by $x$, we get $n x(1+x)^{n-1}=\sum_{r=1}^{n}{\binom{n}{r}}r x^{r}$ Differentiating and multiplying by $x$ again, we get $x{\frac{\mathrm{d}}{\m... | [
"combinatorics",
"dp",
"math"
] | 2,400 | #include "bits/stdc++.h"
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define h... |
932 | F | Escape Through Leaf | You are given a tree with $n$ nodes (numbered from $1$ to $n$) rooted at node $1$. Also, each node has two values associated with it. The values for $i$-th node are $a_{i}$ and $b_{i}$.
You can jump from a node to any node in its subtree. The cost of one jump from node $x$ to node $y$ is the product of $a_{x}$ and $b_... | The problem can be solved by dynamic programming. Let $dp[i]$ be the minimum cost to reach a leaf from $i^{th}$ node. Then, $d p[i]=\operatorname*{min}_{\forall j\in s u b t r e e(i)}(a[i]\ast b[j]+d p[j])$ where $j \neq i$. This is equivalent to finding the minimum $y$ at $x = a[i]$ among lines $y = b[j] * x + dp[j]... | [
"data structures",
"dp",
"geometry"
] | 2,700 | #include "bits/stdc++.h"
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define ... |
932 | G | Palindrome Partition | Given a string $s$, find the number of ways to split $s$ to substrings such that if there are $k$ substrings $(p_{1}, p_{2}, p_{3}, ..., p_{k})$ in partition, then $p_{i} = p_{k - i + 1}$ for all $i$ $(1 ≤ i ≤ k)$ and $k$ is even.
Since the number of ways can be large, print it modulo $10^{9} + 7$. | Let n be the length of the string $s$. Consider the string $t = s[0]s[n - 1]s[1]s[n - 2]s[2]s[n - 3]...s[n / 2 - 1]s[n / 2]$. The problem can be reduced to finding the number of ways to partition string $t$ into palindromic substrings of even length. Proof: Let $k$ be the total number of partitions. Let $p_{i} = p_{k -... | [
"dp",
"string suffix structures",
"strings"
] | 2,900 | #define NDEBUG
NDEBUG
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstring>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unord... |
933 | A | A Twisty Movement | A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a $1$, while one holding it high is represented by a $2$. Thus... | Since $1 \le a_{i} \le 2$, it's equivalent to find a longest subsequence like $1^{} * 2^{} * 1^{} * 2^{} *$. By an easy dynamic programming we can find it in $O(n)$ or $O(n^{2})$ time. You can see $O(n^{2})$ solution in the model solution below. Here we introduce an O(n) approach: Since the subsequence can be split... | [
"dp"
] | 1,800 | #include <bits/stdc++.h>
#define rep(i, x, y) for (int i = (x), _ = (y); i < _; ++i)
#define down(i, x, y) for (int i = (x) - 1, _ = (y); i >= _; --i)
#define fi first
#define se second
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define bin(x) (1 << (x))
#define SZ(x) int((x).size())
using namespace ... |
933 | B | A Determined Cleanup | In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers $p$ and $k$, find a polynomial $f(x)$ with non-negative integer coefficients... | For simplicity's sake, we present a rather intuitive approach rather than a rigorous proof (can be obtained by induction). For a given polynomial $f(x)$, what's its remainder taken modulo $(x + k)$? Let $f(x) = q(x) \cdot (x + k) + p$. Let Simulating the process of polynomial long division $f(x)$ divided by $(x + k)$, ... | [
"math"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
long long p;
int k;
int cnt=0;
int ans[107];
int get()
{
int x=p%k;
if (x<0) x+=k;
return x%k;
}
int main()
{
scanf("%lld%d",&p,&k);
while (p!=0)
{
++cnt;
ans[cnt]=get();
p-=get();
p/=(-k);
}
printf("%d\n",cnt);
for (int i=1;i<=cnt;i++)
printf("%d ",ans[i... |
933 | C | A Colourful Prospect | Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.
Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.
A wonder strikes Tommy. How many regions are formed by the circl... | It seems the problem can be solved with case analysis at first sight. Okay let's try to do so... For $n = 1$, it's trivial and the answer is, of course, $2$. For $n = 2$, there are two cases: If the two circles are intersect, the answer is $4$; Otherwise, the answer is $3$. For $n = 3$... well I think it's really a tou... | [
"geometry",
"graphs"
] | 2,700 | #include <cmath>
#include <cstdio>
#include <algorithm>
static const int MAXN = 3;
static const double EPS = 1e-9;
static int n;
static int x[MAXN], y[MAXN], r[MAXN];
// -2: internally separate
// -1: internally tangent
// 0: intersecting
// +1: externally tangent
// +2: externally separate
static int g[MAXN][MAXN]... |
933 | D | A Creative Cutout | Everything red frightens Nian the monster. So do red paper and... you, red on Codeforces, potential or real.
Big Banban has got a piece of paper with endless lattice points, where lattice points form squares with the same area. His most favorite closed shape is the circle because of its beauty and simplicity. Once he ... | For the sake of explanation, let's use $\textstyle{\binom{n}{k}}$ to represent the binomial coefficient $\frac{n!}{k!(n-k)!}$ and construct a coordinate system such that each coordinate axis parallels to one of the lattice edges, the origin is the center of concentric circles and each unit of length in this system is a... | [
"brute force",
"combinatorics",
"math"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
#define re return
#define sz(a) (int)a.size()
#define mp(a, b) make_pair(a, b)
#define fi first
#define se second
#define re return
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define bend(a) a.begin(),a.end()
typedef long long ll;
typedef vector<int> vi;
typedef... |
933 | E | A Preponderant Reunion | East or west, home is best. That's why family reunion, the indispensable necessity of Lunar New Year celebration, is put in such a position.
After the reunion dinner, Little Tommy plays a game with the family. Here is a concise introduction to this game:
- There is a sequence of $n$ non-negative integers $p_{1}, p_{2... | The author was inspired by 100705B1 - Rasta-making and then made this problem. Noticing that there are no two consecutive positive integers after the game ends, the final sequence can be divided into some intervals which consist only zero elements such that the gap between every two adjacent intervals is at most one el... | [
"constructive algorithms",
"dp"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = (int)3e5 + 3;
int n, a[maxn], cnt, p[maxn], m, out[maxn];
LL f[maxn];
bool v[maxn];
int descension(int pos) {
int dt = min(a[pos], a[pos + 1]);
if(dt)
out[++m] = pos;
a[pos] -= dt;
a[pos + 1] -= dt;
return dt;
}
int main() {
sc... |
934 | A | A Compatible Pair | Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has $n$ lanterns and Big B... | We can do as what we are supposed to do - hide one of the Tommy's lantern, and then take one non-hidden lantern from Tommy and one lantern from Banban so that the product of their brightness is maximized and the minimum between all cases becomes our answer. This is a straightforward $O(n^{2}m)$ solution. Also, there ar... | [
"brute force",
"games"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=(1LL<<60)-1;
ll a[55],b[55];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(int i=1;i<=m;i++)
scanf("%lld",&b[i]);
ll res=INF;
for(int i=1;i<=n;i++)
{
... |
934 | B | A Prosperous Lot | Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.
Big Banban is hesitating over the amount ... | What's the maximum number of loops in an integer no greater than $10^{18}$? Since $8$ is the only digit with two loops, we tend to use as many eights as possible. It can be seen that the answer is $36$, achieved by $888 888 888 888 888 888$. Thus if $k > 36$, the answer does not exist under the constraints. There are t... | [
"constructive algorithms",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int n,k;
int main()
{
scanf("%d",&k);
if (k>36) printf("%d\n",-1);
else
{
while (k>0)
{
if (k>=2)
{
printf("%d",8);
k-=2;
} else
{
printf("%d",9);
k-=1;
}
}
printf("\n");
}
return 0;
}
|
935 | A | Fafa and his Company | Fafa owns a company that works on huge projects. There are $n$ employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best $l$ em... | Let's try all values of $l$ from 1 to $n - 1$ and check whether the remaining people could be distributed equally over team leaders (that is, $l$ divides $n - l$). The number of valid values of $l$ is our answer. Complexity: $O(n)$. The problem is also equivalent to finding the number of ways to divide the $n$ employee... | [
"brute force",
"implementation"
] | 800 | null |
935 | B | Fafa and the Gates | Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | Fafa visits the gates when he stands on the line $y = x$. This happens only when he makes an equal number of up and right moves. Fafa will pass the gates if he is currently at a gate and will make a move similar to the last one. So, we can iterate over the moves in order from left to right keeping track of the number o... | [
"implementation"
] | 900 | null |
935 | C | Fifa and Fafa | Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of $r$ meters (this range can be chosen ... | Let $p$ be Fafa's position and $c$ be the flat center. Obviously, the largest wifi circle we can draw will touch the point $p$ and a point on the flat circle border $q$. The diameter of the circle will be the distance between $p$ and $q$. To maximize the area of the wifi circle, we will choose $q$ to be the furthest po... | [
"geometry"
] | 1,600 | null |
935 | D | Fafa and Ancient Alphabet | Ancient Egyptians are known to have used a large set of symbols $\textstyle\mathbf{\hat{Z}}$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words $S_{1}$ and $S_{2}$ of equal lengths on the wall of temple written one below the other. Since this temple is very anci... | Let $Suff_{1}(i)$ and $Suff_{2}(i)$ be the suffixes of $S_{1}$ and $S_{2}$ starting from index $i$, respectively. Also, let $P(i)$ be the probability of $Suff_{1}(i)$ being lexicographically larger than $Suff_{2}(i)$. $P(i)$ is equal to the probability that: $S_{1}[i]$ is greater than $S_{2}[i]$, or $S_{1}[i]$ is equal... | [
"math",
"probabilities"
] | 1,900 | null |
935 | E | Fafa and Ancient Mathematics | Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.
An Ahmes arithmetic expression can be defined as:
- "$d$" is an Ahmes arithmetic e... | We can represent the arithmetic expression as a binary tree where: each leaf node is a digit. each non-leaf node is an operator and the left and right subtrees are the operands. To maximize the value of the sub-expression represented by a subtree rooted at $v$, we will either: put a plus (+) operator at $v$, and maximi... | [
"dfs and similar",
"dp",
"trees"
] | 2,300 | null |
935 | F | Fafa and Array | Fafa has an array $A$ of $n$ positive integers, the function $f(A)$ is defined as $\textstyle{\sum_{i=1}^{n-1}|a_{i}-a_{i+1}|}$. He wants to do $q$ queries of two types:
- $1 l r x$ — find the maximum possible value of $f(A)$, if $x$ is to be added to one element in the range $[l, r]$. You can choose to which element ... | Let's have a look at the relation of each element $a_{i}$ with its adjacent elements. Without loss of generality, assume $a_{i}$ has two adjacent elements $b_{i}$ and $c_{i}$ where $b_{i} \le c_{i}$. One of the following cases will hold for $a_{i}$, $b_{i}$ and $c_{i}$: $a_{i} \ge b_{i}$ and $a_{i} \ge c_{i}$. $a... | [
"data structures",
"greedy"
] | 2,600 | null |
936 | A | Save Energy! | Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after $k$ minutes after turning on.
During cooking, Julia goes to the kitchen every $d$ minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. T... | There are repeated segments in the cooking process, that are between two consecutive moments, when Julia turns the stove on. Let's call such segment a period. Consider two cases: If $k \le d$, when Julia comes, the stove is always off, that means $period = d$. In other case Julia comes to the kitchen $p$ times betwee... | [
"binary search",
"implementation",
"math"
] | 1,700 | null |
936 | B | Sleepy Game | Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of $n$ vertices and $m$ edges. One of the vertices contains a chip. Initially the chip is located at vertex $s$. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who c... | Note that the answer is sequence of adjacent vertices of even length such that the last vertex of this sequence has no outgoing edges. Build state graph as follows: State is pair $(v, parity)$, where $v$ is vertex of initial graph and $parity$ is parity of count of vertices on path from $s$ to $v$. For every edge $uv$ ... | [
"dfs and similar",
"dp",
"games",
"graphs"
] | 2,100 | null |
936 | C | Lock Puzzle | Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock... | The answer is <<NO>> only in the case when multisets of letters in $s$ and $t$ differ. In all other cases there is a solution. Let's construct the solution uses $\textstyle{\frac{5}{2}}n$ operations. To do that, you need to <<add>> two symbols to current already built substring using five operations. You can do it, for... | [
"constructive algorithms",
"implementation",
"strings"
] | 2,300 | null |
936 | D | World of Tank | Vitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that h... | At first arrange a pair of facts: If there is a path which doesn't contain blowed cell you can easily convert it to path which does. So it's enough to check such paths to determine answer. Tank can accumulate shots when it moves without turns. In other words: consider tank makes 100 steps without turns and shots, so le... | [
"dp",
"greedy"
] | 3,000 | null |
936 | E | Iqea | Gridland is placed on infinite grid and has a shape of figure consisting of cells. Every cell of Gridland is a city. Two cities that are placed in adjacent cells are connected by the road of length $1$. It's possible to get from any city to any other city using roads. The \underline{distance} between two cities is the ... | Let's cut the figure into strips of consecutive cells which lie in the same column. Consider strips as vertices. Connect two vertices by an edge if their strips have common edge. It can be proved that resulting graph is a tree. Consider two cells (x_a, y_a) and (x_b, y_b). Cell (x_a, y_a) lies on strip v_a, cell (x_b, ... | [
"data structures",
"dfs and similar",
"divide and conquer",
"dsu",
"shortest paths",
"trees"
] | 3,400 | null |
937 | A | Olympiad | The recent All-Berland Olympiad in Informatics featured $n$ participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
- At least one participant should get a dipl... | Drop all participants with zero points. Then the answer is simply the number of distinct points among the remaining participants. | [
"implementation",
"sortings"
] | 800 | null |
937 | B | Vile Grasshoppers | The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from $2$ to $y$. Some of them (more precise, from $2$ to $p$) are occupied by tiny vile grasshoppers which you're at war with. These gr... | The first observation is that the optimal branch shouldn't be divisible by anything in range $[2..p]$. Let us decrease $y$ until its minimal divisor (other than one) is greater than $p$. Why does this approach work? Note that the the nearest prime less or equal to $y$ is valid. At the same time the prime gap of numbers... | [
"brute force",
"math",
"number theory"
] | 1,400 | null |
938 | A | Word Correction | Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two \textbf{consecutive} vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are t... | Iterate over the string, output only consonants and vowels which don't have a vowel before them. | [
"implementation"
] | 800 | "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst string V = \"aeiouy\";\n\nbool vowel(char c)\n{\n\treturn V.find(c) != -1;\n}\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tcout << s[0];\n\tfor(int i = 1; i < n; i++)\n\t\tif (!vowel(s[i - 1]) || !vowel(s[i]))\n\t\t\tcout << s[i];\n\tcout... |
938 | B | Run For Your Prize | You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show $n$ prizes are located on a straight line. $i$-th prize is located at position $a_{i}$. Positions of all prizes are distinct. You start at position $1$, your friend — at position $10^{6}$ (and there is no prize in any of ... | You can find the total time with the knowledge of the prefix length. The final formula is $\operatorname*{min}(a_{n}-1,10^{6}-a_{1},\operatorname*{min}_{i=1}^{n-1}(\operatorname*{max}(a_{i}-1,10^{6}-a_{i+1})))$. | [
"brute force",
"greedy"
] | 1,100 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e7;\n\nint n;\nvector<int> pos;\n\nint main() {\n\tscanf(\"%d\", &n);\n\tpos.resize(n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &pos[i]);\n\t\n\tint ans = INF;\n\t\n\tforn(i, n + 1){\n\t\tint cur = 0;\n... |
938 | C | Constructing Tests | Let's denote a $m$-free matrix as a binary (that is, consisting of only $1$'s and $0$'s) matrix such that every square submatrix of size $m × m$ of this matrix contains at least one zero.
Consider the following problem:
{You are given two integers $n$ and $m$. You have to construct an $m$-free square matrix of size $... | Now that you know the formula, you can iterate over $n$ and find the correct value. The lowest non-zero value you can get for some $n$ is having $k = 2$. So you can estimate $n$ as about $\frac{4{\sqrt{x}}}{3}$. Now let's get $k$ for some fixed $n$. $n^{2}-\lfloor{\frac{n}{k}}\rfloor^{2}=x$ $\to$ $\lfloor{\frac{n}{k}}\... | [
"binary search",
"brute force",
"constructive algorithms"
] | 1,700 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint getSqr(int x){\n\tint l = sqrt(x);\n\tfor (int i = -2; i <= 2; ++i)\n\t\tif (l + i >= 0 && (l + i) * (l + i) == x)\n\t\t\treturn l;\n\treturn -1;\n}\n\nvoid solve(){\n int x;\n\tscanf(\"%d\", &x);\n\tfor (... |
938 | D | Buy a Ticket | Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.
There are $n$ cities in Berland. People can travel between cities using two-directional train routes; there are exactly $m$ routes, $i$-th route can be used to go ... | The function of the path length is not that different from the usual one. You can multiply edge weights by two and run Dijkstra in the following manner. Set $dist_{i} = a_{i}$ for all $i\in[1,n]$ and push these values to heap. When finished, $dist_{i}$ will be equal to the shortest path. | [
"data structures",
"graphs",
"shortest paths"
] | 2,000 | "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int N = 200 * 1000 + 13;\nconst li INF64 = 1e18;\n\nint n, m;\nli a[N];\nvector<pair<int, li>> g[N];\n\nli dist[N];\n\nvoid Dijkstra(){\n\tset<pair<li, int>> q;\n\tforn(i, n){\n\t\t... |
938 | E | Max History | You are given an array $a$ of length $n$. We define $f_{a}$ the following way:
- Initially $f_{a} = 0$, $M = 1$;
- for every $2 ≤ i ≤ n$ if $a_{M} < a_{i}$ then we set $f_{a} = f_{a} + a_{M}$ and then set $M = i$.
Calculate the sum of $f_{a}$ over all $n!$ permutations of the array $a$ modulo $10^{9} + 7$.
Note: two... | It is easy to see that $i$-th element appears in $f_{a}$ if and only if all elements appearing before it in the array are less than it, so if we define $l_{i}$ as the number of elements less than $a_{i}$ the answer will be equal to: $\textstyle\sum_{i=1}^{n}a_{i}\times[\sum_{i=1}^{l_{i}+1}{\binom{l_{i}}{j_{-1}}}\times(... | [
"combinatorics",
"math"
] | 2,300 | "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int MAX_N = 1e6+10;\nconst int mod = 1e9+7;\n\nll a[MAX_N],n,fact[MAX_N],rfact[MAX_N];\nll num(int t){\n return fact[n-t-1]*rfact[n-t+1]%mod;\n}\nmain(){\n scanf(\"%lld\", &n);\n for(ll i=1;i<=n;i++)\n scanf(\"%lld\", &a[i]);\... |
938 | F | Erasing Substrings | You are given a string $s$, initially consisting of $n$ lowercase Latin letters. After that, you perform $k$ operations with it, where $k=\lfloor\log_{2}(n)\rfloor$. During $i$-th operation you \textbf{must} erase some substring of length exactly $2^{i - 1}$ from $s$.
Print the lexicographically minimal string you may... | Let's try to apply some greedy observations. Since each state represents a possible prefix of the resulting string, then among two states $dp[m_{1}][mask_{1}]$ and $dp[m_{2}][mask_{2}]$ such that the lenghts of corresponding prefixes are equal, but the best answers for states are not equal, we don't have to consider th... | [
"bitmasks",
"dp",
"greedy"
] | 2,700 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5043;\nconst int M = 12;\n\nbool dp[N][(1 << M)];\n\ntypedef pair<int, int> pt;\n\n#define x first\n#define y second\n\nvector<int> bits[(1 << M)];\n\nint main()\n{\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\tstring ans;\n\tdp[0][0] = 1;\n\tvector... |
938 | G | Shortest Path Queries | You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times).
There are three types of queries you h... | This is a more complex version of problem G from Educational Round 27. You can find its editorial here. To solve the problem we consider now, you have to use a technique known as dynamic connectivity. Let's build a segment tree over queries: each vertex of the segment tree will contain a list of all edges existing in t... | [
"bitmasks",
"data structures",
"dsu",
"graphs"
] | 2,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<pair<int, int>, int> edge;\n\n#define x first\n#define y second\n\nconst int M = 2000043;\nconst int N = 200043;\nconst int B = 30;\nconst int IDX = 200002;\n\nint* where[M];\nint val[M];\nint st = 0;\n\ninline void rollback(int new_st)\n{\n\twhile(st !=... |
939 | A | Love Triangle | As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are $n$ planes on Earth, numbered from $1$ to $n$, and the plane with number $i$ likes the plane with number $f_{i}$, where $1 ≤ f_{i} ≤ n$ and $f_{i} ≠ i$.
We call a love triangle a situation in wh... | It is enough to check if there is some $i$ such that $f_{ffi} = i$, i. e. f[f[f[i]]] == i. | [
"graphs"
] | 800 | null |
939 | B | Hamster Farm | Dima has a hamsters farm. Soon $N$ hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory ... | The easies way to solve this problem is to find the minimum number of hamsters that can be left on the farm. If Dima byes boxes of the $i$-th type, there are $n\ \mathrm{mod}\ a_{i}$ hamsters left on the farm. So we should find such a type $x$, that the value $n{\mathrm{~mod~}}a_{x}$ is minimum among all $x$; The numbe... | [
"implementation"
] | 1,000 | null |
939 | C | Convenient For Everybody | In distant future on Earth day lasts for $n$ hours and that's why there are $n$ timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from $1$ to $n$ are used, i.e. there is no time "0 hours", instead of it "$n$ hours" is used. When local time in the $1$-st timezone i... | Initially, compute prefix sums: for each $i$ the total number of people in timezones from the first to the $i$-th. Let's loop through all possible starting times of the competition. Each starting time gives as one or two segments of timezones, in which people will compete in the contest. We can easily compute the total... | [
"binary search",
"two pointers"
] | 1,600 | null |
939 | D | Love Rescue | Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.
This story c... | Let's build a graph with 26 vertices representing the 26 letters of English alphabet. When we buy a spell of form $(c_{1}, c_{2})$, add an edge between vertices $c_{1}$ and $c_{2}$. It's easy to see, that it is possible to change a letter $a$ to a letter $b$ if and only if there is a path between corresponding vertices... | [
"dfs and similar",
"dsu",
"graphs",
"greedy",
"strings"
] | 1,600 | null |
939 | E | Maximize! | You are given a multiset $S$ consisting of positive integers (initially empty). There are two kind of queries:
- Add a positive integer to $S$, the newly added integer is not less than any number in it.
- Find a subset $s$ of the set $S$ such that the value ${\mathrm{max}}(s)-{\mathrm{mean}}(s)$ is maximum possible. H... | Let's first prove some lemmas we will use in the solution. Let $a_{0}, ..., a_{n}$ be integers that are at the current moment in $S$, sorted in increasing order. Lemma 1. Let the maximum element in optimal $s$ be $a_{n}$. Then the rest of the elements in $s$ form a prefix of $a$. Proof: let it be wrong. Let's consider ... | [
"binary search",
"greedy",
"ternary search",
"two pointers"
] | 1,800 | null |
939 | F | Cutlet | Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for $2n$ seconds, in particular, it should be fried for $n$ seconds on one side and $n$ seconds on the other side. Arkady has already got a frying pan and turn o... | Let's use dynamic programming approach. Solve the following subproblem: let $t$ be the seconds passed since the start of cooking, and $t_{0}$ seconds among them the cutlet was preparing on the current side; what is the minimum number of flips needed to reach this state? This can be easily computed using answers for sub... | [
"data structures",
"dp"
] | 2,400 | null |
940 | A | Points on the line | We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The \textbf{diameter} of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset ${1, 3, 2, 1}$ i... | It's clear that diameter of the multiset of points equals to difference of coordinates of point with maximum coordinate and point with minimum coordinate. So we can iterate over all possible pairs of maximum and minimum point and check number of remaining points in $O(n)$. This solution works in $O(n^{3})$. Of course, ... | [
"brute force",
"greedy",
"sortings"
] | 1,200 | null |
940 | B | Our Tanya is Crying Out Loud | Right now she actually isn't. But she will be, if you don't solve this problem.
You are given integers $n$, $k$, $A$ and $B$. There is a number $x$, which is initially equal to $n$. You are allowed to perform two types of operations:
- Subtract 1 from $x$. This operation costs you $A$ coins.
- Divide $x$ by $k$. Can ... | If $k = 1$, then answer is obvious, $(n-1)\cdot\,A$, otherwise we will greedily decrease number. During each moment of time we should consider following three cases: If $n < k$, we can only $n - 1$ decrease number by 1, paying $A$ coins each time. It can be done in $O(1)$ using formula. If $n > k$ and $n$ is not divisi... | [
"dp",
"greedy"
] | 1,400 | null |
940 | C | Phone Numbers | And where the are the phone numbers?
You are given a string $s$ consisting of lowercase English letters and an integer $k$. Find the lexicographically smallest string $t$ of length $k$, such that its set of letters is a subset of the set of letters of $s$ and $s$ is lexicographically smaller than $t$.
It's guaranteed... | Consider $2$ cases: If $n < k$ we should simply add $k - n$ minimum symbols from $s$. If $n \ge k$ we need to replace all symbols in the suffix of first $k$ symbols of string consisting of largest symbols to smallest symbols and next symbol before this suffix replace with next symbol that exists in the string. Comple... | [
"constructive algorithms",
"implementation",
"strings"
] | 1,500 | null |
940 | D | Alena And The Heater | "We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."
"Little Alena got an array as a birthday present$...$"
The array $b$ of length $n$ is obtained from the array $a$ of length $n$ and two integers $l$ and $r$ ($l ≤ r$) using the following procedur... | Notice, that constraints on ${\mathit{l}}_{}^{}$ and ${\boldsymbol{J}}^{*}$ generates only sequences $b_{i}$ that equals 00001, 00000, 11110, 11111. 00000 on positions $[i;i+4]$ means that $l\leq\operatorname*{max}_{i\leq j\leq i+4}a_{j}$. 00001 on positions $[i;i+4]$ means that $l\geq\operatorname*{max}_{i\leq j\leq i... | [
"binary search",
"implementation"
] | 1,600 | null |
940 | E | Cashback | Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.
You are given an array $a$ of length $n$ and an integer $c$.
The value of some array $b$ of length $k$ is the sum of its elements except for the $\left\lfloor{\frac{k}{x_{-}}}\right\rfloor$ smallest. For e... | At first let's solve this problem with $O(n^{2}\log{n})$ complexity. It can be done using dynamic programming. Let $d p_{i}$ be minimum cost of splitting prefix with length $i$.$d p_{0}=0$, $d p_{i}=\operatorname*{min}_{j<i}d p_{j}+c o s t_{j+1,i}$ where $c o s t_{l,r}$ is a cost of $\left(r-l+1\right)-\left.{\bigl\lfl... | [
"data structures",
"dp",
"greedy",
"math"
] | 2,000 | null |
940 | F | Machine Learning | You come home and fell some unpleasant smell. Where is it coming from?
You are given an array $a$. You have to answer the following queries:
- You are given two integers $l$ and $r$. Let $c_{i}$ be the number of occurrences of $i$ in $a_{l: r}$, where $a_{l: r}$ is the subarray of $a$ from $l$-th element to $r$-th in... | At first let's find out minimum length of array, such that answer for it is $c$. For it on this segment there should be a number that has one occurrence, some number that has two occurrences, etc. Length of this segment will be $1\ +\ 2\ +\ 3\ +\ \cdots\ +c\ =\ {\frac{c(c+1)}{2}}$. That's why answer won't exceed $2\cdo... | [
"brute force",
"data structures"
] | 2,600 | null |
946 | A | Partition | You are given a sequence $a$ consisting of $n$ integers. You may partition this sequence into two sequences $b$ and $c$ in such a way that every element belongs exactly to one of these sequences.
Let $B$ be the sum of elements belonging to $b$, and $C$ be the sum of elements belonging to $c$ (if some of these sequence... | The answer for this problem can be calculated by the next simple formula: $\sum_{i=1}^{n}\left|a_{i}\right|$, where $|a_{i}|$ is the absolute value of $a_{i}$. | [
"greedy"
] | 800 | null |
946 | B | Weird Subtraction Process | You have two variables $a$ and $b$. Consider the following sequence of actions performed with these variables:
- If $a = 0$ or $b = 0$, end the process. Otherwise, go to step $2$;
- If $a ≥ 2·b$, then set the value of $a$ to $a - 2·b$, and repeat step $1$. Otherwise, go to step $3$;
- If $b ≥ 2·a$, then set the value ... | The answer can be calculated very easy by Euclid algorithm (which is described in the problem statement), but all subtractions will be replaced by taking by modulo. | [
"math",
"number theory"
] | 1,100 | null |
946 | C | String Transformation | You are given a string $s$ consisting of $|s|$ small english letters.
In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.
Your target is to make some number... | The problem can be solved by the next greedy algorithm. At first we need to store the last character of the alphabet we haven't obtained, for example, in variable $c$ (initially it will be equal to 'a'). Then we will just iterate over all characters of the string from left to right and if the current character of the s... | [
"greedy",
"strings"
] | 1,300 | null |
946 | D | Timetable | Ivan is a student at Berland State University (BSU). There are $n$ days in Berland week, and each of these days Ivan might have some classes at the university.
There are $m$ working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during $i$... | The problem can be solved in the following dynamic programming manner. Let $dp[i][j]$ be the smallest number of hours Ivan can spend in university in the first $i$ days while having $j$ lessons skipped. To calculate it we can store $mn[i][j]$ - minimal number of hours Ivan is required to spend in the $i$-th day so that... | [
"dp"
] | 1,800 | null |
946 | E | Largest Beautiful Number | Yes, that's another problem with definition of "beautiful" numbers.
Let's call a positive integer $x$ beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, $4242$ is a beautiful number, sin... | This is pretty typical problem on greedy construction: you are asked to build lexicographically maximal string. In the majority of cases it's done like this. Imagine you've built some prefix of length $i$ with all numbers equal to the prefix of length $i$ of the original string. You are also sure there exists some suff... | [
"greedy",
"implementation"
] | 2,200 | null |
946 | F | Fibonacci String Subsequences | You are given a binary string $s$ (each character of this string is either 0 or 1).
Let's denote the cost of string $t$ as the number of occurences of $s$ in $t$. For example, if $s$ is 11 and $t$ is 111011, then the cost of $t$ is $3$.
Let's also denote the Fibonacci strings sequence as follows:
- $F(0)$ is 0;
- $F... | If $F(x)$ was not really large, then we could run the following dynamic programming solution: Let $dp[i][j]$ be the number of ways to process first $i$ characters of $F(x)$ so that the suffix of the subsequence of length $j$ matches the prefix of $s$ with length $j$. This is not really different from a usual approach w... | [
"combinatorics",
"dp",
"matrices"
] | 2,400 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> vec;\ntypedef vector<vec> mat;\n\nconst int MOD = 1000 * 1000 * 1000 + 7;\n\nint add(int x, int y)\n{\n\tint z = x + y;\n\twhile(z >= MOD)\n\t\tz -= MOD;\n\treturn z;\t\n}\n\nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n\nvec mul(co... |
946 | G | Almost Increasing Array | We call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it).
You are given an array $a$ consisting of $n$ elements. You are allowed to replace any element with any integer nu... | If the problem was to make the array strictly increasing, then we could use the following approach: for every element subtract its index from it, find the longest non-decreasing subsequence, and change every element not belonging to this sequence. In this problem we can use a similar technique. Let's iterate on the ele... | [
"data structures",
"dp"
] | 2,500 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmap<int, int> comp;\n\nvoid compress(const vector<int>& a)\n{\n\tvector<int> z;\n\tfor(int i = 0; i < a.size(); i++)\n\t{\n\t\tz.push_back(a[i] - i);\n\t\tz.push_back(a[i] - i + 1);\n\t}\n\tsort(z.begin(), z.end());\n\tz.erase(unique(z.begin(), z.end()), z.end());\n\... |
948 | A | Protect Sheep | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.
The pasture is a rectangle consisting of $R × C$ cells. Each cell is either empty, contains a sheep, a wolf or a d... | Suppose that there is a wolf and a sheep in adjacent cells. It is obvious that in this case, the answer "NO" - this particular wolf can always attack this sheep. Otherwise, the answer is always "YES". The simplest way of protecting all sheep is to place a dog in every empty cell. Then no wolf can move and all sheep are... | [
"brute force",
"dfs and similar",
"graphs",
"implementation"
] | 900 | null |
949 | A | Zebras | Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences o... | Simple greedy works here. Let's go from left to right and assign each element to some subsequence. At each moment we have two types of already built subsequences: zebras ("0", "010", "01010", ...) and "almost zebras" ("01", "0101", "010101"). If next element of the string is '1' we should add it to some zebra making it... | [
"greedy"
] | 1,600 | null |
949 | B | A Leapfrog in the Array | Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.
Let's consider that i... | In odd position $p$ value $\textstyle{\frac{p+1}{2}}$ will be set. For even position $p$ let's find out position from which value has arrived and iterate over such position until we will arrive to odd position for which we know answer. At the moment of jumping to cell $p$ there are $\textstyle{\frac{p}{2}}$ elements to... | [
"constructive algorithms",
"math"
] | 1,700 | null |
949 | C | Data Center Maintenance | BigData Inc. is a corporation that has $n$ data centers indexed from $1$ to $n$ that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).
Main feature of services offered by BigData Inc. is the access availability guarantee even under ... | Formally you are given a properly colored graph and you are asked to find out size of smallest non-empty subset such that after addition $1$ modulo $h$ to colors of vertices in this subset coloring will remain proper. Let's build a directed graph with $n$ vertices and edge from $u$ to $v$ iff $u$ and $v$ are connected ... | [
"dfs and similar",
"graphs"
] | 1,900 | null |
949 | D | Curfew | Instructors of Some Informatics School make students go to bed.
The house contains $n$ rooms, in each room exactly $b$ students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from $1$ to $n$. In... | Let's solve the problem in case when there is only one instructor (which moves from left to right and the only goal is to minimize number of bad rooms) I claim, that the following greedy works: Move through rooms from left to right If there are too many students inside room, send the excess students to the next room If... | [
"binary search",
"brute force",
"greedy",
"sortings"
] | 2,300 | null |
949 | E | Binary Cards | It is never too late to play the fancy "Binary Cards" game!
There is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either $2^{k}$ or $ - 2^{k}$ for some integer $k ≥ 0$. There is an infinite amou... | There are two observations required to solve this problem: You don't have to take two cards with same number. If you took two cards with number $x$ you can take card with number $2x$ and card with number $x$ and answer will remain correct. If you took card with number $x$ you don't have to take card with number $- x$. ... | [
"brute force"
] | 2,700 | null |
949 | F | Astronomy | \url{CDN_BASE_URL/571a7070e5784ace821a58b11e4350fb} | Let's shuffle lines randomly. Select some 4 points and find their intersection point. If it's not integer or is not in bounding box it's definitely not an answer. Otherwise let's check it. Iterate over points and check if there is another point on the line that going through answer and this point. To check it we need t... | [
"geometry",
"probabilities"
] | 3,300 | null |
950 | A | Left-handers, Right-handers and Ambidexters | You are at a water bowling training. There are $l$ people who play with their left hand, $r$ people, who play with their right hand, and $a$ ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and ... | Iterate over size of the team. Now you know how many players should play with left hand, but are not left-handed (because there are no so much left-handed players). The same with right hand. Just check if sum of these values is not more than number of ambidexters. | [
"implementation",
"math"
] | 800 | null |
950 | B | Intercepted Message | Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.
Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred... | Let's define $\mathbf{{\mu}_{i}}$ and $p_{i}$ as sums of first $\overline{{i}}$ elements of $\textstyle{\bar{\mathbf{Z}}}$ and $\mathbf{\mathbf{y}}$ ($s_{0}=0$, $s_{i}=s_{i-1}+x_{i}$, $p_{0}=0$, $p_{i}=p_{i-1}+y_{i}$). ${\mathcal{L}}_{l_{1}},{\mathcal{L}}_{l_{1}+1},\cdot\cdot,{\mathcal{L}}_{r_{1}}$ and $y l_{2},y l_{2}... | [
"greedy",
"implementation"
] | 1,100 | null |
954 | A | Diagonal Walking | Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an... | Let's iterate over all characters of the string from left to right (excluding last character). Suppose $i$ is a position of the current element of the string. If $s_{i} \neq s_{i + 1}$, increase answer by $1$ and increase $i$ by $2$, else just increase $i$ by $1$. | [
"implementation"
] | 800 | null |
954 | B | String Typing | You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to type this string using your keyboard.
Initially, you have an empty string. Until you type the whole string, you may perform the following operation:
- add a character to the end of the string.
Besides, \textbf{at most once} you may per... | Let's consider $s[i; j)$ as a substring of string $s$ from position $i$ to position $j$ ($j$ is not included). Let's iterate over all lenghts of the copied prefix from $\textstyle{\left|{\frac{n}{2}}\right|}$ to 0 inclusive, and then if $s[0; len) = s[len; 2 \cdot len)$ then answer will be $min(n, n - len + 1)$ and ite... | [
"implementation",
"strings"
] | 1,400 | null |
954 | C | Matrix Walk | There is a matrix $A$ of size $x × y$ filled with integers. For every $i\in[1...x]$, $j\in[1..y]$ $A_{i, j} = y(i - 1) + j$. Obviously, every integer from $[1..xy]$ occurs exactly once in this matrix.
You have traversed some path in this matrix. Your path can be described as a sequence of visited cells $a_{1}$, $a_{2}... | You can notice that moves of kind $(i - 1, j)$ and $(i + 1, j)$ are changing value $x$ to $x - m$ and $x + m$. Thus, you can determine $m$ by checking adjacent nodes in the path. The answer is YES if there are one or zero distinct values of differences not counting difference of $1$. You can also set $n$ to arbitrary b... | [
"implementation"
] | 1,700 | null |
954 | D | Fight Against Traffic | Little town Nsk consists of $n$ junctions connected by $m$ bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible... | Let's use bfs to calculate the smallest distances to all vertices from the vertex $s$ and from the vertex $t$. These will be $d_{s}[i]$ and $d_{t}[i]$ for all $i$. $d_{s}[t] = d_{t}[s] = D$ is the the current smallest distance between $s$ and $t$. What you need is to iterate over all pairs $(u, v)$ and check if the edg... | [
"dfs and similar",
"graphs",
"shortest paths"
] | 1,600 | null |
954 | E | Water Taps | Consider a system of $n$ water taps all pouring water into the same container. The $i$-th water tap can be set to deliver any amount of water from $0$ to $a_{i}$ ml per second (this amount may be a real number). The water delivered by $i$-th tap has temperature $t_{i}$.
If for every $i\in[1,n]$ you set $i$-th tap to d... | The following greedy strategy work. Let's turn all the taps at full power. If total temperature is greater than $T$ then we would like to decrease power on some taps with higher temperature. We want to decrease as low power as possible, so we should prioritize taps with the highest temperature. Sort all taps by tempera... | [
"binary search",
"greedy",
"sortings"
] | 2,000 | null |
954 | F | Runner's Problem | You are running through a rectangular field. This field can be represented as a matrix with $3$ rows and $m$ columns. $(i, j)$ denotes a cell belonging to $i$-th row and $j$-th column.
You start in $(2, 1)$ and have to end your path in $(2, m)$. From the cell $(i, j)$ you may advance to:
- $(i - 1, j + 1)$ — only if ... | There is a simple dynamic programming solution that works in $O(m)$. Let's try to improve it. Firstly, if there are no obstacles in some column $i$ and we have calculated the number of paths to every cell of the previous column, then we may get the values in column $i$ by multiplying the vector of values in column $i -... | [
"dp",
"matrices",
"sortings"
] | 2,100 | null |
954 | G | Castle Defense | Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into $n$ sections. At this moment there are exactly $a_{i}$ archers located... | Firstly, if we may obtain reliability at least $x$, then we may obtain reliability not less than $x - 1$ with the same number of archers. So we may use binary search and check whether we may obtain reliability at least $x$. How can we check it? Let's find the leftmost section such that its defense level is less than $x... | [
"binary search",
"data structures",
"greedy",
"two pointers"
] | 2,000 | null |
954 | H | Path Counting | You are given a rooted tree. Let's denote $d(x)$ as depth of node $x$: depth of the root is $1$, depth of any other node $x$ is $d(y) + 1$, where $y$ is a parent of $x$.
The tree has the following property: every node $x$ with $d(x) = i$ has exactly $a_{i}$ children. Maximum possible depth of a node is $n$, and $a_{n}... | At first when we read the problem, a simple solution comes to our mind, take a look at the LCA (Lowest Common Ancestor) of that starting and ending vertices of the path and then use combinatorics to calculate the number of the paths, but after trying to implement this or solve this on paper it doesn't seem to be easy a... | [
"combinatorics",
"dp"
] | 2,500 | null |
954 | I | Yet Another String Matching Problem | Suppose you have two strings $s$ and $t$, and their length is equal. You may perform the following operation any number of times: choose two different characters $c_{1}$ and $c_{2}$, and replace every occurence of $c_{1}$ in both strings with $c_{2}$. Let's denote the distance between strings $s$ and $t$ as the minimum... | Unfortunately, it seems we failed to eliminate bitset solutions. The approach in our model solution is the following: Firstly, let's try to find some "naive" solution for calculating the distance between two strings. We may build an undirected graph where vertices represent letters, and edges represent that one letter ... | [
"fft",
"math"
] | 2,200 | null |
955 | A | Feed the cat | After waking up at $hh$:$mm$, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is $H$ points, moreover each minute without food increases his hunger by $D$ points.
At any time Andrew can visit the store where tasty buns are... | It's optimal to buy buns either right after waking up or at $20$:$00$ (if possible) because between the awakening and $20$:$00$ cost doesn't change but cat's hunger does. There was one extra case when Andrew wakes up after $20$:$00$ and has only one possible option of buying everything since he cannot turn back time. | [
"greedy",
"math"
] | 1,100 | hh, mm = map(int, input().split())
H, D, cost, nutr = map(int, input().split())
hh = 60 * hh + mm
if hh >= 1200:
print('{:.4f}'.format((H + nutr - 1) // nutr * cost * 0.8))
else:
print('{:.4f}'.format(min((H + nutr - 1) // nutr * cost, (H + (1200 - hh) * D + nutr - 1) // nutr * cost * 0.8))) |
955 | B | Not simply beatiful strings | Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of $a$-s and others — a ... | Since order of letters in adorable strings doesn't matter, it doesn't matter in the initial string as well. Let $d$ be the number of distinct letters in $s$. Consider the following cases one after another: If $|s| < 4$ answer is <<No>> since lengths of adorable strings cannot be less than two; If $d$ is more than $4$ a... | [
"implementation"
] | 1,400 | from collections import Counter
d = Counter(input())
if sum(d.values()) < 4 or len(d) > 4 or len(d) == 1:
print('No')
elif len(d) >= 3:
print('Yes')
elif any(d[k] == 1 for k in d):
print('No')
else:
print('Yes') |
955 | C | Sad powers | You're given $Q$ queries of the form $(L, R)$.
For each query you have to find the number of such $x$ that $L ≤ x ≤ R$ and there exist integer numbers $a > 0$, $p > 1$ such that $x = a^{p}$. | Let's fix some power $p$. It's obvious that there are no more than $10^{\frac{13}{p}}$ numbers $x$ such that $x^{p}$ does not exceed $10^{18}$. At the same time, only for $p = 2$ this amoung is relatively huge; for all other $p \ge 3$ the total amount of such numbers will be of the order of $10^{6}$. Let's then gener... | [
"binary search",
"math",
"number theory"
] | 2,100 | #define _CRT_SECURE_NO_WARNINGS
//#pragma GCC optimize("Ofast, unroll-loops")
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <unordered_set>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include ... |
955 | D | Scissors | Jenya has recently acquired quite a useful tool — $k$-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length $k$ from an arbitrary string $s$ (its length should be at least $2·k$ in order to perform this operation) and concatenating them afterwards (preserving th... | Denote $lpos(x)$ - the minimum index in $s$ that prefix of $t$ of length $x$ might start at, provided $lpos(x) + x \ge k$ (so this prefix can be enclosed in some $k$-substring of $s$ as a suffix) or $- 1$ if there are none. Denote $rpos(x)$ in the same manner - the maximum index in $s$ that suffix of $t$ of length $x... | [
"brute force",
"strings"
] | 2,600 | #define _CRT_SECURE_NO_WARNINGS
//#pragma GCC optimize("Ofast, unroll-loops")
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <unordered_set>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include ... |
955 | E | Icicles | Andrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back!
At the moment the refugee is inside an icy cave with $n$ icicles dangling from the ceiling located in integer coordinates numbered from $1$ to $n$. The distance between floor and the $i$-th icicle is equal to $a_{i}$.
Andrew is ... | Fix some point $T$ and launch the wave. Icicle at $i$ will reach the floor in $f_{T}(i) = a_{i} + |T - i|$ seconds. Krakozyabra will definitely stop at minimum icicle $j$ such that $f_{T}(j) < j$ and wait for something to the left of it to fall. Note that some icicle to the right of $j$ might also fall earlier than $j$... | [] | 2,900 | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <unordered_set>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <cassert>
#include <functional>
#include <queue>
#include <numeric>
#include <bitset>
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.