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 ⌀ |
|---|---|---|---|---|---|---|---|
526 | A | King of Thieves | In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
An interesting feature of the game is that you can design your own levels that wil... | This task is easy for many of you. We can just iterate over all possible $i_{1}$ and $i_{2} - i_{1}$, then we can compute $i_{3, ..., 5}$, and check whether this subsequence satisfies the condition mentioned in the task. | [
"brute force",
"implementation"
] | 1,300 | null |
526 | B | Om Nom and Dark Park | Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
The park consists of $2^{n + 1} - 1$ squares connected by roads so ... | We use greedy and recursion to solve this task. For each tree rooted at $v$, we adjust its two subtrees at first, using recursion. Then we increase one edge from $v$'s child to $v$. | [
"dfs and similar",
"greedy",
"implementation"
] | 1,400 | null |
526 | C | Om Nom and Candies | A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?
One day, when he came to his friend Evan, Om Nom didn't find him at home but h... | If there is a kind of candy which weighs greater than $\sqrt{C}$, then we can iterate over the number of it to buy, which is less than $\sqrt{C}$. Otherwise, without loss of generality we suppose ${\frac{H_{b}}{W_{b}}}<{\frac{H_{s}}{W_{r}}}$. If the number of the blue candies that Om Nom eats is more than $W_{r}$, he c... | [
"brute force",
"greedy",
"math"
] | 2,000 | null |
526 | D | Om Nom and Necklace | One day Om Nom found a thread with $n$ beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.
Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular patt... | This task is to determine whether a string is in the form of $ABABA... ABA$ for each prefixes of a given string $S$ For a prefix P, let's split it into some blocks, just like $P = SSSS... SSSST$, which $T$ is a prefix of $S$. Obviously, if we use KMP algorithm, we can do it in linear time, and the length of $S$ will be... | [
"hashing",
"string suffix structures",
"strings"
] | 2,200 | null |
526 | E | Transmitting Levels | Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application.
In one secret game developed deep in the ZeptoLab company, the game universe consists of $n$ levels, located in a circle. You can get from level $i$ to levels $i - 1$ and $i + 1$, also yo... | Our task is to compute at least how many number of blocks are needed to partition a circular sequence into blocks whose sum is less than $K$. By monotonicity, it is easy to get the length of maximal blocks which starts from 1 to $n$ in $O(n)$. Assume the block with minimal length is $A$ and its length is $T$, it is obv... | [
"dp",
"implementation"
] | 2,400 | null |
526 | F | Pudding Monsters | In this problem you will meet the simplified model of game Pudding Monsters.
An important process in developing any game is creating levels. A game field in Pudding Monsters is an $n × n$ rectangular grid, $n$ of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the mon... | Actually this problem is to compute how many segments in a permutation forms a permutation of successive integers. We use divide and conquer to solve this problem. If we want to compute the answer for an interval $[1, n]$, we divide this interval into two smaller ones $[1, m], [m + 1, n]$ where $m=\lfloor{\frac{n+1}{2}... | [
"data structures",
"divide and conquer"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
const int N = 2000010;
int mn[N], add[N], cnt[N];
void build(int x, int l, int r) {
mn[x] = l;
add[x] = 0;
cnt[x] = 1;
if (l < r) {
int y = (l + r) >> 1;
build(x + x, l, y);
build(x + x + 1, y + 1, r);
}
}
inline void push(int x) {
if (add[... |
526 | G | Spiders Evil Plan | Spiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom.
Let's consider a rope structure consisting of $n$ nodes and $n - 1$ ropes connecting the nodes. The structure ... | In this task, we are given a tree and many queries. In each query, we are supposed to calculate the maximum total length of $y$ paths with the constraint that $x$ must be covered. Consider $S$ is the union of the paths (it contains nodes and edges). For each query $(x, y)$, if $y > 1$ , then there is always a method th... | [
"greedy",
"trees"
] | 3,300 | null |
527 | A | Playing with Paper | One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular $a$ mm $ × $ $b$ mm sheet of paper ($a > b$). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and c... | It's easy to see that described process is equivalent to the following loop: But such naive approach will obviously lead to verdict TLE, since it makes ~$10, 2015 - 03 - 19^{12}$ operations even on the third sample test. The key idea is to replace repeating subtraction operations with integer division operations. This ... | [
"implementation",
"math"
] | 1,100 | null |
527 | B | Error Correct System | Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings $S$ and $T$ of equal length to be "similar". After a brief search on th... | The first observation is that the new Hamming distance may not be less than the old one minus two, since we change only two characters. So the task is to actually determine, if we can attain decrease by two, one or can't attain decrease at all. The decrease by two is possible if there are two positions with the same tw... | [
"greedy"
] | 1,500 | null |
527 | C | Glass Carving | Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular $w$ mm $ × $ $h$ mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to prac... | Obviously the largest glass piece at any moment is the one that is product of the largest horizontal segment by the largest vertical segment. One of the possible solutions is to carefully implement what described in the statement and keep all horizontal segments and all vertical segments in priority queue or std::set, ... | [
"binary search",
"data structures",
"implementation"
] | 1,500 | null |
527 | D | Clique Problem | The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph $G$. It is required to find a subset of vertices $C$ of the maximum size such that any two of them are connected by an edge in graph $G$. Sounds simple, doesn't ... | One may think that this task is about graph theory, but it after some investigation and several equivalent changes in task statement it can be reduced to the well-known greedy problem. Initially you have that points may lie together in a set if they are not too close, i. e. $|x_{i} - x_{j}| \ge w_{i} + w_{j}$. This i... | [
"data structures",
"dp",
"greedy",
"implementation",
"sortings"
] | 1,800 | null |
527 | E | Data Center Drama | The project of a data center of a Big Software Company consists of $n$ computers connected by $m$ cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan ... | Problem legend asks you to add minimum number of edges to the given connected undirected graph (possibly, with loops and duplicating edges) and choose direction for its edges so that both the incoming and outgoing degrees of all vertices are even. First idea is that the resulting graph before we choose the direction (b... | [
"dfs and similar",
"graphs"
] | 2,600 | null |
528 | D | Fuzzy Search | Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.
Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a st... | There were issues with this task. Intended constraints were actually $n, m, k \le 500000$, and the intended solution was using Fast Fourier Transformation, that leads to $|\ast n\log n$ running time. But unfortunately the statement contained wrong constraints, so we reduced input size during the tour. Nevertheless, w... | [
"bitmasks",
"brute force",
"fft"
] | 2,500 | null |
528 | E | Triangles 3000 | \url{CDN_BASE_URL/2fdd572a668b63052b21147ea5152e78} | Let's draw a bounding box that contains all intersection points. Let's fix a triangle and consider three angles shown on the picture. Calculate area of intersection of those area with the bounding box and call this area to be the "area of an angle". Then it's easy to see, that those three angles are complement to the t... | [
"geometry",
"sortings"
] | 3,100 | /* --- author: enot-the-rockstar ---*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <ctime>
#include <cassert>
#define fs first
#define sc second
#define pb push_back
#define... |
529 | B | Group Photo 2 (online mirror version) | Many years have passed, and $n$ friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.
Simply speaking, the process of photographing can be descr... | In an online mirror version the problem was slightly harder. Let's call people with $w \le h$ \textit{high}, and remaining people \textit{wide}. Let's fix photo height $H$. Let's consider several following cases: If a high person fits into height $H$, we leave him as is. If a high person doesn't fit into height $H$, ... | [
"brute force",
"greedy",
"sortings"
] | 1,900 | null |
533 | A | Berland Miners | The biggest gold mine in Berland consists of $n$ caves, connected by $n - 1$ transitions. The entrance to the mine leads to the cave number $1$, it is possible to go from it to any remaining cave of the mine by moving along the transitions.
The mine is being developed by the InMine Inc., $k$ miners work for it. Each d... | We can add $n - k$ miners with height $0$ and it won't affect answer. So we can assume that numbers of miners and caves are the same. For every cave let's define $t_{i}$ as maximal possible height of miner working in cave $i$ if we wouldn't change any cave. We can calculate it from root to leaves with line $t_{i} = min... | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 3,000 | null |
533 | B | Work Group | One Big Software Company has $n$ employees numbered from $1$ to $n$. The director is assigned number $1$. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person $a$ a subordinates of another person $b$, if either $b$ i... | This problem can be solved by using dynamic programming over subtrees of company hierarchy. Denote as $D[v][e]$ maximum possible efficiency that can be obtained by taking several people from subtree of $v$ so that pairity of their number is $e$ in order condition from statement is fullfilled for all already taken peopl... | [
"dfs and similar",
"dp",
"graphs",
"strings",
"trees"
] | 2,000 | null |
533 | C | Board Game | Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell $(x, y)$ to $(x - 1, y)$ or $(x, y - 1)$. Vasiliy can move his pawn from $(x, y)$ to one of... | We will consider three cases: 1) $x_{p} + y_{p} \le max(x_{v}, y_{v})$. In this case Polycarp can be in $(0, 0)$ after $x_{p} + y_{p}$ moves and Vasiliy will always be ,,behind''. It's enough for Polycarp to make any move and he is always able to do it. It makes Polycarp closer to $(0, 0)$ and after Vasiliy's move we... | [
"games",
"greedy",
"implementation",
"math"
] | 1,700 | null |
533 | D | Landmarks | We have an old building with $n + 2$ columns in a row. These columns support the ceiling. These columns are located in points with coordinates $0 = x_{0} < x_{1} < ... < x_{n} < x_{n + 1}$. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary.
For each column we... | First observation: column crashes only if distance between its neighbours is greater than $2d_{i}$ so it doesn't matter where exactly is this column. The only important thing is how far are left and right neighbour of it. For every column $C$ let's calculate does there exist subset of columns on the left that everythin... | [
"data structures",
"dp"
] | 3,000 | null |
533 | E | Correcting Mistakes | Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.
Polycarp needed to write a code that could, given two words, check whether t... | Suppose that $S$ is obtained from $W$ by deleteing the earlier symbol than $T$. Then it is true that $W = A + x + B + y + C$, $S = A + x + B + C$, $T = A + B + y + C$, where $x$ and $y$ are deleted symbols and $A$, $B$ and $C$ are some (possibly, empty) strings. Let's calculate $A$ as a longest common prefix of $S$ and... | [
"constructive algorithms",
"dp",
"greedy",
"hashing",
"strings",
"two pointers"
] | 1,800 | null |
533 | F | Encoding | Polycarp invented a new way to encode strings. Let's assume that we have string $T$, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in $T$ with its pair letter if there is a ... | There are two possible ideas for solving this task. Fix pair of letters $x$ and $y$. Replace all letters $x$ in $S$ with 1s and all remaining letters with 0s. Do the same for $y$ with string $T$. By using KMP algorithm or Z-function determine all positions where string $T$ can be attached to string $S$ so there is a ma... | [
"hashing",
"string suffix structures",
"strings"
] | 2,400 | null |
534 | A | Exam | An exam for $n$ students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers ($i$ and $i + 1$) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other f... | Is easy to see that $k = n$ with $n \ge 4$. There are many algorithms that can be used to build a correct sequence of length $n$ with $n \ge 4$. For example, students can be seated from left to right with the first to seat students with odd numbers in decreasing order starting with largest odd number. Then similary... | [
"constructive algorithms",
"implementation",
"math"
] | 1,100 | #include <stdio.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int N = 5001;
int n;
int a[N];
int main() {
scanf("%d", &n);
if (n == 2) {
printf("1\n1");
return 0;
}
if (n == 3) {
printf("2\n1 3");
return 0;
}
int c... |
534 | B | Covered Path | The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals $v_{1}$ meters per second, and in the end it is $v_{2}$ meters per second. We know that this section of the route took exactly $t$ seconds to pass.
Assuming that at each of the seconds the speed is c... | It can be easily proved that every second $i$ ($0 \le i \le t - 1$) the maximum possible speed is $v_{i}=\operatorname*{min}\,(v_{1}+d\cdot i,v_{2}+d\cdot(t-i-1))$. You can iterate through $i$ from $0$ to $t - 1$ and the values of $v_{i}$. Solution complexity - $O(t)$. Also you can use next fact. If current speed e... | [
"dp",
"greedy",
"math"
] | 1,400 | #include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int v1, v2;
int n, d;
cin >> v1 >> v2;
cin >> n >> d;
int ans = v1;
int curv = v1;
for(int i = 1; i < n; i++) {
int newv;
for(int dd = d; dd >= -d; dd--) {
newv =... |
534 | C | Polycarpus' Dice | Polycarp has $n$ dice $d_{1}, d_{2}, ..., d_{n}$. The $i$-th dice shows numbers from $1$ to $d_{i}$. Polycarp rolled all the dice and the sum of numbers they showed is $A$. Agrippina didn't see which dice showed what number, she knows only the sum $A$ and the values $d_{1}, d_{2}, ..., d_{n}$. However, she finds it eno... | Solution uses next fact. With $k$ dice $d_{1}, d_{2}, ..., d_{k}$ you can dial any sum from $k$ to $\sum_{i=1}^{k}d_{i}$. This is easily explained by the fact that if there is a way to get the amount of $s > k$, then there is a way to dial the sum equal $s - 1$, which is obtained by decreasing the value of one die by o... | [
"math"
] | 1,600 | #include <stdio.h>
#include <algorithm>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int N = 200002;
int n;
int a[N];
long long A, sum;
int main() {
scanf("%d%I64d", &n, &A);
forn(i, n) {
scanf("%d", &a[i]);
sum += a[i];
}
forn(i, n) {
... |
534 | D | Handshakes | On February, 30th $n$ students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came ... | From here we will not consider resulting permutation but correct handshakes sequence (rearranged given sequence). Formally, the sequence of handshakes count $a_{i}$ is correct if and only if $a_{i + 1} \le a_{i} + 1$ and $a_{i + 1} \equiv a_{i} + 1 \pm od{m}$ and $a_{1} = 0$. To form correct sequence, we can use ... | [
"binary search",
"constructive algorithms",
"data structures",
"greedy"
] | 1,900 | #include <stdio.h>
#include <algorithm>
#include <set>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef pair<int, int> pii;
const int N = 1000001;
int n;
set<pii> a[3];
int ans[N];
int main() {
scanf("%d", &n);
forn(i, n) {
int x;
scanf("%d", &x);
... |
534 | E | Berland Local Positioning System | In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are $n$ bus stops located along the street, the $i$-th of them is located at the distance $a_{i}$ from the central square, all distances are distinct, the stops are numbered in... | Suppose that the bus started his way from the stop with number 1 and modulate its way during $m$ stops. For every stop we will calculate how many times this stop was visited by the bus at that way. Check if that counts match counts in the input and update the answer if needed. Then we will try to move the start stop to... | [
"constructive algorithms",
"greedy",
"hashing",
"implementation"
] | 2,400 | #define _CRT_SECURE_NO_DEPRECATE
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stack>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <set>
#include <iterator>
#include <memory.h>
#include <vector>
#include <map>
#include <queue>
#include <iomanip>
#i... |
534 | F | Simplified Nonogram | In this task you have to write a program dealing with nonograms on fields no larger than $5 × 20$.
Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous bla... | This task has several solution algorithms. One of them could be described next way. Let's divide $n \times m$ field into two parts with almost same number of columns (it will be $n \times k$ and $n \times (m - k)$). Let's solve the puzzle for every part of the field with brute-force algorithm (considering column ... | [
"bitmasks",
"dp",
"hashing",
"meet-in-the-middle"
] | 2,400 | #include <cstdio>
#include <cstdlib>
#include <vector>
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define sz(a) (int)(a.size())
const int N = 5;
const int M = 20;
const int B = 6;
const int S = 7776; // B ^ N
using namespace std;
int n, m, a[N], b[M], bc[1 << N];
typedef char dpmat[M / 2 + 2][S][1 << ... |
535 | A | Tavas and Nafas | Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
He ate coffee mix without... | First of all check if $n$ is one of the values $0, 10, 11, \dots , 19$. Then, let's have array $x[]$ = {"", "", "twenty", "thirty", \dots , "ninety"} and $y[]$ = {"", "one", \dots , "nine"}. Let $a={\frac{n}{10}}$ and $b = n modulo 10$. If $n$ is not one of the values above, then if $a = 0$, print $y[b]$, else if $b... | [
"brute force",
"implementation"
] | 1,000 | #include <iostream>
using namespace std;
string a[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
string b[10] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
string c[10] = {"tmp", "ten", "twenty", "thirty", "fo... |
535 | B | Tavas and SaDDas | \underline{Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."}
The problem ... | Sol1: Consider $n$ has $x$ digits, $f(i) =$ decimal representation of binary string $i$, $m$ is a binary string of size $x$ and its $i - th$ digit is 0 if and only if the $i - th$ digit of $n$ is $4$. Finally, answer equals to $2^{1} + 2^{2} + \dots + 2^{x - 1} + f(m) + 1$. Time complexity: $O(log(n))$ Sol2: Count th... | [
"bitmasks",
"brute force",
"combinatorics",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
535 | C | Tavas and Karafs | \underline{Karafs is some kind of vegetable in shape of an $1 × h$ rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.}
Each Karafs has a positive integer height. Tavas has an infinite \textbf{1-based} sequence of Karafses. The height of the $... | Lemma: Sequence $h_{1}, h_{2}, \dots , h_{n}$ is $(m, t) -$Tavas-Eatable if and only if $max(h_{1}, h_{2}, \dots , h_{n}) \le t$ and $h_{1} + h_{2} + \dots + h_{n} \le m \times t$. Proof: only if is obvious (if the sequence is Tavas-Eatable, then it fulfills the condition). So we should prove that if the cond... | [
"binary search",
"greedy",
"math"
] | 1,900 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
535 | D | Tavas and Malekas | \underline{Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string $s$ of length $n$ comes out from Tavas' mouth instead.}
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on $s$. Malekas has a favorite string $p$. He determined al... | First of all you need to find uncovered positions in $s$ (because rest of them will determine uniquely). If there is no parados in covered positions (a position should have more than one value), then the answer will be $0$, otherwise it's $26^{uncovered}$. To check this, you just need to check that no two consecutive m... | [
"greedy",
"hashing",
"string suffix structures",
"strings"
] | 1,900 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
535 | E | Tavas and Pashmaks | \underline{Tavas is a cheerleader in the new sports competition named "Pashmaks".}
This competition consists of two part: swimming and then running. People will immediately start running $R$ meters after they finished swimming exactly $S$ meters. A winner is a such person that nobody else finishes running before him/h... | For each competitor put the point $\textstyle{{\binom{1}{s_{i}}},\ {\frac{1}{r_{i}}}}$ in the Cartesian plane. So, the time a competitor finishes the match is $\underline{{{S}}}_{s i}+\frac{R}{r_{i}}=(S,R).(\underline{{{1}}}_{s i},\underline{{{1}}}_{t})$. Determine their convex hull(with maximum number of points. i.e i... | [
"geometry",
"math"
] | 2,600 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
536 | D | Tavas in Kansas | Tavas lives in Kansas. Kansas has $n$ cities numbered from 1 to $n$ connected with $m$ bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.
Tavas invented a game and ... | For each vertex $v$, put a point $(dis(s, v), dis(v, t))$ with its point (score) in the Cartesian plane. The first player in his/her turn chooses a vertical line and erases all the points on its left side. Second player in his/her turn chooses a horizontal line and erases all the point below it. Each player tries to ma... | [
"dp",
"games"
] | 2,900 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
536 | E | Tavas on the Path | Tavas lives in Tavaspolis. Tavaspolis has $n$ cities numbered from $1$ to $n$ connected by $n - 1$ bidirectional roads. There exists a path between any two cities. Also each road has a length.
Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like $s = s_{1}s_{2}... s_{k}$, ... | Let's call the answer for vertices $v$ and $u$ with edges $e_{1}, e_{2}, ..., e_{k}$ on the path, score of sequence $w(e_{1}), w(e_{2}), ..., w(e_{k})$. Use heavy-light decomposition. Decompose the edges into chains. So, for each Query, decompose the path into subchains. After solving the problem for them, combine them... | [
"data structures",
"divide and conquer",
"trees"
] | 3,100 | #include <bits/stdc++.h>
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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#... |
538 | A | Cutting Banner | A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforces$^{ω}$ that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-... | Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word CODEFORCES. The (somewhat vague) wording some substring in the Eng... | [
"brute force",
"implementation"
] | 1,400 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | B | Quasi Binary | A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer $n$. Represent it as a sum of minimum number of quasibinary numbers. | $n$ is up to $10^{6}$. We may note that there are only $2^{6} + 1 = 65$ quasi-binary numbers not exceeding $10^{6}$, so we could find them all and implement a DP solution that counts the optimal representation for all numbers up to $n$, or even a brute-force recursive solution (which is not guaranteed to pass, but has ... | [
"constructive algorithms",
"dp",
"greedy",
"implementation"
] | 1,400 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | C | Tourist's Notes | A tourist hiked along the mountain range. The hike lasted for $n$ days, during each day the tourist noted height above the sea level. On the $i$-th day height was equal to some integer $h_{i}$. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most... | We want to make the maximum height as large as possible. Consider the part of the chain that was travelled between $d_{i}$ and $d_{i + 1}$; we can arrange it in any valid way independently of any other parts of the chain, thus we consider all these parts separately. There also parts before $d_{1}$ and after $d_{n}$, bu... | [
"binary search",
"brute force",
"greedy",
"implementation",
"math"
] | 1,600 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | D | Weird Chess | Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.
Igor's chessboard is a square of size $n × n$ cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pie... | Instead of trying to find out where the piece may go, let's try to find out where it can not go. Initially mark all the moves as possible; if there is a field ($x_{1}$, $y_{1}$) containing a piece, and a field ($x_{2}$, $y_{2}$) not containing a piece and not being attacked, clearly a move ($x_{2} - x_{1}$, $y_{2} - y_... | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,800 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | E | Demiurges Play Again | Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.
There is a rooted tree on $n$ nodes, $m$ of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves... | With such large constraints our only hope is the subtree dynamic programming. Let us analyze the situation and how the subtrees are involved. Denote $w(v)$ the number of leaves in the subtree of $v$. Suppose that a non-leaf vertex $v$ has children $u_{1}$, $...$, $u_{k}$, and the numbers to arrange in the leaves are 1,... | [
"dfs and similar",
"dp",
"math",
"trees"
] | 2,200 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | F | A Heap of Heaps | Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.
The teacher gave Andrew an array of $n$ numbers $a_{1}$, $...$, $a_{n}$. After that he asked Andrew for each $k$ from 1 to $n - 1... | The first approach. For a given $k$ and an element $v$, how do we count the number of children of $v$ that violate the property? This is basically a range query 'how many numbers in the range are greater than $v$' (because, evidently, children of any element occupy a subsegment of the array); the answers for every $k$ ... | [
"brute force",
"data structures",
"math",
"sortings"
] | 2,200 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
538 | G | Berserk Robot | Help! A robot escaped our lab and we need help finding it.
The lab is at the point $(0, 0)$ of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a program — a string of length $l$, consisting of characters U, L, D, R. Each second the robot executes the next command in his progra... | First of all, we'll simplify the problem a bit. Note that after every command the values of $x + y$ and $x - y$ are altered by $ \pm 1$ independently. Suppose we have a one-dimensional problem: given a sequence of $x$'s and $t$'s, provide a looped program of length $l$ with commands $ \pm 1$ which agrees with the dat... | [
"constructive algorithms",
"math",
"sortings"
] | 3,100 | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <numeric>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define mp make_pair
#define fi first
#define s... |
538 | H | Summer Dichotomy | $T$ students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least $t$ students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!)
During a sh... | The problem has several possible approaches. The first approach. More popular one. Forget about $t$ and $T$ for a moment; we have to separate teachers into two groups so that no conflicting teachers are in the same group, and the number of students in each group can be chosen to satisfy all the teachers. Consider a con... | [
"2-sat",
"data structures",
"dfs and similar",
"greedy"
] | 3,200 | #include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define s... |
540 | A | Combination Lock | Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by $n$ rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn ... | For every symbol we should determine how to rotate the disk. This can be done either by formula: $min(abs(a[i] - b[i]), 10 - abs(a[i] - b[i]))$ or even by the two for cycles: in both directions. | [
"implementation"
] | 800 | null |
540 | B | School Marks | Little Vova studies programming in an elite school. Vova and his classmates are supposed to write $n$ progress tests, for each test they will get a mark from 1 to $p$. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all t... | First count the number of marks that are less than $y$. If there are more than $\scriptstyle{\frac{n-1}{2}}$ such marks, we can't satisfy the second condition (about the median), and the answer is -1. Otherwise we can get exactly such number of $y$ marks so that the total number of marks greater than or equal to $y$ is... | [
"greedy",
"implementation"
] | 1,700 | null |
540 | C | Ice Cave | You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.
The level of the cave where you are is a rectangular square grid of $n$ rows and $m$ columns. Each cell consis... | There are three cases here, though some of them can be merged. If the start and finish cells are equal, let's count the intact neighbours of this cell. If there is one, move there and instantly move back - the answer is YES. Otherwise it's NO. If the start and finish cells are neighbours, the solution depends on the ty... | [
"dfs and similar"
] | 2,000 | null |
540 | D | Bad Luck Island | The Bad Luck Island is inhabited by three kinds of species: $r$ rocks, $s$ scissors and $p$ papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill... | Let's count the values dp[r][s][p] - the probability of the situation when r rocks, s scissors and p papers are alive. The initial probability is 1, and in order to calculate the others we should perform the transitions. Imagine we have r rocks, s scissors and p papers. Let's find the probability of the rock killing sc... | [
"dp",
"probabilities"
] | 1,900 | #include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
typedef long double ld;
ld a[105][105][105];
int main() {
int R, S, P;
cin >> R >> S >> P;
a[R][S][P] = 1;
for (int sum = R + S + P; sum > 0; sum--) {
for (int r = R; r >= 0; ... |
540 | E | Infinite Inversions | There is an infinite sequence consisting of all positive integers in the increasing order: $p = {1, 2, 3, ...}$. We performed $n$ swap operations with this sequence. A $swap(a, b)$ is an operation of swapping the elements of the sequence on positions $a$ and $b$. Your task is to find the number of inversions in the res... | At first find the position of each element which is used in swap (using map). Now let's find the answer. It consists of the two parts. First part is the number of inversions formed by only whose elements which took part in the swaps. They can be counted by one of the standard ways: mergesort or Fenwick tree. The second... | [
"binary search",
"data structures",
"implementation",
"sortings",
"trees"
] | 2,100 | class E {
static class Item implements Comparable<Item> {
int pos, val;
public Item(int pos, int val) {
this.pos = pos;
this.val = val;
}
public int compareTo(Item o) {
if (pos != o.pos) {
return Integer.compare(pos, o.pos);
... |
542 | A | Place Your Ad Here | Ivan Anatolyevich's agency is starting to become famous in the town.
They have already ordered and made $n$ TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the $i$-th video can only be shown within the time r... | Let's fix the TV channel window and look for a commerical having the largest intersection with it. There are four types of commercials: lying inside the window, overlapping the window and partially intersecting the window from the left and from the right. It's easy to determine if there is overlapping commercial: it's ... | [
"data structures",
"sortings"
] | 2,400 | null |
542 | B | Duck Hunt | A duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point $(0, 0)$. As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately — $r$ or... | First of all, let's say that ducks stay still and the one that moves is the hunter. Let's define the value $F[x][s]$ as the minimum number of ducks among having the right end no further than $x$, that we can't shot if the last shot was in the point $s$. In particular, the value $F[x][s]$ includes all ducks located insi... | [
"data structures"
] | 3,100 | null |
542 | C | Idempotent functions | Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set ${1, 2, ..., n}$ is such function $g:\{1,2,\cdot\cdot,n\}\to\{1,2,\cdot\cdot,n\}$, that for any $x\in\{1,2,\cdot\cdot,n\}$ the formula $g(g(x)) = g(x)$ holds.
Let's denote as $f^{(k)}(x)$ the function $f$ applied $k$ times... | In order to solve this task it's good to understand how does the graph corresponding the function from ${1, ..., n}$ to itself looks. Let's consider a graph on vertices $1, ..., n$ with edges from vertex $i$ to the vertex $f(i)$. Such graph always looks like a set of cycles with several trees leading to that cycles. Ho... | [
"constructive algorithms",
"graphs",
"math"
] | 2,000 | null |
542 | D | Superhero's Job | It's tough to be a superhero. And it's twice as tough to resist the supervillain who is cool at math. Suppose that you're an ordinary Batman in an ordinary city of Gotham. Your enemy Joker mined the building of the city administration and you only have several minutes to neutralize the charge. To do that you should ent... | First step is to understand the properties of a Joker function. It's important property is that it is multiplicative: $J(ab) = J(a)J(b)$ for $(a, b) = 1$, so we can write the value of function knowing the factorization of an argument: $J(p_{1}^{k1}p_{2}^{k2}... p_{m}^{km}) = J(p_{1}^{k1})J(p_{2}^{k2})... J(p_{m}^{km}) ... | [
"dfs and similar",
"dp",
"hashing",
"math",
"number theory"
] | 2,600 | null |
542 | E | Playing on Graph | Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.
Vova has a non-directed graph consisting of $n$ vertices and $m$ edges without loops and multiple edges. Let's define the operation of contraction two vertices $a$ and $b$ that are \textbf{not connected by a... | First, if the original graph isn't bipartite then the answer is (-1). Indeed, any odd cycle, while being contracted by the pair of vertices, always produces an odd cycle of smaller size, so at some point we will get a triangle that blocks us from doing anything. From the other way, each bipartite component can be contr... | [
"graphs",
"shortest paths"
] | 2,600 | null |
542 | F | Quest | Polycarp is making a quest for his friends. He has already made $n$ tasks, for each task the boy evaluated how interesting it is as an integer $q_{i}$, and the time $t_{i}$ in minutes needed to complete the task.
An interesting feature of his quest is: each participant should get the task that is best suited for him, ... | This task can be solved in lot of ways. The most straightforward is DP. The task can be seen in the following way. We want some set of vertices as leaves and for each potential leaf we know the upper bound for its depth and its cost. Let's sweep over the tree from down to up. Let's calculate the value $D[h][c]$ that is... | [
"dp",
"greedy"
] | 2,100 | null |
543 | A | Writing Code | Programmers working on a large project have just received a task to write exactly $m$ lines of code. There are $n$ programmers working on a project, the $i$-th of them makes exactly $a_{i}$ bugs in every line of code that he writes.
Let's call a sequence of non-negative integers $v_{1}, v_{2}, ..., v_{n}$ a plan, if $... | Let's create the solution, which will work too slow, but after that we will improve it. Let's calculate the following dynamic programming $z[i][j][k]$ - answer to the problem, if we already used exactly $i$ programmers, writed exactly $j$ lines of code, and there are exactly $k$ bugs. How we can do transitions in such ... | [
"dp"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 505;
int a[N];
int z[2][N][N];
int main() {
int n, bl, bugs, md;
scanf("%d %d %d %d", &n, &bl, &bugs, &md);
forn(i, n) scanf("%d", &a[i]);
z[0][0][0] = 1;
for(int it = 1; it <= n; it++){
... |
543 | B | Destroying Roads | In some country there are exactly $n$ cities and $m$ bidirectional roads connecting the cities. Cities are numbered with integers from $1$ to $n$. If cities $a$ and $b$ are connected by a road, then in an hour you can go along this road either from city $a$ to city $b$, or from city $b$ to city $a$. The road network is... | Let's solve easiest task. We have only one pair of vertices, and we need to calculate smallest amout of edges, such that there is a path from first of vertex to the second. It's clear, that the answer for that problem equals to shortest distance from first vertex to the second. Let's come back to initial task. Let's $d... | [
"constructive algorithms",
"graphs",
"shortest paths"
] | 2,100 | #include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int N = 5005;
int d[N][N];
vector < int > g[N];
int main() {
memset(d, -1, sizeof d);
int n, m;
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++) {
int a, b;
scanf("%d %d", &a, &b);
a--, b--;
... |
543 | C | Remembering Strings | You have multiset of $n$ strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position $i$ and some letter $c$ of the English alphabet, such that this string is the only string in the multiset that has letter $c$ in pos... | First that we need to notice, that is amout of strings is smaller then alphabet size. It means, that we can always change some character to another, because at least one character is not used by some string. After that we need handle two cases: We can change exactly one character to another. The cost of such operation ... | [
"bitmasks",
"dp"
] | 2,500 | #include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
const int N = 20;
const int leng = 300;
string s[N];
int cost[N][leng], c[N][leng], sv[N][leng], a[N][leng];
int d[1 << N];
int main() {
int n, m;
cin >> n >> m;
forn(i, n) cin >> s[i];
forn(i, n) forn(j, m)... |
543 | D | Road Improvement | The country has $n$ cities and $n - 1$ bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from $1$ to $n$ inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will ass... | Let's suppose $i$ is a root of tree. Let's calculate extra dynamic programming $d[i]$ - answer to the problem for sub-tree with root $i$ We can understand, that d[i] equals to the following value: $d[i]=\prod_{i}(d[j]+1)$ - where $j$ is a child of the vertex $i$. It's nice. After that answer to problem for first vertex... | [
"dp",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define ford(i, n) for(int i = int(n) - 1; i >= 0; i--)
#define sz(a) int((a).size())
const int N = 200000 + 300;
const int md = 1000000007;
vector < int > g[N], pref[N], suf[N];
int ans[N], d[N];
void dfs(int s){... |
543 | E | Listening to Music | Please note that the memory limit differs from the standard.
You really love to listen to music. During the each of next $s$ days you will listen to exactly $m$ songs from the playlist that consists of exactly $n$ songs. Let's number the songs from the playlist with numbers from $1$ to $n$, inclusive. The quality of s... | Let's sort all songs in decreasing order. We will iterate over songs, and each time we will say, that now current song will fully satisfy our conditions. So, let's $s_{i} = 0$, is song $i$ was not processed yet and $s_{i} = 1$ otherwise. Let $v_{i}=\sum_{i=i}^{j=i+m-1}s_{j}$. It's clear, when we add new song in positio... | [
"constructive algorithms",
"data structures"
] | 3,200 | #include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define sz(a) int((a).size())
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define mp make_pair
#define sc second
#define ft first
using namespace std;
const int M = 512;
const int N = M * M;
int blvalue[M][M];
int ftvalue[M]... |
544 | A | Set of Strings | You are given a string $q$. A sequence of $k$ strings $s_{1}, s_{2}, ..., s_{k}$ is called beautiful, if the concatenation of these strings is string $q$ (formally, $s_{1} + s_{2} + ... + s_{k} = q$) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the be... | In that task you need to implement what was written in the statements. Let's iterate over all characters of string and keep array $used$. Also let's keep current string. If current character was not used previously, then let's put current string to the answer and after that we need to clear current string. Otherwise, l... | [
"implementation",
"strings"
] | 1,100 | k = input()
s = raw_input()
ans = []
cur = ""
used = set()
for i in range(len(s)):
if s[i] not in used:
if len(cur) > 0:
ans.append(cur)
cur = ""
cur += s[i]
used.add(s[i])
else:
cur += s[i]
ans.append(cur)
if len(ans) < k:
print("NO")
else:
print("YES")
for i in range(k, len(ans)):
ans[k - 1] += a... |
544 | B | Sea and Islands | A map of some object is a rectangular field consisting of $n$ rows and $n$ columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly $k$ islands appear on the map. We will call a set of sand cells to be \textbf{island} if it is possible to get from each o... | It's clear to understand, that optimal answer will consists of simple cells, for which following condition fullfills: the sum of indices of row and column is even. We will try to put $k$ islands in such way, and if it's impossible, we will report that answer is NO. Try to prove that this solution is optimal. | [
"constructive algorithms",
"implementation"
] | 1,400 | #include <cstdio>
#include <string>
#include <vector>
using namespace std;
int main() {
int n, k;
scanf("%d %d", &n, &k);
if (n == 5 && k == 2) {
puts("YES");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if (i & 1) printf("L");
else printf("S");
}
puts("");... |
545 | A | Toy Cars | Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are $n$ toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turne... | We can find all information about $i$-th car collisions in the $i$-th row of the matrix $A$. More specific, if there is at least one 1 or 3 at $i$-th row, then $i$-th car isn't good (it was turned over in at least one collision). Otherwise, $i$-th car is good. We just need to check this condition for each car. | [
"implementation"
] | 900 | null |
545 | B | Equidistant String | Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:
We will define the distance between two strings $s$ and $t$ of the same length consisting of digits zero and one as the... | One can see, that if $s_{i} = t_{i}$ for some $i$, then the value of $p_{i}$ isn't important for us. Really, if we make $p_{i}$ equal to $s_{i}$ then it also be equal to $t_{i}$. And if we make $p_{i}$ not equal to $s_{i}$ then it also be not equal to $t_{i}$. So, we have an answer that is closer or further to both of ... | [
"greedy"
] | 1,100 | null |
545 | C | Woodcutters | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are $n$ trees located along the road at points with coordinates $x_{1}, x_{2}, ..., ... | One can solve this problem using dynamic programming or greedy algorithm. Start with DP solution. Define $stay_{i}$, $left_{i}$ and $right_{i}$ as maximal count of trees that woodcutters can fell, if only trees with number from $1$ to $i$ exist, and $i$-th tree isn't cutted down, $i$-th tree is cutted down and fallen l... | [
"dp",
"greedy"
] | 1,500 | null |
545 | D | Queue | Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are $n$ people in the queue. For each person we know time $t_{i}$ needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total t... | We can solve this problem by greedy algorithm. Let's prove that it is always possible find an answer (queue with the maximal number of not disappointed people), where all not disappointed people are at the begin of queue. Assume the contrary - there are two position $i$ and $j$ such that $i < j$, persons at position fr... | [
"greedy",
"implementation",
"sortings"
] | 1,300 | null |
545 | E | Paths and Trees | Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a \... | It's true, that Dijkstra modification, where in case of equal distances we take one with shorter last edge, find an answer. For prove that let's do some transformation with graph. At first, find all shortest paths from $u$ to other vertices. Define $d_{i}$ as the length of shortest path from $u$ to $i$. After that, we ... | [
"graphs",
"greedy",
"shortest paths"
] | 2,000 | null |
546 | A | Soldier and Bananas | A soldier wants to buy $w$ bananas in the shop. He has to pay $k$ dollars for the first banana, $2k$ dollars for the second one and so on (in other words, he has to pay $i·k$ dollars for the $i$-th banana).
He has $n$ dollars. How many dollars does he have to borrow from his friend soldier to buy $w$ bananas? | We can easily calculate the sum of money that we need to buy all the bananas that we want, let's name it x. If n > = x the answer is 0, because we don't need to borrow anything. Otherwise the answer is x - n. | [
"brute force",
"implementation",
"math"
] | 800 | null |
546 | B | Soldier and Badges | Colonel has $n$ badges. He wants to give one badge to every of his $n$ soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the se... | Let's count the number of badges with coolness factor 1, 2 and so on. Then, let's look at the number of badges with value equal to 1. If it's greater than 1, we have to increase a value of every of them except for one. Then, we look at number of badges with value 2, 3 and so on up to 2n - 2 (because maximum value of ba... | [
"brute force",
"greedy",
"implementation",
"sortings"
] | 1,200 | null |
546 | C | Soldier and Cards | Two bored soldiers are playing card war. Their card deck consists of exactly $n$ cards, numbered from $1$ to $n$, \textbf{all values are different}. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On ... | It's easy to count who wins and after how many "fights", but it's harder to say, that game won't end. How to do it? Firstly let's count a number of different states that we can have in the game. Cards can be arranged in any one of n! ways. In every of this combination, we must separate first soldier's cards from the se... | [
"brute force",
"dfs and similar",
"games"
] | 1,400 | null |
546 | D | Soldier and Number Game | Two soldiers are playing a game. At the beginning first of them chooses a positive integer $n$ and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer $x > 1$, such that $n$ is divisible by $x$ and replacing $n$ with $n ... | Firstly we have to note, that second soldier should choose only prime numbers. If he choose a composite number x that is equal to p * q, he can choose first p, then q and get better score. So our task is to find a number of prime factors in factorization of n. Now we have to note that factorization of number a! / b! is... | [
"constructive algorithms",
"dp",
"math",
"number theory"
] | 1,700 | null |
546 | E | Soldier and Traveling | In the country there are $n$ cities and $m$ bidirectional roads between them. Each city has an army. Army of the $i$-th city consists of $a_{i}$ soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at \textbf{moving along at most one road}.
... | There are few ways to solve this task, but I'll describe the simplest (in my opinion) one. Let's build a flow network in following way: Make a source. Make a first group of vertices consisting of n vertices, each of them for one city. Connect a source with ith vertex in first group with edge that has capacity ai. Make ... | [
"flows",
"graphs",
"math"
] | 2,100 | null |
547 | A | Mike and Frog | Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time $0$), height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$. Each second, Mike waters Abol and Xaniar.
So, if height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$, after one second height of Xaniar will beco... | In this editorial, consider $p = m$, $a = h_{1}$, $a' = a_{1}$, $b = h_{2}$ and $b' = a_{2}$, $x = x_{1}$, $y = y_{1}$, $X = x_{2}$ and $Y = y_{2}$. First of all, find the number of seconds it takes until height of Xaniar becomes $a'$ (starting from $a$) and call it $q$. Please note that $q \le p$ and if we don't rea... | [
"brute force",
"greedy",
"implementation",
"math"
] | 2,200 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
547 | B | Mike and Feet | Mike is the president of country What-The-Fatherland. There are $n$ bears living in this country besides Mike. All of them are standing in a line and they are numbered from $1$ to $n$ from left to right. $i$-th bear is exactly $a_{i}$ feet high.
A group of bears is a non-empty contiguous segment of the line. The size ... | For each $i$, find the largest $j$ that $a_{j} < a_{i}$ and show it by $l_{i}$ (if there is no such $j$, then $l_{i} = 0$). Also, find the smallest $j$ that $a_{j} < a_{i}$ and show it by $r_{i}$ (if there is no such $j$, then $r_{i} = n + 1$). This can be done in $O(n)$ with a stack. Pseudo code of the first part (sec... | [
"binary search",
"data structures",
"dp",
"dsu"
] | 1,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... |
547 | C | Mike and Foam | Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are $n$ kinds of beer at Rico's numbered from $1$ to $n$. $i$-th kind of beer has $a_{i}$ milliliters of foam on it.
Maxim is Mike's boss. Today he told Mike to perform $q$ queries. Initially the shelf is empty. In each reque... | We define that a number $x$ is good if and only if there is no $y > 1$ that $y^{2}$ is a divisor of $x$. Also, we define function $f(x)$ as follow: Consider $x = p_{1}^{a1} \times p_{2}^{a2} \times ... \times p_{k}^{ak}$ where all $p_{i}$s are prime. Then, $f(x) = a_{1} + a_{2} + ... + a_{n}$. Use simple inclusio... | [
"bitmasks",
"combinatorics",
"dp",
"math",
"number theory"
] | 2,300 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
547 | D | Mike and Fish | As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
He has marked $n$ distinct points in the plane. $i$-th point is point $(x_{i}, y_{i})$. He wants to put exactly one fish in each of these points such t... | Consider a bipartite graph. In each part (we call them first and second part) there are $L = 2 \times 10^{5}$ vertices numbered from $1$ to $L$. For each point $(x, y)$ add an edge between vertex number $x$ from the first part and vertex number $y$ from the second part. In this problem, we want to color edges with tw... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,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... |
547 | E | Mike and Friends | What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears!
In that country there is a rock band called CF consisting of $n$ bears (including Mike) numbered from $1$ to $n$.
Phon... | $call(i, j) = match(s_{jins}_{i})$ which $match(tins)$ is the number of occurrences of $t$ in $s$. Concatenate all strings together in order (an put null character between them) and call it string $S$. We know that $|S|=\sum_{i=1}^{n}|s_{i}|+n-1$. Consider $N = 5 \times 10^{5}$. Consider Consider for each $i$, $S_{xi... | [
"data structures",
"string suffix structures",
"strings",
"trees"
] | 2,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... |
548 | A | Mike and Fax | While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string $s$.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly $k$ messages ... | Consider characters of this string are number 0-based from left to right. If $|s|$ is not a multiply of $k$, then answer is "NO". Otherwise, let $l e n={\frac{\log}{\frac{\langle\pi\rangle}{k}}}$. Then answer is "Yes" if and only if for each $i$ that $0 \le i < |s|$, $s_{i} = s_{(i / len) * len + len - 1 - (i%len)}$ ... | [
"brute force",
"implementation",
"strings"
] | 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... |
548 | B | Mike and Fun | Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an $n × m$ grid, there's exactly one bear in each cell. We denote the bear standing in column number $j$ of row number $i$ by $(i, j)$. Mike's hands are on his ears (since he's the judge) and each bear standing... | Consider this problem: We have a binary sequence $s$ and want to find the maximum number of consecutive 1s in it. How to solve this? Easily: Finally, answer to this problem is ans. For each row $r$ of the table, let $ans_{r}$ be the maximum number of consecutive 1s in it (we know how to calculate it in $O(m)$ right ?).... | [
"brute force",
"dp",
"greedy",
"implementation"
] | 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... |
549 | A | Face Detection | The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a $2 ... | One should iterate through each 2x2 square and check if it is possible to rearrange letters in such way they they form the word "face". It could be done i.e. by sorting all letters from the square in alphabetic order and comparing the result with the word "acef"(sorted letters of word "face"). | [
"implementation",
"strings"
] | 900 | null |
549 | B | Looksery Party | The Looksery company, consisting of $n$ staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much tim... | In any cases there is such set of people that if they come on party and send messages to their contacts then each employee receives the number of messages that is different from what Igor pointed. Let's show how to build such set. There are 2 cases. There are no zeros among Igor's numbers. So if nobody comes on party t... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | 2,300 | null |
549 | C | The Game Of Parity | There are $n$ cities in Westeros. The $i$-th city is inhabited by $a_{i}$ people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly $k$ cities ... | If n = k no moves may be done. The winner is determined with starting parity of citizens' number. Otherwise let's see that the player making the last move may guarantee his victory, if there are both odd and even cities when he makes the move. He just selects the city of which parity he should burn to obtain required p... | [
"games"
] | 2,200 | null |
549 | D | Haar Features | The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.
Let's consider a rectangular image that is represent... | This problem had a complicated statement but it is very similar to the real description of the features. Assume that we have a solution. It means we have a sequence of prefix-rectangles and coefficients to multiply. We can sort that sequence by the bottom-right corner of the rectangle and feature's value wouldn't be ch... | [
"greedy",
"implementation"
] | 1,900 | null |
549 | E | Sasha Circle | Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has $n$ points, Sasha — $m$. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so t... | Author's solution has complexity $O((|A|+|B|)C^{\frac{2}{3}}+|A|l o g|A|+|B|l o g|B|)$, where $C$ is a maximum absolute value of the coordinates of all given points. Let's call a set of points $A$ and $B$ separable if there's a circle inside or on the boundary of which lie all the points of one set. When there're no po... | [
"geometry",
"math"
] | 2,700 | null |
549 | F | Yura and Developers | Yura has a team of $k$ developers and a list of $n$ tasks numbered from $1$ to $n$. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing \textbf{no less than 2 numbers}, i. e. a sequence of form $l, l +... | Let's consider following solution: Let $f(l, r)$ be the solution for $[l, r]$ subarray. It's easy to see that $f(1, n)$ is the answer for the given problem. How should one count $f(l, r)$? Let $m$ be an index of the maximum value over subarray $[l, r]$. All the $good$ segments can be divided into two non-intersecting s... | [
"data structures",
"divide and conquer"
] | 2,800 | null |
549 | G | Happy Line | Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of $n$ Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people,... | Let's reformulate the condition in terms of a certain height the towers, which will be on the stairs. Then an appropriate amount of money of a person in the queue is equal to the height of the tower with the height of the step at which the tower stands. And the process of moving in the queue will be equivalent to raisi... | [
"constructive algorithms",
"greedy",
"sortings"
] | 2,200 | null |
549 | H | Degenerate Matrix | The determinant of a matrix $2 × 2$ is defined as follows:
\[
\operatorname*{det}\left(\begin{array}{c c}{{a}}&{{b}}\\ {{c}}&{{d\rangle}}=a d-b c
\]
A matrix is called degenerate if its determinant is equal to zero.
The norm $||A||$ of a matrix $A$ is defined as a maximum of absolute values of its elements.
You are... | The rows of degenerate matrix are linear dependent so the matrix B can be written in the following way: Suppose Let's assume that elements of the first row of matrix $A$ are coordinates of point $a_{0}$ on two-dimensional plane and the elements of the second row are coordinates of point $a_{1}$. Assume that the rows of... | [
"binary search",
"math"
] | 2,100 | null |
550 | A | Two Substrings | You are given string $s$. Your task is to determine if the given string $s$ contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | There are many ways to solve this problem. Author solution does the following: check if substring "AB" goes before "BA", and then vice versa, if "BA" goes before "AB". You can do it in the following way: find the first occurence of "AB" then check all substrings of length two to the right of it to check if substring "B... | [
"brute force",
"dp",
"greedy",
"implementation",
"strings"
] | 1,500 | null |
550 | B | Preparing Olympiad | You have $n$ problems. You have estimated the difficulty of the $i$-th one as integer $c_{i}$. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the conte... | Because of the low constraints, this problem can be solved by complete search over all problem sets (there are $2^{n}$ of them). For every potential problem set (which can be conviniently expressed as bit mask) we need to check if it satisfies all needed criteria. We can simply find the sum of problem complexities and ... | [
"bitmasks",
"brute force"
] | 1,400 | null |
550 | C | Divisibility by Eight | You are given a non-negative integer $n$, its decimal representation consists of at most $100$ digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a ... | This problem can be solved with at least two different approaches. The first one is based on the "school" property of the divisibility by eight - number can be divided by eight if and only if its last three digits form a number that can be divided by eight. Thus, it is enough to test only numbers that can be obtained f... | [
"brute force",
"dp",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
#define sz(x) (int) x.size()
#define all(a) a.begin(), a.end()
#define prev sadasdjksgjkasjdklaj
const int MAXN = 105;
string s;
int n;
bool dp[MAXN][8];
int prev[MAXN][8];
int main() {
getline(cin, s);
n = sz(s);
memset(prev, -1, sizeof(prev));
... |
550 | D | Regular Bridge | An undirected graph is called $k$-regular, if the degrees of all its vertices are equal $k$. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected $k$-regular graph containing at least one bridge, or else state that su... | Let's prove that there is no solution for even $k$. Suppose our graph contains some bridges, $k = 2s$ (even), all degrees are $k$. Then there always exists strongly connected component that is connected to other part of the graph with exactly one bridge. Consider this component. Let's remove bridge that connects it to ... | [
"constructive algorithms",
"graphs",
"implementation"
] | 1,900 | null |
550 | E | Brackets in Implications | Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false.
Implication is written by using character '$\to$', and the arguments and the result of the implication are written as '0' ($false$) and '1' ($true... | Let input consists of $a_{1}\longrightarrow a_{2}\longrightarrow\cdot\cdot\cdot\longrightarrow a_{n}$, $a_{i}$ is $0$ or $1$ for all $i$. Let's show that there is no solution in only two cases: 1) $a_{n} = 1$. $x\to1=1$, for all $x$, and no parentheses can change last $1$ to $0$. 2) Input has the form $1\to1\to1\to\cdo... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 2,200 | null |
551 | A | GukiZ and Contest | Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, $n$ students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from $1$ to $n$. Let's denot... | Very simple implementation problem. Just implement what is written in the statement: for every element of array, find the number of array elements greater than it, and add one to the sum. This can be easily done with two nested loops. Total complexity $O(n^{2})$. | [
"brute force",
"implementation",
"sortings"
] | 800 | import java.util.Scanner;
public class Main {
private Scanner scanner;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void solve() {
int ... |
551 | B | ZgukistringZ | Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.
GukiZ has strings $a$, $b$, and $c$. He wants to obtain string $k$ by swapping some letters in $a$, so that $k$ should contain as many non-overlapping substrings equal either to $b$ or $c$ as possible. Subst... | First, calculate the number of occurences of every English letter in strings $a$, $b$, and $c$. We can now iterate by number of non-overlapping substrings of the resulting string equal to $b$, then we can calculate in constant time how many substrings equal to $c$ can be formed (by simple operations on the number of oc... | [
"brute force",
"constructive algorithms",
"implementation",
"strings"
] | 1,800 | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, m, k, ba[26], bb[26], bs[26];
int d, res, prvi, drugi;
char s[N], a[N], b[N], resenje[N];
int main()
{
scanf("%s %s %s", s + 1, a + 1, b + 1);
n = strlen(s + 1);
m = strlen(a + 1);
k = strlen(b... |
551 | C | GukiZ hates Boxes | Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way.
In total there are $n$ piles of boxes, arranged in a line, from left to right, $i$-th pile ($1 ≤ i ≤ n$) containing $a_{i}$ boxes. Luckily, $m$ students are willing to help GukiZ by removing all the boxes ... | Problem solution (complete work time) can be binary searched, because if the work can be done for some amount of time, it can certainly be done for greater amount of time. Let the current search time be $k$. We can determine if we can complete work for this time by folowing greedy algorithm: find last non-zero pile of ... | [
"binary search",
"greedy"
] | 2,200 | import java.util.Scanner;
public class Main {
private Scanner scanner;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void solve() {
int ... |
551 | D | GukiZ and Binary Operations | We all know that GukiZ often plays with arrays.
Now he is thinking about this problem: how many arrays $a$, of length $n$, with non-negative elements \textbf{strictly less} then $2^{l}$ meet the following condition: $(a_{1}\operatorname{and}a_{2})\operatorname{or}(a_{2}\operatorname{and}a_{3})\operatorname{or}\cdot\cd... | First convert number $k$ into binary number system. If some bit of $k$ is $0$ than the result of $or$ opertion applied for every adjacent pair of those bits in array $a$ must be $0$, that is no two adjacent those bits in array $a$ are $1$. We should count how many times this is fulfilled. If the values were smaller we ... | [
"combinatorics",
"implementation",
"math",
"matrices",
"number theory"
] | 2,100 | import java.util.Scanner;
public class Main {
private Scanner scanner;
private int mod;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void s... |
551 | E | GukiZ and GukiZiana | Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called $GukiZiana$. For given array $a$, indexed with integers from $1$ to $n$, and number $y$, $GukiZiana(a, y)$ represents maximum value of $j - i$, such that $a_{j} = a_{i} = y$. If there is no $y$ as an element in $a$, ... | First we divide array $a$ in $\sqrt{n}$ groups with $\sqrt{n}$ numbers. Every group in each moment will be kept sorted. For type $1$ query, If we update some interval, for each group, which is whole packed in the interval, we will add the number it is being increased to it's current increasing value (this means all the... | [
"binary search",
"data structures",
"implementation"
] | 2,500 | #include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 500010, G = 1010;
int n, q, koren;
ll a[N], d[N];
pair<ll, int> pa[G][G];
int grupa(int x)
{
return 1 + (x - 1) / koren;
}
void sortirajgrupu(int grp, int neki)
{
int vel = 0;
for (int i = n... |
552 | A | Vanya and Table | Vanya has a table consisting of $100$ rows, each row contains $100$ cells. The rows are numbered by integers from $1$ to $100$ from bottom to top, the columns are numbered from $1$ to $100$ from left to right.
In this table, Vanya chose $n$ rectangles with sides that go along borders of squares (some rectangles probab... | In this problem we can get AC with many solutions: 1) With every new rectangle we will add his area to the result, so for each line $x_{1}, y_{1}, x_{2}, y_{2}$ we will add to answer $(x_{2} - x_{1} + 1) * (y_{2} - y_{1} + 1)$ Time complexity $O(n)$. 2) We can just do all, that is written in the statement: create an ar... | [
"implementation",
"math"
] | 1,000 | "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI ... |
552 | B | Vanya and Books | Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the $n$ books should be assigned with a number from $1$ to $n$. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels ... | We can find out a formula for this problem: for $n < 10$ answer will be $n = n - 1 + 1 = 1 * (n + 1) - 1$; for $n < 100$ answer will be $2 * (n - 9) + 9 = 2 * n - 9 = 2 * n - 10 - 1 + 2 = 2 * (n + 1) - 11$; for $n < 1000$ answer will be $3 * (n - 99) + 2 * (99 - 9) + 9 = 3 * n - 99 - 9 = 3 * n - 100 - 10 - 1 + 3 = 3 * ... | [
"implementation",
"math"
] | 1,200 | "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI ... |
552 | C | Vanya and Scales | Vanya has a scales for weighing loads and weights of masses $w^{0}, w^{1}, w^{2}, ..., w^{100}$ grams where $w$ is some integer not less than $2$ (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass $m$ using the given weights, if the weights can be put on both pans of the s... | Convert $m$ to number system of base $w$. If all digits of number - $0$ or $1$, then we can measure the weight of the item with putting weights, that have digits equal to $1$, on one pan, and our item on another one. If this condition isn't satisfied, then we should iterate from lower digit to high and if digit is not ... | [
"brute force",
"dp",
"greedy",
"math",
"meet-in-the-middle",
"number theory"
] | 1,900 | "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI ... |
552 | D | Vanya and Triangles | Vanya got bored and he painted $n$ distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the \textbf{non-zero} area. | We can look through all pair of points, draw line through each pair and write, that this line includes these 2 points. We can do it with map. If some line includes $x$ points, then in fact we counted, that it has $2 * x * (x - 1)$ points, because we included each point 2*(x-1) times in this line. We can create an array... | [
"brute force",
"combinatorics",
"data structures",
"geometry",
"math",
"sortings"
] | 1,900 | "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#include <unordered_map>\n#define mp make_pair\n#define... |
552 | E | Vanya and Brackets | Vanya is doing his maths homework. He has an expression of form $x_{1}\otimes x_{2}\otimes x_{3}\otimes\cdot\cdot\otimes x_{n}$, where $x_{1}, x_{2}, ..., x_{n}$ are digits from $1$ to $9$, and sign $\quad\quad\quad\quad\quad\quad\quad\quad\quad{}$ represents either a plus '+' or the multiplication sign '*'. Vanya need... | We can see, that we can reach maximal answer, when brackets will be between two signs $*$, or between one sign $*$ and the end of expression. For convenience we will add in the begin of expression $1 *$, and in the end of expression $* 1$. After that we can iterate all possible pairs of signs $*$ and count the expressi... | [
"brute force",
"dp",
"expression parsing",
"greedy",
"implementation",
"strings"
] | 2,100 | "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.