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 ⌀ |
|---|---|---|---|---|---|---|---|
696 | C | PLEASE | As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.
Then at one turn Barney swaps the cup in the middle with a... | It gets tricky when the problem statement says $p$ and $q$ should be coprimes. A wise coder in this situation thinks of a formula to make sure this happens. First of all let's solve the problem if we only want to find the fraction $\overset{p}{q}$. Suppose $dp[i]$ is answer for swapping the cups $i$ times. It's obvious... | [
"combinatorics",
"dp",
"implementation",
"math",
"matrices"
] | 2,000 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
696 | D | Legen... | Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
Initially, happiness level of Nora is $0$. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows $n$ pi... | Build the prefix automaton of these strings (Aho-Corasick). In this automaton every state denotes a string which is prefix of one of given strings (and when we feed characters to it the current state is always the longest of these prefixes that is a suffix of the current string we have fed to it). Building this DFA can... | [
"data structures",
"dp",
"matrices",
"strings"
] | 2,500 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
696 | E | ...Wait for it... | Barney is searching for his dream girl. He lives in NYC. NYC has $n$ junctions numbered from $1$ to $n$ and $n - 1$ roads connecting them. We will consider the NYC as a rooted tree with root being junction $1$. $m$ girls live in NYC, $i$-th of them lives along junction $c_{i}$ and her weight initially equals $i$ pounds... | First of all, for each query of 1st type we can assume $k = 1$ (because we can perform this query $k$ times, it doesn't differ). Consider this problem: there are only queries of type 1. For solving this problem we can use heavy-light decomposition. If for a vertex $v$ of the tree we denote $a_{v}$ as the weight of the ... | [
"data structures",
"dsu",
"trees"
] | 3,000 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
696 | F | ...Dary! | Barney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of $n$ points. Like most of castles in Demonata worlds, this castle has no ceiling.
Barney and Lyanna have an escape plan, but it requires... | In the first thoughts you see that there's definitely a binary search needed (on $r$). Only problem is checking if there are such two points fulfilling conditions with radius $r$. For each edge, we can shift it $r$ units inside the polygon (parallel to this edge). The only points that can see the line coinciding the li... | [
"binary search",
"geometry",
"two pointers"
] | 3,300 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
697 | A | Pineapple Incident | Ted has a pineapple. This pineapple is able to bark like a bulldog! At time $t$ (in seconds) it barks for the first time. Then every $s$ seconds after it, it barks twice with $1$ second interval. Thus it barks at times $t$, $t + s$, $t + s + 1$, $t + 2s$, $t + 2s + 1$, etc.
Barney woke up in the morning and wants to e... | You should check two cases for YES: $x mod s = t mod s$ and $t \le x$ $x mod s = (t + 1) mod s$ and $t + 1 < x$ Time Complexity: $O(1)$ | [
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
697 | B | Barnicle | Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.
Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance ... | Nothing special, right? just find the position of letters . and e with string searching methods (like .find) and do the rest. Time Complexity: ${\cal O}(n)$ | [
"brute force",
"implementation",
"math",
"strings"
] | 1,400 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
698 | A | Vacations | Vasya has $n$ days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this $n$ days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the $i$-th day there are four options:
- on this day the gym is closed ... | This problem can be solved with dynamic programming. Let's solve the opposite problem and find the maximum number of days which Vasya will not have a rest. We need o use two-dimensional array $d$, where $d[i][j]$ equals to the maximum number of days, which Vasya will not have a rest, if $i$ days passed and $j$ equals t... | [
"dp"
] | 1,400 | null |
698 | B | Fix a Tree | A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with $n$ vertices, numbered $1$ through $n$. There are many ways to represent such a tree. One way is to create an array with $n$ integers $p_{1}, p_{2}, ..., p_{n}$, where $p_{i}$ denotes a parent of vertex $i$ (here, for ... | One can easily see that given sequence describes a functional graph, thus a directed graph with edges going from $i$ to $a_{i}$ for every $i$. This graph represents a set of cycles and each cycle vertex is a root of its own tree (possibly consisting of one vertex). Picture above shows an example of a functional graph. ... | [
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 1,700 | null |
699 | A | Launch of Collider | There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. $n$ particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis... | To solve this problem it is enough to look at all pairs of adjacent particles such that the left particle will move to the right and the right particle will move to the left. If there is no such pair the answer is -1. Otherwise, let's iterate through the particles from the left to the right. If the particle $i$ will mo... | [
"implementation"
] | 1,000 | null |
699 | B | One Bomb | You are given a description of a depot. It is a rectangular checkered field of $n × m$ size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*").
You have one bomb. If you lay the bomb at the cell $(x, y)$, then after triggering it will wipe out all walls in the row $x$ and all walls in the c... | To solve this problem we need to calculate two arrays $V[]$ and $G[]$, where $V[j]$ must be equal to the number of walls in the column number $j$ and $G[i]$ must be equal to the number of walls in the row number $i$. Also let's store the total number of walls in the variable $cur$. Now we need to look over the cells. L... | [
"implementation"
] | 1,400 | null |
700 | A | As Fast As Possible | On vacations $n$ pupils decided to go on excursion and gather all together. They need to overcome the path with the length $l$ meters. Each of the pupils will go with the speed equal to $v_{1}$. To get to the excursion quickly, it was decided to rent a bus, which has seats for $k$ people (it means that it can't fit mor... | This problem can be solved with formula or with help of the binary search. Let's describe the solution with binary search on the answer. If the target function of the binary search returns $true$ we need to move in mid the right end of the search, else we need to move in mid the left end of the search. The target funct... | [
"binary search",
"math"
] | 1,900 | null |
700 | B | Connecting Universities | Treeland is a country in which there are $n$ towns connected by $n - 1$ two-way road such that it's possible to get from any town to any other town.
In Treeland there are $2k$ universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The... | Let's root a tree with vertex $1$ by single DFS and by the way find two values for every vertex $v$: $lv$ - length of the edge that leads from parent of $v$ to vertex $v$; $sv$ - the number of universities in the subtree of vertex $v$ (including $v$ itself). Consider any optimal solution, i.e. such solution that the to... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,800 | null |
701 | A | Cards | There are $n$ cards ($n$ is \textbf{even}) in the deck. Each card has a positive integer written on it. $n / 2$ people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the ... | Because of it is guaranteed, that the answer always exists, we need to sort all cards in non-descending order of the numbers, which are written on them. Then we need to give to the first player the first and the last card from the sorted array, give to the second player the second and the penultimate cards and so on. | [
"greedy",
"implementation"
] | 800 | null |
701 | B | Cells Not Under Attack | Vasya has the square chessboard of size $n × n$ and $m$ rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a... | To solve this problem we will store two sets - the set of the verticals, in which there is at least one rook, and the set of the horizontals, in which there is at least one rook. We need to iterate through the rooks in the order of we put them on the board and calculate the number of the cells under attack, after put e... | [
"data structures",
"math"
] | 1,200 | null |
701 | C | They Are Everywhere | Sergei B., the young coach of Pokemons, has found the big house which consists of $n$ flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number $1$ i... | At first let's find all different letters, which exist in the given string. It can be done with help of the array with letters or with help of the set. Then we need to use the array $len$, where $len[i]$ equals to minimal length of the substring, which ends in the position $i$ and contains all different letters from th... | [
"binary search",
"strings",
"two pointers"
] | 1,500 | null |
702 | A | Maximum Increase | You are given array consisting of $n$ integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray \textbf{strictly greater} than previous. | Let's iterate through the given array from the left to the right and store in the variable $cur$ the length of the current increasing subarray. If the current element is more than the previous we need to increase $cur$ on one. In the other case we need to update the answer with the value of $cur$ and put in $cur$ 1, be... | [
"dp",
"greedy",
"implementation"
] | 800 | null |
702 | B | Powers of Two | You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Find the number of pairs of indexes $i, j$ ($i < j$) that $a_{i} + a_{j}$ is a power of $2$ (i. e. some integer $x$ exists so that $a_{i} + a_{j} = 2^{x}$). | To solve this problem we need to use map $cnt$ and store in this map how many times every integer appears in the given array. Then we need to iterate through all given numbers with variable $i$. Let the current number is equal to $a_{i}$. For this number we need to iterate on all possible powers of 2 (the number of the... | [
"brute force",
"data structures",
"implementation",
"math"
] | 1,500 | null |
702 | C | Cellular Network | You are given $n$ points on the straight line — the positions ($x$-coordinates) of the cities and $m$ points on the same line — the positions ($x$-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than ... | At first store coordinates of all towers in set $towers$. Then let's look through all cities. Let the current city be located in the point $cur$. Let $it = towers.lower_{bound}(cur)$. Then if $it$ is not equal to the end of the set we put in the variable $dist$ the value $( * it - cur)$ - the distance to the nearest to... | [
"binary search",
"implementation",
"two pointers"
] | 1,500 | null |
702 | D | Road to Post Office | Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to $d$ kilometers.
Vasiliy's car is not new — it breaks after driven every $k$ kilometers and Vasiliy needs $t$ seconds to repair it. After repairing his car Vasiliy can drive again (but after $k$ kilometers ... | To solve this problem we need to analyze some cases. If $d \le k$ then Vasiliy can ride car all road without breaking, so the answer is $d * a$. If $t + k * a > k * b$ (i. e. it is better to do not repair the car), Vasiliy must ride car the first $k$ kilometers and then walks on foot, so the answer is $k * a + (d - k... | [
"math"
] | 1,900 | null |
702 | E | Analysis of Pathes in Functional Graph | You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from $0$ to $n - 1$.
Graph is given as the array $f_{0}, f_{1}, ..., f_{n - 1}$, where $f_{i}$ — the number of vertex to which goes the only arc from the vertex $i$. Besides you are give... | This problem can be solved with help of the binary exponentiation. Let the $f_{r}[u]$ is a structure, which for the vertex $u$ store the information about the path from this vertex with length equals to $r$. The information which we need: $f_{r}[u].to$ - the number of vertex, in which ends the path with length $r$ from... | [
"data structures",
"graphs"
] | 2,100 | null |
703 | A | Mishka and Game | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds $n$ is defined.... | In this problem you had to do use the following algo. If Mishka wins Chris in the current round, then increase variable $countM$ by 1. Otherwise (if Chris wins Mishka) increase variable $countC$. After that you had to compare this values and print the answer. | [
"implementation"
] | 800 | null |
703 | B | Mishka and trip | Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.
Here are some interesting facts about XXX:
- XXX consists of $n$ cities, $k$ of whose (just imagine!) are capital cities.
- All of cities in ... | Let's look at the first capital. Note that the total cost of the outgoing roads is $c[id_{1}] \cdot (sum - c[id_{1}])$, where $sum$ - summary beauty of all cities. Thus iterating through the capitals we can count the summary cost of roads between capitals and all the other cities. But don't forget that in this case w... | [
"implementation",
"math"
] | 1,400 | null |
703 | C | Chris and Road | And while Mishka is enjoying her trip...
Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.
Once walking with his friend, John gave Chris the following proble... | Imagine that the bus stands still and we move "to the right" with a constant speed $v$. Then it's not hard to see that movement along the line $y = (u / v) \cdot (x - v \cdot t_{0})$ is optimal, where $t_{0}$ - time in which we begin our movement. In this way answer is $t = t_{0} + (w / u)$. If $t_{0} = 0$, then we... | [
"geometry",
"implementation"
] | 2,100 | null |
703 | D | Mishka and Interesting sum | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of $n$ elements!
Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. ... | Easy to see, that the answer for query is XOR-sum of all elements in the segment xored with XOR-sum of distinct elements in the segment. XOR-sum of all numbers we can find in $O(1)$ using partial sums. As for the XOR-sum of distinct numbers... Let's solve easier problem. Let the queries be like "find the number of dist... | [
"data structures"
] | 2,100 | null |
703 | E | Mishka and Divisors | After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem.
You are given integer $k$ and array $a_{1}, a_{2}, ..., a_{n}$ of $n$ integers. You are to find \textbf{non-empty} subseque... | Let's use dp to solve this problem. Suppose $dp[i][d]$ is the minimal number of elements on prefix of size $i$, that their product is divisible by $d$. It's easy to see that $dp[i][d] = min(dp[i - 1][d], dp[i - 1][d / gcd(d, a_{i})] + 1)$. That is so because it's optimal to take as much divisors of $a_{i}$ as possible.... | [
"dp",
"number theory"
] | 2,600 | null |
704 | A | Thor | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are $n$ applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
$q$ events are ... | Consider a queue $e$ for every application and also a queue $Q$ for the notification bar. When an event of the first type happens, increase the number of unread notifications by 1 and push pair $(i, x)$ to $Q$ where $i$ is the index of this event among events of the first type, and also push number $i$ to queue $e[x]$.... | [
"brute force",
"data structures",
"implementation"
] | 1,600 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
704 | B | Ant Man | Scott Lang is at war with Darren Cross. There are $n$ chairs in a hall where they are, numbered with $1, 2, ..., n$ from left to right. The $i$-th chair is located at coordinate $x_{i}$. Scott is on chair number $s$ and Cross is on chair number $e$. Scott can jump to all other chairs (not only neighboring chairs). He w... | Reduction to TSP is easy. We need the shortest Hamiltonian path from $s$ to $e$. Consider the optimal answer. Its graph is a directed path. Consider the induced graph on first $i$ chairs. In this subgraph, there are some components. Each components forms a directed path. Among these paths, there are 3 types of paths: I... | [
"dp",
"graphs",
"greedy"
] | 2,500 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
704 | C | Black Widow | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:
Where $\boldsymbol{\mathit{V}}$ represents logical OR and $\mathbb{C}$ represents logical exclusive OR ... | Build a graph. Assume a vertex for each clause. For every variable that appears twice in the clauses, add an edge between clauses it appears in (variables that appear once are corner cases). Every vertex in this graph has degree at most two. So, every component is either a cycle or a path. We want to solve the problem ... | [
"dp",
"graphs",
"implementation",
"math"
] | 2,900 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
704 | D | Captain America | Steve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are $n$ shields in total, the $i$-th shield is located at point $(x_{i}, y_{i})$ of the coordinate plane. It's possible that two or more shields share the same location.
Steve wants to paint all these shields. He p... | Assume $r < b$ (if not, just swap the colors). Build a bipartite graph where every vertical line is a vertex in part $X$ and every horizontal line is a vertex in part $Y$. Now every point(shield) is an edge (between the corresponding vertical and horizontal lines it lies on). We write 1 on an edge if we want to color i... | [
"flows",
"greedy"
] | 3,100 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
704 | E | Iron Man | Tony Stark is playing a game with his suits (they have auto-pilot now). He lives in Malibu. Malibu has $n$ junctions numbered from $1$ to $n$, connected with $n - 1$ roads. One can get from a junction to any other junction using these roads (graph of Malibu forms a tree).
Tony has $m$ suits. There's a special plan for... | First, we're gonna solve the problem for when the given tree is a bamboo (path). For simplifying, assume vertices are numbered from left to right with $1, 2, .., n$ (it's an array). There are some events (appearing and vanishing). Sort these events in chronological order. At first (time $- \infty $) no suit is there. ... | [
"data structures",
"geometry",
"trees"
] | 3,300 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
705 | A | Hulk | Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have $n$ layers. The first layer is hate, se... | Just alternatively print "I hate that" and "I love that", and in the last level change "that" to "it". Time Complexity: ${\mathcal{O}}(n)$ | [
"implementation"
] | 800 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
705 | B | Spider Man | Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.
Initially t... | First of all, instead of cycles, imagine we have bamboos (paths). A valid move in the game is now taking a path and deleting an edge from it (to form two new paths). So, every player in his move can delete an edge in the graph (with components equal to paths). So, no matter how they play, winner is always determined by... | [
"games",
"math"
] | 1,100 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
706 | A | Beru-taxi | Vasiliy lives at point $(a, b)$ of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested $n$ available Beru-taxi nearby. The $i$-th taxi is located at point $(x_{i}, y_{i})$ and moves with a speed $v_{i}$.
Consider that each of $n$ drivers will move ... | We know that time=distance/speed. For each car we should find $time_{i}$, than if it is less than answer we should update it. Time Complexity: O(n). | [
"brute force",
"geometry",
"implementation"
] | 900 | #include <bits/stdc++.h>
using namespace std;
double dist (int x1, int y1, int x, int y){
return sqrt((x1 - x) * (x1 - x) + (y - y1)*(y - y1));
}
int main()
{
ios_base::sync_with_stdio(false);
int n, x, y;
cin >> x >> y >> n;
long double time = 1e9;
for (int i = 0; i < n; i++){
int xi... |
706 | B | Interesting drink | Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in $n$ different shops in the city. It's known that the price of one bottle in the shop $i$ is equal to $x_{i}$ coins.
Vasiliy plans to buy his favorite... | Consider $c[x]$ the number of stores in which the price per drink is $x$. We calculate this array prefix sum. Then the following options: 1) If the current amount of money $m$ is larger than the size of the array with the prefix sums than answer is $n$. 2) Otherwise, the answer is $c[m]$. Time Complexity: O(n+q). | [
"binary search",
"dp",
"implementation"
] | 1,100 | #include <iostream>
using namespace std;
const int N = (int)1e5 + 5;
int cost[N], dp[N];
int main()
{
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++){
int x;
cin >> x;
cost[x]++;
}
for (int i = 1; i < N; i++){
dp[i] = dp[i - 1] +... |
706 | C | Hard problem | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given $n$ strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only o... | We will solve the problem with the help of dynamic programming. $dp[i][j]$ is the minimum amount of energy that should be spent to make first $i$ strings sorted in lexicographical order and $i$-th of them will be reversed if $j$ = 1 and not reversed if $j$ = 0. $dp[i][j]$ is updated by $dp[i - 1][0]$ and $dp[i - 1][1]$... | [
"dp",
"strings"
] | 1,600 | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
int n;
vector <string> str;
long long c[200000];
long long dp[200000][2];
string rev(string x)
{
string y;
for (int i = x.size() - 1; i >= 0; i--)
y += x[i];
return y;
}
bool check(string a, str... |
706 | D | Vasiliy's Multiset | Author has gone out of the stories about Vasiliy, so here is just a formal task description.
You are given $q$ queries and a multiset $A$, initially containing only integer $0$. There are three types of queries:
- "+ x" — add integer $x$ to multiset $A$.
- "- x" — erase one occurrence of integer $x$ from multiset $A$... | Let's store each number in binary system (each number consists of 32 bits, 0 or 1) in such a data structure as trie.The edges will be the bits 1 and 0, and the vertices will be responsible for whether it is possible to pass the current edge. To reply to a query like "? X" will descend the forest of high-order bits to w... | [
"binary search",
"bitmasks",
"data structures",
"trees"
] | 1,800 | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
int q;
int sz = 1;
struct node
{
int zero;
int one;
int cnt1;
int cnt0;
}a[10000000];
int main()
{
cin >> q;
for (int i = 0; i <= q; i++)
{
char c;
int x;
if(i==0)
{
c='+';
... |
706 | E | Working routine | Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of $n$ rows and $m$ columns and $q$ tasks. Each task is to swap two submatrices of the given matrix.
For each task Vasiliy knows six integers $a_{i}$, $b_{i}$, $c_{i}$, $d_{i}$, $h_{i}$, $w_{i}$, wh... | Let's surround the matrix with the frame of elements. In each element of the matrix, and frame we need to store value, the number of the right element and the number of down element. When a request comes we should change only values of the elements along the perimeter of rectangles. Time Complexity: O(q*(n+m)). | [
"data structures",
"implementation"
] | 2,500 | null |
707 | A | Brain's Photos | Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | We need to do exactly what is written in the task: to consider all of the characters, and, if there is at least one of the set ${C, M, Y}$ print "#Color" else - "#Black&White" | [
"implementation"
] | 800 | null |
707 | B | Bakery | Masha wants to open her own bakery and bake muffins in one of the $n$ cities numbered from $1$ to $n$. There are $m$ bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only $k$ storages, located in different... | Note that it makes no sense to choose the city for bakeries and the city with the warehouse so that had more than one way between them, as every road increases the distance over which you have to pay. So, the problem reduces to the following: select two neighboring cities so that one is a warehouse, and in the other & ... | [
"graphs"
] | 1,300 | null |
707 | D | Persistent Bookcase | Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.
After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcas... | bookcase Solution No. 1: Note that the data is delivered all at once (offline). Then we can build a tree of versions, then run out of the DFS root and honestly handle each request in the transition from the top to the top. Solution No. 2: Note that Alina uses operations that relate to the columns. We can make an array ... | [
"bitmasks",
"data structures",
"dfs and similar",
"implementation"
] | 2,200 | null |
707 | E | Garlands | Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlands — chains consisting of a lightbulbs.
Alesha uses a grid field sized $n × m$ for playing. The rows of the field are numbered from $1$ to $n$ f... | Let us handle each request as follows: Let's go for a "frame" request and remember lamp garlands, which lies on the boundary. Then, in order to find concrete garland, what part of it lies within the query, sum all of its segments, the ends of it are lamps that lie on the "frame". Also, do not forget the garland wich li... | [
"data structures"
] | 2,400 | null |
708 | A | Letters Cyclic Shift | You are given a non-empty string $s$ consisting of lowercase English letters. You have to pick \textbf{exactly one non-empty substring} of $s$ and shift all its letters 'z' $\to$ 'y' $\to$ 'x' $\to\cdot\cdot\top$ 'b' $\to$ 'a' $\to$ 'z'. In other words, each character is replaced with the previous character of English ... | If string consists only of symbols 'a', then we could only make it lexicographically bigger. To achieve the least change we should shift the last symbol. In any other case we could make string lexicographically less. We should shift first biggest subsegment of string consists only from symbols not equal to 'a'. | [
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | 1,200 | void solve() {
string s;
cin >> s;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == 'a') {
continue;
}
int j = i + 1;
while (j < s.length() && s[j] != 'a') {
++j;
}
for (int r = i; r < j; ++r) {
--s[r];
}
cout << s << "\n";
return;
}
s.back() = 'z';
c... |
708 | B | Recover the String | For each string $s$ consisting of characters '0' and '1' one can define four integers $a_{00}$, $a_{01}$, $a_{10}$ and $a_{11}$, where $a_{xy}$ is the number of \textbf{subsequences} of length $2$ of the string $s$ equal to the sequence ${x, y}$.
In these problem you are given four integers $a_{00}$, $a_{01}$, $a_{10}... | Using $a_{00}$ and $a_{11}$ easy to calculate $c_{0}, c_{1}$ - numbers of 0 and 1 in string (it could be done by binary search or solving quadratic equation $c_{0} \cdot (c_{0} - 1) / 2 = a_{00}$). But in case $a_{00} = 0$, $c_{0}$ is not fixed and could be equal 0 or 1. One could consider both cases for sure (or code ... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,900 | void imp() {
cout << "Impossible\n";
exit(0);
}
ll invtriange(ll x) {
ll l = 1, r = 1000000;
while (r - l > 1) {
ll m = (l + r) / 2;
if (m * (m - 1) / 2 > x) r = m;
else l = m;
}
if (l * (l - 1) / 2 != x) {
imp();
}
return l;
}
int main() {
vvl a(2, vl(2));
for (int i = 0; i < 2; +... |
708 | C | Centroids | Tree is a connected acyclic graph. Suppose you are given a tree consisting of $n$ vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed $\frac{n t}{2}$.
You are given a tree of size $n$ and can perform no more th... | The first observation is that to make vertex $x$ a centroid we need to choose some subtree not containing $x$ with size not exceeding $\frac{n t}{2}$ (assume its root is $w$), remove an edge $uw$ between its subtree and the remaining tree, and add an edge between $x$ and $w$, in such a way that subtrees of all children... | [
"data structures",
"dfs and similar",
"dp",
"graphs",
"greedy",
"trees"
] | 2,300 | int n;
vector<vector<int>> g;
vector<int> cnt;
int min_mx = 1e9;
int center = -1;
void dfs(int v, int p) {
cnt[v] = 1;
int mx = 0;
for (int to : g[v]) {
if (to == p) {
continue;
}
dfs(to, v);
cnt[v] += cnt[to];
mx = max(mx, cnt[to]);
}
mx = max(mx, n - cnt[v]);
if (mx < min_mx) {
min_mx = mx;
c... |
708 | D | Incorrect Flow | At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to... | This problem could be solved by max-flow-min-cost algorithm. At first we will fix edges with flow exceeding capacity. We will just increase capacity to the flow value and add sum of all these changes to the answer. Now we need to get rid of excess incoming flow in some vertices and excess outcoming flow in some other v... | [
"flows"
] | 2,900 | class FixFlow {
public:
void solve(std::istream& in, std::ostream& out) {
int n, m;
in >> n >> m;
int s = n;
int t = n + 1;
MinCostFlow<int, int> flow(n + 2);
vector<int> balance(n);
int INF = 1000000000;
flow.addEdge((size_t) (n - 1), 0, INF, 0);
int defaultAnswer = 0;
for (int i: range(m)) {
... |
708 | E | Student's Camp | Alex studied well and won the trip to student camp Alushta, located on the seashore.
Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of $n + 2$ concrete blocks height and $m$ blocks width.
Every day there is a b... | Let $dp[t][l][r]$ is probability that first $t$ rows are connected and $t$-th row is $[l;r)$ (it's always a segment). We can write a simple equation: $d p[t][l][r]=p_{l,r}\sum_{l p,r p}d p[t-1][l p][r p]$ $p_{l}={\binom{k}{l}}p^{l}(1-p)^{k-l}.$ $d p_{r}[t][r]=\sum_{l<r}d p[t][l][r]$ $s u m_{-}d p_{r}[t][r]=\sum_{a\leq ... | [
"dp",
"math"
] | 3,100 | class MAI {
public:
void solve(std::istream& in, std::ostream& out) {
int N, m;
int a, b;
int k;
in >> N >> m >> a >> b >> k;
using Z = ZnConst<1000000007>;
Z p = Z::valueOf(a) / b;
Z q = 1 - p;
// dp[r'] = sum l < r <= r' d[l][r]
vector<Z> dp(m + 1, Z());
dp[m] = 1;
vector<Z> powersP(k + 1), p... |
709 | A | Juicer | Kolya is going to make fresh orange juice. He has $n$ oranges of sizes $a_{1}, a_{2}, ..., a_{n}$. Kolya will put them in the juicer in the fixed order, starting with orange of size $a_{1}$, then orange of size $a_{2}$ and so on. To be put in the juicer the orange must have size not exceeding $b$, so if Kolya sees an o... | In this problem you have to carefully implement exactly what it written in the statement. Pay attention to some details: Don't forget to throw away too large oranges. Don't mix up strict and not-strict inequalities. | [
"implementation"
] | 900 | int main() {
int n, b, d;
std::cin >> n >> b >> d;
int current_size = 0;
int result = 0;
int x;
for (; n > 0; --n) {
std::cin >> x;
if (x > b) {
continue;
}
current_size += x;
if (current_size > d) {
++result;
current_size = 0;
}
}
std::cout << result << "\n";... |
709 | B | Checkpoints | Vasya takes part in the orienteering competition. There are $n$ checkpoints located along the line at coordinates $x_{1}, x_{2}, ..., x_{n}$. Vasya starts at the point with coordinate $a$. His goal is to visit at least $n - 1$ checkpoint in order to finish the competition. Participant are allowed to visit checkpoints i... | Sort all point by $x$-coordinate. If we've chosen the set of points we want to visit, then we must go either to the leftmost of them and then to the rightmost, or to the rightmost and then to the leftmost, the others will be visited automatically during this process. The other observation is that it makes sense to not ... | [
"greedy",
"implementation",
"sortings"
] | 1,500 | const int MAXN = 100000;
int x[MAXN];
int main() {
int n, A;
scanf("%d %d", &n, &A);
if (n == 1) {
printf("0\n");
return 0;
}
for (int i = 0; i < n; i++) {
scanf("%d", &x[i]);
}
int first_max = -2e6;
int second_max = -2e6;
int first_min = 2e6;
int second_min = 2e6;
for (int i = 0; i... |
710 | A | King Moves | The only king stands on the standard chess board. You are given his position in format "cd", where $c$ is the column from 'a' to 'h' and $d$ is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here https://en.wikipedia.org/wiki/King_(chess).
\begin{center}
{\small King ... | Easy to see that there are only three cases in this problem. If the king is in the corner of the board the answer is $3$. If the king is on the border of the board but not in a corner then the answer is $5$. Otherwise the answer is $8$. Complexity: $O(1)$. | [
"implementation"
] | 800 | char c, d;
bool read() {
return !!(cin >> c >> d);
}
void solve() {
int cnt = 0;
if (c == 'a' || c == 'h') cnt++;
if (d == '1' || d == '8') cnt++;
if (cnt == 0) puts("8");
else if (cnt == 1) puts("5");
else if (cnt == 2) puts("3");
else throw;
} |
710 | B | Optimal Point on a Line | You are given $n$ points on a line with their coordinates $x_{i}$. Find the point $x$ so the sum of distances to the given points is minimal. | The function of the total distance is monotonic between any pair of adjacent points from the input, so the answer is always in some of the given points. We can use that observation to solve the problem by calculating the total distance for each point from the input and finding the optimal point. The other solution uses... | [
"brute force",
"sortings"
] | 1,400 | const int N = 300300;
int n, a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
void solve() {
sort(a, a + n);
li suml = 0, sumr = accumulate(a, a + n, 0ll);
li ansv = LLONG_MAX, ansp = LLONG_MIN;
forn(i, n) {
li curv = li(i) * a[i] - suml;
curv ... |
710 | C | Magic Odd Square | Find an $n × n$ matrix with different numbers from $1$ to $n^{2}$, so the sum in each row, column and both main diagonals are odd. | The solution can be got from the second sample testcase. Easy to see that if we place all odd numbers in the center in form of rhombus we will get a magic square. Complexity: $O(n^{2})$. | [
"constructive algorithms",
"math"
] | 1,500 | int n;
bool read() {
return !!(cin >> n);
}
const int N = 101;
int a[N][N];
void solve() {
memset(a, 0, sizeof(a));
forn(i, n / 2) {
int len = n / 2 - i;
forn(j, len) {
int x1 = i, x2 = n - 1 - i;
int y1 = j, y2 = n - 1 - j;
a[x1][y1] = 1;
a[x1][y2] = 1;
a[x2][y1] = 1;
a[x2][y2] = 1;
}
... |
710 | D | Two Arithmetic Progressions | You are given two arithmetic progressions: $a_{1}k + b_{1}$ and $a_{2}l + b_{2}$. Find the number of integers $x$ such that $L ≤ x ≤ R$ and $x = a_{1}k' + b_{1} = a_{2}l' + b_{2}$, for some integers $k', l' ≥ 0$. | Let's write down the equation describing the problem: $a_{1}k + b_{1} = a_{2}l + b_{2} \rightarrow a_{1}k - a_{2}l = b_{2} - b_{1}$. So we have linear Diofant equation with two variables: $Ax + By = C, A = a_{1}, B = - a_{2}, C = b_{2} - b_{1}$. The solution has the form: $A{\frac{C x_{0}+B p}{g}}+B{\frac{C y_{0}-A p... | [
"math",
"number theory"
] | 2,500 | li a1, b1, a2, b2, l, r;
bool read() {
return !!(cin >> a1 >> b1 >> a2 >> b2 >> l >> r);
}
li _ceil(li, li);
li _floor(li a, li b) { return b < 0 ? _floor(-a, -b) : a < 0 ? -_ceil(-a, b) : a / b; }
li _ceil(li a, li b) { return b < 0 ? _ceil(-a, -b) : a < 0 ? -_floor(-a, b) : (a + b - 1) / b; }
li gcd(li a, li b, l... |
710 | E | Generate a String | zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of $n$ letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him $x$ seconds to insert or delete a letter... | This problem has a simple solution described by participants in the comments. My solution is a little harder. Let's solve it using dynamic programming. Let $z_{n}$ be the smallest amount of time needed to get $n$ letters 'a'. Let's consider transitions: the transition for adding one letter 'a' can be simply done. Let's... | [
"dfs and similar",
"dp"
] | 2,000 | int n;
li x, y;
bool read() {
return !!(cin >> n >> x >> y);
}
const int N = 20 * 1000 * 1000 + 13;
li z[N];
void solve() {
forn(i, N) z[i] = LLONG_MAX;
list<pair<li, int>> q;
z[0] = 0;
forn(i, n + 1) {
while (!q.empty() && q.front().y < i) q.pop_front();
if (!q.empty()) z[i] = min(z[i], q.front().x - i... |
710 | F | String Set Queries | You should process $m$ queries over a set $D$ of strings. Each query is one of three kinds:
- Add a string $s$ to the set $D$. It is guaranteed that the string $s$ was not added before.
- Delete a string $s$ from the set $D$. It is guaranteed that the string $s$ is in the set $D$.
- For the given string $s$ find the n... | Let's get rid of the queries for deleting a string. There are no strings that will be added two times, so we can calculate the answer for the added (but not deleted strings) and for the deleted separately and subtract the second from the first to get the answer. So we can consider that there are no queries of deletion.... | [
"brute force",
"data structures",
"hashing",
"interactive",
"string suffix structures",
"strings"
] | 2,400 | const int N = 4 * 300300, A = 26, LOGN = 20;
struct node {
char c;
int parent, link, output;
int next[A], automata[A];
int cnt;
node(char c = -1, int parent = -1, int link = -1, int output = -1, int cnt = -1):
c(c), parent(parent), link(link), output(output), cnt(cnt) {
memset(ne... |
711 | A | Bus to Udayland | ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has $n$ rows of seats. There are $4$ seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris... | For each row, check whether there exists two consecutive Os. Once you find a pair of consecutive Os, you can replace them with +s and output the bus. If no such pair exists, output NO. Time Complexity : $O(n)$ | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
711 | B | Chris and Magic Square | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a $n × n$ magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a \textbf{positive integer} into the empty cell.
Chris tried fil... | Firstly, when $n = 1$, output any positive integer in the range will work. Otherwise, we calculate the sum of the values in each row, column and the two long diagonals, and also keep track which row and column the empty square is in and also which diagonals it lies on. Finally, we can use the sums to determine the valu... | [
"constructive algorithms",
"implementation"
] | 1,400 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
711 | C | Coloring Trees | ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where $n$ trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from $1$ to $n$ from left to right.
Initially, tree $i$ has color $c_{i}$. ZS the Coder and Chris the Baboon recogniz... | We compute the following array : $dp[i][j][k]$ denoting the minimum amount of paint needed to color the first $i$ trees such that it has beauty $j$ and the $i$-th tree is colored by color $k$, and initialize all these values to $ \infty $. We can compute this dp array easily by considering two cases : 1. When the last ... | [
"dp"
] | 1,700 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair... |
711 | D | Directed Roads | ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of $n$ towns numbered from $1$ to $n$.
There are $n$ directed roads in the Udayland. $i$-th of them goes from town $i$ to some other town $a_{i}$ ($a_{i} ≠ i$). ZS the Coder can flip the direction of any road in ... | We want to find the number of ways to assign directions to the edges of the graph so that it is acyclic, i.e. contains no cycles. First, we investigate what the graph looks like. It can be easily seen that the graph consists of several connected components, where each component is either a path or a cycle with some pat... | [
"combinatorics",
"dfs and similar",
"graphs",
"math"
] | 1,900 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
711 | E | ZS and The Birthday Paradox | ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of $23$ people, there is around $50%$ chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.
In Udayl... | Note that $MOD = 10^{6} + 3$ is a prime. Firstly, if we have $k > 2^{n}$, then by pigeonhole principle we must have $2$ people with the same birthday. Thus, we can directly output $1$ $1$. Thus, now we suppose $k \le 2^{n}$. Then, instead of computing the probability directly, we compute the complement, i.e. the prob... | [
"math",
"number theory",
"probabilities"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
const int MOD = 1e6 + 3;
ll power(ll base, ll exp)
{
ll ans = 1;
while(exp)
{
if(exp&1) ans = (ans*base)%MOD;
base = (base*base)%MOD;
exp>>=1;
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(fals... |
712 | A | Memory and Crow | There are $n$ integers $b_{1}, b_{2}, ..., b_{n}$ written in a row. For all $i$ from $1$ to $n$, values $a_{i}$ are defined by the crows performing the following procedure:
- The crow sets $a_{i}$ initially $0$.
- The crow then adds $b_{i}$ to $a_{i}$, subtracts $b_{i + 1}$, adds the $b_{i + 2}$ number, and so on unti... | Note that $a[i] + a[i + 1] = b[i]$. Use the initial condition $b[n] = a[n]$ and we can figure out the entire array $b$. Time Complexity: $O(n)$ | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int arr[100000];
int ans[100000];
int main()
{
int n;
cin >> n;
for(int i=0; i < n; i++){
cin >> arr[i];
}
for(int i = n-1; i >=0; i--){
if(i==n-1) ans[i] = arr[i];
else ans[i] = arr[i] + arr[i+1];
}
for(int i=0; i < n... |
712 | B | Memory and Trident | Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string $s$ with his directions for motion:
- An 'L' indicates he should move one unit left.
- An 'R' indicates he should move one unit right.
- A 'U' indicates he should move one unit up.
- A 'D' indicates he should move on... | First, if $S$ has odd length, there is no possible string because letters must come in opposite pairs. Now, let's denote the ending coordinate after following $S$ as $(x, y)$. Since $S$ has even length, $|x|$ has the same parity as $|y|$. Suppose they are both even. Then clearly, we can make $x = 0$ in exactly $\frac{|... | [
"implementation",
"strings"
] | 1,100 | #include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
string str;
cin >> str;
if(str.length()%2==1){
cout << -1 << endl;
return 0;
}
int x=0,y=0;
for(int i=0; i < str.length(); i++){
if(str[i]=='U')y++;
if(str[i]=='D')y--;
... |
712 | C | Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length $x$, and he wishes to perform operations to obtain an equilateral triangle of side length $y$.
In a single second, he can modify the length of a single side of the current triangle suc... | Let's reverse the process: start with an equilateral triangle with side length $y$, and lets get to an equilateral triangle with side length $x$. In each step, we can act greedily while obeying the triangle inequality. This will give us our desired answer. Time Complexity: $O(log$ $x)$ | [
"greedy",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int x,y;
cin >> x >> y;
int besta=y,bestb=y,bestc=y;
int turns = 0;
while(true){
//check the current
if(besta>=x && bestb>=x && bestc>=x){
cout << turns << endl;
break;
}
turns++;
... |
712 | D | Memory and Scores | Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score $a$ and Lexa starts with score $b$. In a single turn, both Memory and Lexa get some integer in the range $[ - k;k]$ (i.e. one integer among $ - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k$)... | One approach to this problem is by first implementing naive DP in $O((kt)^{2})$. The state for this is $(diff, turn)$, and transitions for $(diff, turn)$ is the sum $(diff - 2k, turn - 1) + 2(diff - 2k + 1, turn - 1) + 3(diff - 2k + 2, turn - 1) + ... + (2k + 1)(diff, turn - 1) + 2k(diff + 1, turn - 1) + ...$ $+ diff( ... | [
"combinatorics",
"dp",
"math"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define FOR(i, a, b) for (int i=a; i<b; i++)
#define F0R(i, a) FOR(i, 0, a)
const int MAX = 1000005;
const int MOD = 1000... |
712 | E | Memory and Casinos | There are $n$ casinos lined in a row. If Memory plays at casino $i$, he has probability $p_{i}$ to win and move to the casino on the right ($i + 1$) or exit the row (if $i = n$), and a probability $1 - p_{i}$ to lose and move to the casino on the left ($i - 1$) or also exit the row (if $i = 1$).
We say that Memory dom... | Lets think about two segments of casinos $[i, j]$ and $[j + 1, n]$. Let $L([a, b])$ denote the probability we dominate on $[a, b]$, and let $R([a, b])$ denote the probability we start on $b$ and end by moving right of $b$. Let $l_{1} = L([i, j])$, $l_{2} = L([j + 1, n])$, $r_{1} = R([i, j])$, $r_{2} = R([j + 1, n])$. Y... | [
"data structures",
"math",
"probabilities"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
int n;
double pr[100000];
pair<double,double> seg[400000];
bool ze(double d){
return (abs(d) <= 0.0000000001);
}
pair<double,double> merge(pair<double,double> a, pair<double,double> b){
if(ze(a.first+1) && ze(a.second+1)) return b;
if(ze(b.first+1) && ze(b.second+1)) r... |
713 | A | Sonya and Queries | Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her $t$ queries, each of one of the following type:
- $ + $ $a_{i}$ — add non-negative integer $a_{i}$ to the multiset. Note, that she has a multiset, thus there may b... | Lets exchange every digit by value of digit modulo $2$ and receive binary string. We will convert it to binary form in number $r$. $G$ - array for counts. If we have '+' query we increase $G$[$r$]. If we have '-' query we decrease $G$[$r$]. Otherwise we output $G$[$r$]. | [
"data structures",
"implementation"
] | 1,400 | null |
713 | B | Searching Rectangles | Filya just learned new geometry object — rectangle. He is given a field consisting of $n × n$ unit cells. Rows are numbered from bottom to top with integer from $1$ to $n$. Columns are numbered from left to right with integers from $1$ to $n$. Cell, located at the intersection of the row $r$ and column $c$ is denoted a... | Assume we have just one rectangle. First we can find its right side. In binary search we check is out rectangle to the left of some line $x_{2}$ using function $get$($1$,$1$,$x_{2}$,$n$). As soon as we found right coordinate we can 'cut' everything to the right of the line, because there is nothing to look. In the same... | [
"binary search",
"constructive algorithms",
"interactive"
] | 2,200 | null |
713 | C | Sonya and Problem Wihtout a Legend | Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing $n$ positive integers. At one turn you can pick any element and increase or decrease it by $1$. The goal is the make the array strictly increasing by making the minimum possible number of ope... | Lets first solve easier problem. Given an array of number what it is minimal amount of operations ($+ 1$ to element, $- 1$ to element) to make all numbers in array equal? We need to solve this problem for each prefix. Optimal solution would be making all numbers equal to median value of the prefix (middle element in so... | [
"dp",
"sortings"
] | 2,300 | null |
713 | D | Animals and Puzzle | Owl Sonya gave a huge lake puzzle of size $n × m$ to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be empty — there was no picture on them. Parts with picture on it are denoted by $1$, while empty parts are denoted by $0$. Rows of the puzzle... | First lets calculate $dp[i][j]$ - maximum square ending in cell ($i$, $j$). For each cell if input matrix contain $0$ then $dp[i][j] = 0$ else $dp_{}[i][j] = min$($dp[i - 1][j - 1]$, $dp[i-1][j]$, $dp[i][j-1]$)$+ 1$. We will use binary search to find the answer. Lets fix some value $x$. For each square ($i$, $j$)..($i ... | [
"binary search",
"data structures"
] | 2,700 | null |
713 | E | Sonya Partymaker | Owl Sonya decided to become a partymaker. To train for this role she gather all her owl friends in the country house. There are $m$ chairs located in a circle and consequently numbered with integers from $1$ to $m$. Thus, chairs $i$ and $i + 1$ are neighbouring for all $i$ from $1$ to $m - 1$. Chairs $1$ and $m$ are al... | Will use binary search to find the answer. Assume that we need to know if it is enough $x$ minutes to visit each vertex. Lets $dp[i][0...1]$ is equal to minimum number of vertices to the left of $i$, which wasn't visited yet, second parameter is equal to $1$, if we have't launched robot from vertex $i$. I.e. when $dp[i... | [
"binary search",
"dp"
] | 3,300 | null |
714 | A | Meeting of Old Friends | Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya!
Sonya is an owl and she sleeps during the day and stay awake from minute $l_{1}$ to minute $r_{1}$ inclusive. Also, during the minute $k$ she prinks and is unavailable for Filya.
Filya works a lot and he pla... | Lets find two numbers $l$ and $r$ - lower and upper bound on time which guys can spend together. $l =$ $max$($l_{1}$, $l_{2}$), $r =$ $min$($r_{1}$,$r_{2}$). If $l > r$ then answer is definitely $0$. In case $l \le r$ we need to number $k$ belongs to the interval. If is it true - answer is $r - l$, otherwise it is $r... | [
"implementation",
"math"
] | 1,100 | null |
714 | B | Filya and Homework | Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.
Filya is given an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. First, he pick an integer $x$ and then he adds $x$ to some elements of the array (no more than onc... | Answer can be calculated according to next options: 1). If all numbers are equal - answer is <<Yes>> 2). If there are two distinct numbers in the array - answer is <<Yes>> 3). If there are at least four distinct numbers in the array - answer is <<No>> 4). In other case lets there are three distinct numbers $q < w < e$,... | [
"implementation",
"sortings"
] | 1,200 | null |
715 | A | Plus and Square Root | ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '$ + $' (plus) and '$\lor$' (square root). Initially, the number $2$ is displayed on the screen. There are $n + 1$ levels in the game and ZS the Coder start at the level $1$.
When ZS the Coder is at level $k$, he can :... | Firstly, let $a_{i}(1 \le i \le n)$ be the number on the screen before we level up from level $i$ to $i + 1$. Thus, we require all the $a_{i}$s to be perfect square and additionally to reach the next $a_{i}$ via pressing the plus button, we require $a_{i+1}\equiv\sqrt{a_{i}}(m o d(i+1))$ and $a_{i+1}\geq{\sqrt{a_{i... | [
"constructive algorithms",
"math"
] | 1,600 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<ll... |
715 | B | Complete The Graph | ZS the Coder has drawn an undirected graph of $n$ vertices numbered from $0$ to $n - 1$ and $m$ edges between them. Each edge of the graph is weighted, each weight is a \textbf{positive integer}.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign \textbf{positive integer}... | This problem is actually quite simple if you rule out the impossible conditions. Call the edges that does not have fixed weight variable edges. First, we'll determine when a solution exists. Firstly, we ignore the variable edges. Now, find the length of the shortest path from $s$ to $e$. If this length is $< L$, there ... | [
"binary search",
"constructive algorithms",
"graphs",
"shortest paths"
] | 2,300 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<ll... |
715 | C | Digit Tree | ZS the Coder has a large tree. It can be represented as an undirected connected graph of $n$ vertices numbered from $0$ to $n - 1$ and $n - 1$ edges between them. There is a single \textbf{nonzero} digit written on each edge.
One day, ZS the Coder was bored and decided to investigate some properties of the tree. He ch... | Compared to the other problems, this one is more standard. The trick is to first solve the problem if we have a fixed vertex $r$ as root and we want to find the number of paths passing through $r$ that works. This can be done with a simple tree dp. For each node $u$, compute the number obtained when going from $r$ down... | [
"dfs and similar",
"divide and conquer",
"dsu",
"trees"
] | 2,700 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
715 | D | Create a Maze | ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of $n × m$ rooms, and the rooms are arranged in $n$ rows (numbered from the top to the bottom starting from $1$) and $m$ columns (numbered from the left to the right starting from $1$). The room in the $i$-th row and $j$-th... | The solution to this problem is quite simple, if you get the idea. Thanks to danilka.pro for improving the solution to the current constraints which is much harder than my original proposal. Note that to calculate the difficulty of a given maze, we can just use dp. We write on each square (room) the number of ways to g... | [
"constructive algorithms"
] | 3,100 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
715 | E | Complete the Permutations | ZS the Coder is given two permutations $p$ and $q$ of ${1, 2, ..., n}$, but some of their elements are replaced with $0$. The distance between two permutations $p$ and $q$ is defined as the minimum number of moves required to turn $p$ into $q$. A move consists of swapping exactly $2$ elements of $p$.
ZS the Coder want... | We'll slowly unwind the problem and reduce it to something easier to count. First, we need to determine a way to tell when the distance between $p$ and $q$ is exactly $k$. This is a classic problem but I'll include it here for completeness. Let $f$ denote the inverse permutation of $q$. So, the minimum number of swaps ... | [
"combinatorics",
"fft",
"graphs",
"math"
] | 3,400 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
716 | A | Crazy Computer | ZS the Coder is coding on a crazy computer. If you don't type in a word for a $c$ consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second $a$ and then the next word at second $b$, then if $b - a ≤ c$, just the new word is appended to other words on the screen. If $b - a > c$, ... | This is a straightforward implementation problem. Iterate through the times in order, keeping track of when is the last time a word is typed, keeping a counter for the number of words appearing on the screen. Increment the counter by $1$ whenever you process a new time. Whenever the difference between the time for two ... | [
"implementation"
] | 800 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
716 | B | Complete the Word | ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a \textbf{substring} (contiguous segment of letters) of it of length $26$ where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than $26$, no such substring exists and thu... | Firstly, if the length of the string is less than $26$, output $- 1$ immediately. We want to make a substring of length $26$ have all the letters of the alphabet. Thus, the simplest way is to iterate through all substrings of length $26$ (there are $O(n)$ such substrings), then for each substring count the number of oc... | [
"greedy",
"two pointers"
] | 1,300 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<in... |
718 | A | Efim and Strange Grade | Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after th... | One can notice that the closer to the decimal point we round our grade the bigger grade we get. Based on this observation we can easily solve the problem with dynamic programming. Let $dp_{i}$ be the minimum time required to get a carry to the ($i - 1$)-th position. Let's denote our grade as $a$, and let $a_{i}$ be the... | [
"dp",
"implementation",
"math"
] | 1,700 | null |
718 | C | Sasha and Array | Sasha has an array of integers $a_{1}, a_{2}, ..., a_{n}$. You have to perform $m$ queries. There might be queries of two types:
- 1 l r x — increase all integers on the segment from $l$ to $r$ by values $x$;
- 2 l r — find $\textstyle\sum_{i=l}^{r}f(a_{i})$, where $f(x)$ is the $x$-th Fibonacci number. As this number... | Let's denote Let's recall how we can quickly find $n$-th Fibonacci number. To do this we need to find a matrix product $(1~1)\times A^{n-2}$. In order to solve our problem let's create the following segments tree: in each leaf which corresponds to the element $i$ we will store a vector $\left(f_{a_{i}}\ \ f_{a_{i}+1}\r... | [
"data structures",
"math",
"matrices"
] | 2,300 | null |
718 | D | Andrew and Chemistry | During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he... | Let's first figure out how we can solve the problem in $O(n^{2}\log{n})$ time. Let's pick a vertex we're going to add an edge to and make this vertex the root of the tree. For each vertex $v_{i}$ we're going to assign a label $a[v_{i}]$ (some number). The way we assign labels is the following: if the two given vertices... | [
"dp",
"hashing",
"trees"
] | 2,900 | null |
718 | E | Matvey's Birthday | Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string $s$ of length $n$. This string consists of only first eight English letters: 'a', 'b', $...$, 'h'.
First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what t... | Let's prove that the distance between any two vertices is no more than $MaxDist = 2 \cdot sigma - 1$, where $sigma$ is the size of the alphabet. Let's consider one of the shortest paths from the position $i$ to the position $j$. One can see that in this path each letter $ch$ occurs no more than two times (otherwise you... | [
"bitmasks",
"graphs"
] | 3,300 | null |
719 | A | Vitya in the Countryside | Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | There are four cases that should be carefully considered: $a_{n} = 15$ $-$ the answer is always DOWN. $a_{n} = 0$ $-$ the answer is always UP. If $n = 1$ $-$ the answer is -1. If $n > 1$, then if $a_{n-1} > a_{n}$ $-$ answer is DOWN, else UP. Time Complexity: $O(1)$. | [
"implementation"
] | 1,100 | null |
719 | B | Anatoly and Cockroaches | Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are $n$ cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectio... | We can notice that there are only two possible final coloring of cockroaches that satisfy the problem statement: $rbrbrb...$ or $brbrbr...$ Let's go through both of these variants. In the each case let's count the number of red and black cockroaches which are not standing in their places. Let's denote these numbers as ... | [
"greedy"
] | 1,400 | null |
720 | A | Closing ceremony | The closing ceremony of Squanch Code Cup is held in the big hall with $n × m$ seats, arranged in $n$ rows, $m$ seats in a row. Each seat has two coordinates $(x, y)$ ($1 ≤ x ≤ n$, $1 ≤ y ≤ m$).
There are two queues of people waiting to enter the hall: $k$ people are standing at $(0, 0)$ and $n·m - k$ people are standi... | Probably the easiest way to solve the problem is greedy. Sort people from the first line by increasing of their stamina. Give them tickets in this order, each time using the place which is furthest away from the other line. After that try to assign people from the second line to the remaining seats by sorting people by... | [
"greedy"
] | 2,000 | null |
720 | B | Cactusophobia | Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle.
Vasya has an edge cactus, each edge of this graph has some color.
Vasya would like to remove the minimal number of edges in such way ... | Let us divide the graph to biconnected blocks. Each block is either a bridge, or a cycle. Our goal is to remove one edge from each cycle, so that the number of remaining colors were maximum possible. Let us build a bipartite graph, one part would be blocks, another one would be colors. For each block put an edge of cap... | [
"dfs and similar",
"flows"
] | 2,400 | null |
720 | C | Homework | Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: $n$, $m$ and $k$, and asked him to mark one or more squares on a square grid of size $n × m$.
The marked squares must form a connected figure, and there must be exactly $k$ triples of marked squares that form an L-sha... | The solution is constructive. First let us use backtracking to find solutions for all $n, m < 5$, it is also better to precalculate all answers, in order not to mess with non-asymptotic optimizations. Now $m \ge 5$. Let us put asterisks from left to right, one row after another. When adding the new asterisk, we add 4... | [
"constructive algorithms"
] | 3,100 | null |
720 | D | Slalom | Little girl Masha likes winter sports, today she's planning to take part in slalom skiing.
The track is represented as a grid composed of $n × m$ squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square $(1, 1)$ to the square $(n, m)$. She can move from a square t... | First let us consider all paths from the starting square to the finish one. Let us say that two paths are equivalent, if each obstacle is at the same side for both paths. For each class of equivalence let us choose the representative path - the one that tries to go as low as possible, lexicographically minimum. Let us ... | [
"data structures",
"dp",
"sortings"
] | 3,100 | null |
720 | E | Cipher | Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has $n$ decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet.
There is a legend near the display,... | First let us consider a slow solution. Let us find a condition for each number $k$ after what number of seconds Borya can distinguish it from the given number. Let us look at their initial encoding. Increase both numbers by $1$ until the encodings are different (or one of the numbers needs more than $n$ digits to repre... | [
"implementation"
] | 3,100 | null |
720 | F | Array Covering | Misha has an array of integers of length $n$. He wants to choose $k$ different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays.
Misha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all thes... | We give the outline of the solution, leaving technical details as an excercise. First note that the answer will always use $min(k - n, 0)$ subarrays with maximal sums. Sof let us find the sum of $min(k - n, 0)$ maximal subarrays, elements that are used in them, and the following $min(k, n)$ subarrays. We can do it usin... | [
"data structures"
] | 3,100 | null |
721 | A | One-dimensional Japanese Crossword | Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized $a × b$ squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represen... | In this problem we have to compute the lengths of all blocks consisting of consecutive black cells. Let's iterate from the left cell of crossword to the end: let $i$ be the number of the cell where we are currently; if $s[i] = B$, let $j = i$, and while $j < n$ and $s[j] = 'B'$, we increase $j$ by one. When we come to ... | [
"implementation"
] | 800 | null |
721 | B | Passwords | Vanya is managed to enter his favourite site Codehorses. Vanya uses $n$ distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitr... | The author suggests a solution with formulas: let's count two variables - $cnt_{l}$ (the number of passwords that are shorter than Vanya's Codehorses password) and $cnt_{le}$ (the number of passwords that are not longer than Vanya's Codehorses password). Then it's easy to see that in the best case answer will be equal ... | [
"implementation",
"math",
"sortings",
"strings"
] | 1,100 | null |
721 | C | Journey | Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are $n$ showplaces in the city, numbered from $1$ to $n$, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there \textbf{are no} cyclic routes between showplaces.
... | Author's solution uses dynamic programming. Let $dp_{i, j}$ be the minimum time required to arrive at the vertex $i$, if we visit $j$ vertices (including vertices $1$ and $i$). We have a DAG (directed acyclic graph), so we can compute it recursively (and memory constraints were a bit strict in this problem, so it's bet... | [
"dp",
"graphs"
] | 1,800 | null |
721 | D | Maxim and Array | Recently Maxim has found an array of $n$ integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer $x$ and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer $i$ ($1 ≤ i ≤ n$) and replaces the $i$-th e... | Main idea: we act greedily, trying to make the best possible answer every action (each time we choose an action with minimum possible product after it). Detailed explanation: While we have zeroes in our array, we have to get rid of them, changing each of them exactly one time. Also we keep the quantity of negative numb... | [
"constructive algorithms",
"data structures",
"greedy",
"math"
] | 2,000 | null |
721 | E | Road to Home | Once Danil the student was returning home from tram stop lately by straight road of length $L$. The stop is located at the point $x = 0$, but the Danil's home — at the point $x = L$. Danil goes from $x = 0$ to $x = L$ with a constant speed and does not change direction of movement.
There are $n$ street lights at the r... | Firstly, if we are in some segment and we are going to sing in it, we want to sing as much as possible in this segment. So there are two cases for each segment: either we sing in the segment while we can or we just skip it. Now we consider two different cases: 1) $p \le 100$ If we have stopped singing in the segment,... | [
"binary search",
"dp"
] | 2,700 | null |
722 | A | Broken Clock | You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from $1$ to $12$, while in 24-hours it changes from $0$ to $23$. In both formats minutes change from $0$ to $59$.
You are given a time in format HH:MM that is currently displayed on... | Let's iterate over all possible values that can be shown on the clock. First two digits must form a number from $1$ to $12$ in case of $12$-hours format and a number from $0$ to $23$ in case of $24$-hours format. Second two digits must form a number from $0$ to $59$. For each value, we will count the number of digits t... | [
"brute force",
"implementation"
] | 1,300 | null |
722 | B | Verse Pattern | You are given a text consisting of $n$ lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowel... | Number of syllables, in which we can split a word, can be uniqely defined by the number of vowels in it. Thus, we need to count the number of vowels in each line and compare them to the given sequence. | [
"implementation",
"strings"
] | 1,200 | null |
722 | C | Destroying Array | You are given an array consisting of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from $1$ to $n$ defining the order elements of the array are destroyed.
After each element is destroyed you have to find... | Main observation, that was necessary to solve the problem: since all numbers are non-negative, it makes sense to consider only subsegments, maximal with respect to inclusion. That is, such segments on both sides of which there are either destroyed numbers or the end of the array. Let's solve the problem in reversed ord... | [
"data structures",
"dsu"
] | 1,600 | null |
722 | D | Generating Sets | You are given a set $Y$ of $n$ \textbf{distinct} positive integers $y_{1}, y_{2}, ..., y_{n}$.
Set $X$ of $n$ \textbf{distinct} positive integers $x_{1}, x_{2}, ..., x_{n}$ is said to generate set $Y$ if one can transform $X$ to $Y$ by applying some number of the following two operation to integers in $X$:
- Take any... | Author's solution appeared to be slightly more complicated than the solutions of most of the participants, so we will describe that simple solution. An arbitrary number $y$ can be obtained from one of the following numbers - $y,\{{\frac{y}{2}}\},\{{\frac{y}{4}}\},\ldots,1$ and only from them. Therefore, we will use the... | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"strings",
"trees"
] | 1,900 | null |
722 | E | Research Rover | Unfortunately, the formal description of the task turned out to be too long, so here is the legend.
Research rover finally reached the surface of Mars and is ready to complete its mission. Unfortunately, due to the mistake in the navigation system design, the rover is located in the wrong place.
The rover will operat... | Several auxiliary statements: The number of paths between cells with coordinates $(i_{1}, j_{1})$ and $(i_{2}, j_{2})$, for which $i_{1} \le i_{2}$ and $j_{1} \le j_{2}$, is equal to $\left(^{\left(j_{2}-j_{1}\right)+\left(i_{2}-i_{1}\right)}\right)$. In order to get the answer it is not necessary to find irreducib... | [
"combinatorics",
"dp"
] | 2,900 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.