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
380
C
Sereja and Brackets
Sereja has a bracket sequence $s_{1}, s_{2}, ..., s_{n}$, or, in other words, a string $s$ of length $n$, consisting of characters "(" and ")". Sereja needs to answer $m$ queries, each of them is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. The answer to the $i$-th query is the length of the max...
We will support the segments tree. At each vertex will be stored: $a_{v}$ - the maximum length of the bracket subsequence $b_{v}$ - how many there it open brackets that sequence doesn't contain $c_{v}$ - how many there it closed brackets that sequence doesn't contain If we want to combine two vertices with parameters $...
[ "data structures", "schedules" ]
2,000
null
380
D
Sereja and Cinema
The cinema theater hall in Sereja's city is $n$ seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for $n = 4$. Today it's the pre...
In order that no one would be upset, every person except first should sitdown near someone else. Now when any human comes we know that for one side of him there will not be any people. Will use it. We will support the interval exactly occupied seats. If the first person is not known, it is possible that we have 2 such ...
[ "combinatorics", "math" ]
2,500
null
380
E
Sereja and Dividing
Let's assume that we have a sequence of doubles $a_{1}, a_{2}, ..., a_{|a|}$ and a double variable $x$. You are allowed to perform the following two-staged operation: - choose an index of the sequence element $i$ $(1 ≤ i ≤ |a|)$; - consecutively perform assignments: $t m p={\frac{a_{\mathrm{s}}+x}{2}},a_{i}=t m p,x=t ...
Note that at any particular segment we are interested not more than 60 numbers. The greatest number enters with a coefficient of 1/2, the following - 1 /4, 1 /8, and so on. Thus to solve the problem we need to know for each number: how many segments to include it as a maximum , as a second maximum , a third , and so on...
[ "data structures" ]
2,600
null
381
A
Sereja and Dima
Sereja and Dima play a game. The rules of the game are very simple. The players have $n$ cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. Th...
Simply do the process described in the statment.
[ "greedy", "implementation", "two pointers" ]
800
null
381
B
Sereja and Stairs
Sereja loves integer sequences very much. He especially likes stairs. Sequence $a_{1}, a_{2}, ..., a_{|a|}$ ($|a|$ is the length of the sequence) is stairs if there is such index $i$ $(1 ≤ i ≤ |a|)$, that the following condition is met: \[ a_{1} < a_{2} < ... < a_{i - 1} < a_{i} > a_{i + 1} > ... > a_{|a| - 1} > a_{|...
Calculate the amount of each number. For all the different numbers - maximum possible times of use isn't more than 2 times. For the maximum is is only - 1.
[ "greedy", "implementation", "sortings" ]
1,100
null
382
A
Ksenia and Pan Scales
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium. The scales is in equilibrium i...
This problem is just a technic problem. So, you should take weights one by one and place the current one into the side of the scales that contains lower number of weights. At the end you should output answer in the correct format.
[ "greedy", "implementation" ]
1,100
null
382
B
Number Busters
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers $a, b, w, x$ $(0 ≤ b < w, 0 < x < w)$ and Alexander took integer $с$. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his n...
In the problem you should understand, what is the structure of Artur's operation. You can see that this operation is near operation $(b + x)$ % $w$ (To see that just apply $b = w - b - 1$). There is nothing hard to get the formula of changing a during the operation. So, if you have $k$ operations, you can see, that $b ...
[ "binary search", "math" ]
2,000
null
382
C
Arithmetic Progression
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ of length $n$, that the following condition fulfills: \[ a_{2} - a_{1} = a_{3} - a_{2} = a_{4} - a_{3} = ... = a_{i + 1} - a_{i} = ... = a_{n} - a_{n -...
This problem is about considering cases: 1) If $n = 1$, the answer is -1. Because of any two numbers is arithmetical progression. 2) If array is constant, the answer if that constant. 3) If you have arithmetical progression initially, you can compute its difference $d$. In this case you should just to output $minVal - ...
[ "implementation", "sortings" ]
1,700
null
382
D
Ksenia and Pawns
Ksenia has a chessboard of size $n × m$. Each cell of the chessboard contains one of the characters: "<", ">", "^", "v", "#". The cells that contain character "#" are blocked. We know that all chessboard cells that touch the border are blocked. Ksenia is playing with two pawns on this chessboard. Initially, she puts t...
In this problem from every cell except # there is one next cell. That's why this graph is almost functional graph. If this graph contains a cycle, then answer is -1 because the length of the cycle is at least two. In the other case, there are no cycles in the graph. Let's find the longest path in it, denote is as $len$...
[ "dfs and similar", "graphs", "implementation", "trees" ]
2,200
null
382
E
Ksenia and Combinatorics
Ksenia has her winter exams. Today she is learning combinatorics. Here's one of the problems she needs to learn to solve. How many distinct trees are there consisting of $n$ vertices, each with the following properties: - the tree is marked, that is, the vertices of the tree are numbered from 1 to $n$; - each vertex ...
In this problem you should count trees with some properties. It can be done using dynamic programming. The main idea is that the maximum mathing in tree can be found using simple dynamic $dp[v][used]$ ($v$ -- vertex, $used$ - was this vertex used in matching). So you should to count the trees tou should include in stat...
[ "combinatorics", "dp" ]
2,600
null
383
A
Milking cows
Iahub helps his grandfather at the farm. Today he must milk the cows. There are $n$ cows sitting in a row, numbered from $1$ to $n$ from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity...
A good strategy to approach this problem is to think how optimal ordering should look like. For this, let's calculate for each 2 different cows i and j if cow i needs to be milked before or after cow j. As we'll show, having this information will be enough to build optimal ordering. It is enough to consider only cases ...
[ "data structures", "greedy" ]
1,600
#include <iostream> using namespace std; int x[200200], zero[200200]; int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) cin >> x[i]; for (int i = n; i >= 1; --i) zero[i] = zero[i + 1] + 1 - x[i]; long long res = 0; for (int i = 1; i <= n; ++i) if (x[i] == 1) ...
383
B
Volcanoes
Iahub got lost in a very big desert. The desert can be represented as a $n × n$ square matrix, where each cell is a zone of the desert. The cell $(i, j)$ represents the cell at row $i$ and column $j$ $(1 ≤ i, j ≤ n)$. Iahub can go from one cell $(i, j)$ only down or right, that is to cells $(i + 1, j)$ or $(i, j + 1)$....
Our first observation is that if there is a path from (1, 1) to (N, N), then the length of path is 2 * N - 2. Since all paths have length 2 * N - 2, it follows that if there is at least one path, the answer is 2 * N - 2 and if there isn't, the answer is -1. How to prove it? Every path from (1, 1) to (N, N) has exactly ...
[ "binary search", "implementation", "sortings", "two pointers" ]
2,500
#include <stdio.h> #include <algorithm> using namespace std; const int INF = 1000000100; struct range { int x, y; } prev[100010], cur[100010], blocked[100010]; inline bool comp1(range A, range B) { if (A.x == B.x) return A.y < B.y; return A.x < B.x; } int main() { int N, M; scanf("%d%d"...
383
C
Propagating tree
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of $n$ nodes numbered from $1$ to $n$, each node $i$ having an initial value $a_{i}$. The root of the tree is node $1$. This tree has a special property: when a value $val$ is added to a value of node $i$,...
This is kind of task that needs to be break into smaller subproblems that you can solve independently, then put them together and get solution. Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is at level 0, sons of root are at level 1, sons of sons of root are at level ...
[ "data structures", "dfs and similar", "trees" ]
2,000
#include <iostream> #include <algorithm> #include <vector> using namespace std; int N, M; int A[200002]; vector<int> V[200002]; int niv[200002], in[200002], out[200002], tnow; int AIB[400002]; bool S[200002]; void update(int pos, int val) { for (; pos <= 400000; pos += pos & -pos) AIB[pos] += val; } int ...
383
D
Antimatter
Iahub accidentally discovered a secret lab. He found there $n$ devices ordered in a line, numbered from $1$ to $n$ from left to right. Each device $i$ $(1 ≤ i ≤ n)$ can create either $a_{i}$ units of matter or $a_{i}$ units of antimatter. Iahub wants to choose some contiguous subarray of devices in the lab, specify th...
The problem is: given an array, iterate all possible subarrays (all possible elements such as their indexes are consecutive). Now, for a fixed subarray we need to know in how many ways we can color its elements in black and white, such as sum of black elements is equal to sum of white elements. The result is sum of thi...
[ "dp" ]
2,300
#include <cstring> #include <cstdio> #include <iostream> #include <algorithm> #include <vector> using namespace std; const int MOD = 1000000007; int N; int A[1002], S[1002]; int F[20002]; int D1[1002][10002], D2[1002][10002]; int result; void get_result(int i1, int i2) { if (i1 == i2) return; ...
383
E
Vowels
Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of $n$ 3-words. A 3-word is a sequence of exactly $3$ lowercase letters of the first 24 letters of the English alphabet ($a$ to $x$). She decided that some of the letters are vow...
Let's iterate over all possible vowel sets. For a given set {x1, x2, ..., xk} we're interested in number of correct words from dictionary. After a precalculation, we can do it in O(k). Suppose our current vowel set is {x1, x2, ..., xk}. How many words are covered by the current vowels? By definition, we say a word is c...
[ "combinatorics", "divide and conquer", "dp" ]
2,700
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int MOD = 1000000007; int N, Q; char ainit[5]; int is[24][24][24]; // trioletul int A1[1 << 12], A2[1 << 12], An[1 << 12][12]; // A1[mask] = cate perechi din prima jumatate, A2[mask] = cate perechi din a doua juma...
384
A
Coder
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position $(x, y)$, he can move to (or attack) positions $(x + 1, y)$, $(x–1, y)$, $(x, y + 1)$ and $(x, y–1)$. Iahub wants to know...
Usually, when you don't have any idea how to approach a problem, a good try is to take some small examples. So let's see how it looks for N = 1, 2, 3, 4 and 5. With C I noted the coder and with * I noted an empty cell. By now you should note that answer is N ^ 2 / 2 when N is even and (N ^ 2 + 1) / 2 when N is odd. Goo...
[ "implementation" ]
800
#include <stdio.h> int main() { int n; scanf("%d", &n); printf("%d ", (n * n + 1) / 2); for (int i = 1; i <= n; ++i, printf(" ")) for (int j = 1; j <= n; ++j) if ((i + j) % 2 == 0) printf("C"); else printf("."); return 0; }
384
B
Multitasking
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort $n$ arrays simultaneously, each array consisting of $m$ integers. Iahub can choose a pair of distinct indices $i$ and $j$ $(1 ≤ i, j ≤ m, i ≠ j)$. Then in each array the values at positions $i$ and $j$ are swapped only if the valu...
Let's start by saying when array A[] is sorted: 1/ is sorted in ascending order when i < j and A[i] <= A[j]. It is NOT sorted when i < j and A[i] > A[j]. 2/ is sorted in descending order when i > j and A[i] <= A[j]. It is NOT sorted when i > j and A[i] > A[j]. Iahub can choose 2 indices i, j and swap values when A[i] >...
[ "greedy", "implementation", "sortings", "two pointers" ]
1,500
#include <iostream> #include <algorithm> using namespace std; const int exl1[] = {0, 1, 3, 2, 5, 4}, exl2[] = {0, 1, 4, 3, 2, 5}; int N, M, K; int A[1002][102]; int main() { cin.sync_with_stdio(false); cin >> N >> M >> K; for (int i = 1; i <= N; ++i) for (int j = 1; j <= M; ++j) ...
385
A
Bear and Raspberry
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following $n$ days. According to the bear's data, on the $i$-th $(1 ≤ i ≤ n)$ day, the price for one barrel of honey is going to is $x_{i}$ kilos of raspberry. Unfortuna...
In this task required to understand that the answer max($a[i] - a[i - 1] - c$),$i$ = $2..n$ and don't forget that the answer not negative as Bear can not borrow in the debt barrel of honey.
[ "brute force", "greedy", "implementation" ]
1,000
null
385
B
Bear and Strings
The bear has a string $s = s_{1}s_{2}... s_{|s|}$ (record $|s|$ is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices $i, j$ $(1 ≤ i ≤ j ≤ |s|)$, that string $x(i, j) = s_{i}s_{i + 1}... s_{j}$ contains at least one string "bear" as a substring. S...
In this problem you could write a better solution than the naive. To do this, you can iterate through the first cycle of the left index $l$ considered substring and the second cycle of the right index $r$ considered substring $(l \le r)$. If any position has been substring "bear", means all the strings $x(l, j)$ $(i ...
[ "brute force", "greedy", "implementation", "math", "strings" ]
1,200
null
385
C
Bear and Prime Numbers
Recently, the bear started studying data structures and faced the following problem. You are given a sequence of integers $x_{1}, x_{2}, ..., x_{n}$ of length $n$ and $m$ queries, each of them is characterized by two integers $l_{i}, r_{i}$. Let's introduce $f(p)$ to represent the number of such indexes $k$, that $x_{...
In order to solve given problem, contestant should solve several subproblems : 1) First one is to compute amount of entries of each natural number between $2$ and $10^{7}$ in given list. This subproblem can be solved by creating array $count$ of $10^{7}$ elements and increasing corresponding element when scanning input...
[ "binary search", "brute force", "data structures", "dp", "implementation", "math", "number theory" ]
1,700
null
385
D
Bear and Floodlight
One day a bear lived on the $Oxy$ axis. He was afraid of the dark, so he couldn't move at night along the plane points that aren't lit. One day the bear wanted to have a night walk from his house at point $(l, 0)$ to his friend's house at point $(r, 0)$, along the segment of length $(r - l)$. Of course, if he wants to ...
In this task, it is crucial to understand that whether there is lighted part of road with length $dist$ then next part should be lit in a such way that leftmost lighted point is touching with $dist$. Let's suppose that road is lit from $l$ to $d$. How we can find rightmost point on X axis that would be lit by next floo...
[ "bitmasks", "dp", "geometry" ]
2,200
null
385
E
Bear in the Field
Our bear's forest has a checkered field. The checkered field is an $n × n$ table, the rows are numbered from 1 to $n$ from top to bottom, the columns are numbered from 1 to $n$ from left to right. Let's denote a cell of the field on the intersection of row $x$ and column $y$ by record $(x, y)$. Each cell of the field c...
In this task there are several problems that should be concerned: 1) Simple modeling of bear movement would cause TLE due to $t$ $ \le $ $10^{18}$. 2) Task can't be solved by separating $x$ and $y$ axes because $x$ and $y$ depends on each other. 3) Also, we can't use standart method of cycle finding via modeling for a ...
[ "math", "matrices" ]
2,300
null
387
A
George and Sleep
George woke up and saw the current time $s$ on the digital clock. Besides, George knows that he has slept for time $t$. Help George! Write a program that will, given time $s$ and $t$, determine the time $p$ when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see t...
I will describe the simple solution. Let George woke up in the $h_{0}$ hours and $m_{0}$ minutes, and he slept for $h_{1}$ hours and $m_{1}$ minutes. Let's get the number $h_{p} = h_{0} - h_{1}$ and $m_{p} = m_{0} - m_{1}$. If $m_{p} < 0$, then you should add to $m_{p}$ $60$ minutes and subtract from $h_{p}$ one hour. ...
[ "implementation" ]
900
#include <cstdio> int main() { int h[2], m[2]; for(int i = 0; i < 2; i++) scanf("%d:%d", &h[i], &m[i]); h[0] -= h[1]; m[0] -= m[1]; if (m[0] < 0) m[0] += 60, h[0]--; if (h[0] < 0) h[0] += 24; printf("%02d:%02d\n", h[0], m[0]); return 0; }
387
B
George and Round
George decided to prepare a Codesecrof round, so he has prepared $m$ problems for the round. Let's number the problems with integers $1$ through $m$. George estimates the $i$-th problem's complexity by integer $b_{i}$. To make the round good, he needs to put at least $n$ problems there. Besides, he needs to have at le...
Consider the number of requirements of the difficulties, which we will cover, and we will come up with and prepare new problem to cover other requirements. It is clear that if we decided to meet the $i$ out of $n$ requirements, it would be better to take those with minimal complexity. Let's simplify $i$ most difficult ...
[ "brute force", "greedy", "two pointers" ]
1,200
#include <cstdio> const int N = 3005; int a[N], b[N]; int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < m; i++) scanf("%d", &b[i]); int bestPossible = n; if (bestPossible > m) bestPossible = m; for(int i = bestPossible...
387
C
George and Number
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers $b$. During the game, George modifies the array by using special changes. Let's mark George's current array as $b_{1}, b_{2}, ..., b_{|b|}$ (record $|b|$ denotes the current length of the array). Then one chang...
Let's obtain the following irreducible representation of a number $p = a_{1} + a_{2} + ... + a_{k}$, where $+$ is a concatenation, and numbers $a_{i}$ have the form $x00..000$ (x - is non zero digit, and after that there are only zeroes). Let's determine largest index $i$, such that $a_{1} + a_{2} + ... + a_{i - 1} < a...
[ "greedy", "implementation" ]
1,700
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author gridnevvvit */ public clas...
387
D
George and Interesting Graph
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: - The graph doesn't contain any multiple arcs; - There is vertex $v$ (we'll call her the center), such that for any vertex of graph $u$, the graph contains arcs $(u, v...
To solve this problem you should know about bipartite matching. Let's consider the center of graph $i$. After that let's remove arcs that have form $(i, u)$ or $(u, i)$. Let's there are $cntWithI$ arcs of such type. Let's $Other = m - CntWithI$ - number of other arcs. After that we should found maximal bipartite matchi...
[ "graph matchings" ]
2,200
#include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <vector> #include <string> #include <deque> #include <bitset> #include <algorithm> #include <utility> #include <functional> #include ...
387
E
George and Cards
George is a cat, so he loves playing very much. Vitaly put $n$ cards in a row in front of George. Each card has one integer written on it. All cards had distinct numbers written on them. Let's number the cards from the left to the right with integers from $1$ to $n$. Then the $i$-th card from the left contains number ...
Let's calculate arrays $pos[i]$ - position of number $i$ in permutation $p$ and $need[i]$ - equals to one if we should remove number $i$ from permutation $p$, and zero if we shouldn't remove $i$ from permutation $p$. Let's $a_{1}, a_{2}, ..., a_{n - k}$ - numvers, which we should remove. It is clear to understand that ...
[ "binary search", "data structures" ]
2,200
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution i...
388
A
Fox and Box Accumulation
Fox Ciel has $n$ boxes in her room. They have the same size and weight, but they might have different strength. The $i$-th box can hold at most $x_{i}$ boxes on its top (we'll call $x_{i}$ the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some bo...
We need some observation: There exists an optimal solution such that: in any pile, the box on the higher position will have a smaller strength. Let k be the minimal number of piles, then there exists an optimal solution such that: The height of all piles is n/k or n/k+1 (if n%k=0, then all of them have the height n/k)....
[ "greedy", "sortings" ]
1,400
null
388
B
Fox and Minimal path
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with $n$ vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain outp...
First we need to know how to calculate the number of different shortest paths from vertex 1 to vertex 2: it can be done by dp: dp[1] = 1, dp[v] = sum{dp[t] | dist(1,t) = dist(1,v) - 1}, then dp[2] is our answer. We need to do dp layer by layer. (first we consider vertexes have distance 1 to node 1, then vertexes have d...
[ "bitmasks", "constructive algorithms", "graphs", "implementation", "math" ]
1,900
null
388
C
Fox and Card Game
Fox Ciel is playing a card game with her friend Fox Jiro. There are $n$ piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom...
First let's consider the case which all piles have even size. In this case, we can prove: in the optimal play, Ciel will gets all top most half cards of each pile, and Jiro gets the remain cards. We can prove by these facts: Ciel have a strategy to ensure she can get this outcome and Jiro also have a strategy to ensure...
[ "games", "greedy", "sortings" ]
2,000
null
388
D
Fox and Perfect Sets
Fox Ciel studies number theory. She thinks a non-empty set $S$ contains non-negative integers is perfect if and only if for any $a.b\in S$ ($a$ can be equal to $b$), $(a~x o r~b)\in S$. Where operation $xor$ means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or). Please calculate the number of perfe...
A perfect set correspond to a linear space, so we can use base to represent it. We do the Gauss-Jordan elimination of vectors in that set, and can get an unique base. (Note that we need to to the all process of Gauss-Jordan elimination, including the elimination after it reached upper triangular) And we can construct t...
[ "math" ]
2,700
null
388
E
Fox and Meteor Shower
There is a meteor shower on the sky and there are $n$ meteors. The sky can be viewed as a 2D Euclid Plane and the meteor is point on this plane. Fox Ciel looks at the sky. She finds out that the orbit of each meteor is a straight line, and each meteor has a constant velocity. Now Ciel wants to know: what is the maximu...
All tasks beside this are very easy to code. And this one focus on implementation. We can represent the orbit of each meteor by a line in 3D space. (we use an axis to represent the time, and two axis to represent the position on the plane.) Then the problem becomes: we have some lines in 3D space (they are not complete...
[ "geometry" ]
3,100
null
389
A
Fox and Number Game
Fox Ciel is playing a game with numbers now. Ciel has $n$ positive integers: $x_{1}$, $x_{2}$, ..., $x_{n}$. She can do the following operation as many times as needed: select two different indexes $i$ and $j$ such that $x_{i}$ > $x_{j}$ hold, and then apply assignment $x_{i}$ = $x_{i}$ - $x_{j}$. The goal is to make ...
First we know that: in the optimal solution, all number will be equal: otherwise we can pick a and b (a < b) then do b = b - a, it will make the answer better. Then we need an observation: after each operation, the GCD (Greatest common divisor) of all number will remain same. It can be proved by this lemma: if g is a d...
[ "greedy", "math" ]
1,000
null
389
B
Fox and Cross
Fox Ciel has a board with $n$ rows and $n$ columns. So, the board consists of $n × n$ cells. Each cell contains either a symbol '.', or a symbol '#'. A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks. Ciel wants to draw several (ma...
Let's define the first # of a shape is the cell contain # that have the lexicographical smallest coordinate. Then the first # of a cross is the top one. Then let x be the first # of the given board. (If the board is empty, then we can draw it with zero crosses.) x must be covered by a cross, and x must be the first # o...
[ "greedy", "implementation" ]
1,100
null
390
A
Inna and Alarm Clock
Inna loves sleeping very much, so she needs $n$ alarm clocks in total to wake up. Let's suppose that Inna's room is a $100 × 100$ square with the lower left corner at point $(0, 0)$ and with the upper right corner at point $(100, 100)$. Then the alarm clocks are points with integer coordinates in this square. The morn...
The criterion shows that we can only use either vertical segments or horizontal segments. Since there is no limit on the segments' length, we can see that it's always optimal to use a segment with infinite length (or may be known as a line). We can see that the vertical line $x = a$ will span through every alarm clocks...
[ "implementation" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL...
390
B
Inna, Dima and Song
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the $i$-th note at v...
From the constraints given, for the $i$-th song, provided there exists corresponding $x_{i}$ and $y_{i}$ values, then the following inequality must hold: $2 \le x_{i} + y_{i} \le 2 \cdot a_{i}$. Thus, if any $b_{i}$ is either lower than $2$ or higher than $2 \cdot a_{i}$, then no $x_{i}$ and $y_{i}$ can be found, t...
[ "implementation" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL...
390
C
Inna and Candy Boxes
Inna loves sweets very much. She has $n$ closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to $n$, from left to right. As the boxes are closed, Inna doesn't know which boxes conta...
The query content looks pretty confusing at first, to be honest. Since $k$ is static throughout a scenario, we can group the boxes into $k$ groups, the $z$-th box (in this editorial let's assume that the indices of the boxes start from $0$) falls into group number $z\ {\mathrm{mod}}\ k$. Then, each query can be simplif...
[ "data structures" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL...
390
D
Inna and Sweet Matrix
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix". Inna sees an $n × m$ matrix and $k$ candies. We'll index the matrix rows from $1$ to $n$ and the matrix columns from $1$ to $m$. We'll represent the cell in the $i$-th row and $j$-th column as $(i, j)$. Two cells $(i, j)$ and $(p...
We can see that the most optimal placement will be choosing $k$ cells being nearest to cell $(1, 1)$ (yup, including $(1, 1)$ itself). To find these $k$ points, we can simply do a BFS starting from $(1, 1)$, with traceback feature to construct the paths to get to those cells. However, keep in mind that any cell being c...
[ "constructive algorithms" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int dx[] = {-1, +0, +0, +1}; int dy[] = {+0, -1, +1, +0}; pair<int, int> Defau...
390
E
Inna and Large Sweet Matrix
Inna loves sweets very much. That's why she wants to play the "Sweet Matrix" game with Dima and Sereja. But Sereja is a large person, so the game proved small for him. Sereja suggested playing the "Large Sweet Matrix" game. The "Large Sweet Matrix" playing field is an $n × m$ matrix. Let's number the rows of the matri...
Let's denote $A$ as the total number of candies on the board, $R_{i}$ as the total number of candies on the $i$-th row ($1 \le i \le n$), $C_{j}$ as the total number of candies on the $j$-th column ($1 \le j \le m$). Also, let's denote $R(i_{1},i_{2})=\sum_{x=i_{1}}^{i_{2}}R_{s}$ and $C(j_{1},j_{2})=\sum_{y=j_{...
[]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); struct SegTree_Sum { int n; vector<long long> Tree, Lazy; SegTree_Sum() {} ...
392
A
Blocked Points
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points $A$ and $B$ on the plane are 4-connected if and only if: - the Euclidean distance between $A$ and $B$ is one unit and neither $A$ nor $B$ is blocked; - or there is so...
Let's look at all pairs of neighboring points such that one of them is special and the other one is not. I claim that it is necessary and sufficient to block at least one point in every such pair Necessity is obvious. Let's prove sufficiency. Assume that we blocked at least one point in each pair, but there are two poi...
[ "math" ]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n; cin >> n; if (n == 0) { cout << 1 << '\n'; return 0; } int L = sqrt(n * n / 2); pair<long long, long long> near = {L + 1, L}; in...
392
B
Tower of Hanoi
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the pu...
First, understand this solution of the standard Hanoi puzzle, if you don't know it. I will use the same idea to solve this problem. Let's create a function $calc(from, to, n)$ which will count the minimal cost to move $n$ disks from $from$ to $to$. If $n=1$ then we either move the disk directly to $to$, or we first mov...
[ "dp" ]
null
#include <bits/stdc++.h> using namespace std; #define ll long long array<array<ll, 3>, 3> t; map<pair<pair<int, int>, ll>, ll> mem; ll calc(int from, int to, int n) { auto p = make_pair(make_pair(from, to), n); if (mem.count(p)) return mem[p]; int mid = 3 - from - to; if (n == 1) { ...
392
C
Yet Another Number Sequence
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation: \[ F_{1} = 1, F_{2} = 2, F_{i} = F_{i - 1} + F_{i - 2} (i > 2). \] We'll define a new number sequence $A_{i}(k)$ by the formula: \[ A_{i}(k) = F_{i} × i^{k} (i ≥ 1). \] In this problem, your task is to calculate ...
This is obviously some matrix-exponentiation problem. We just have to figure out the matrix. Well, let's look at what we have $A_i(k) = F_i \cdot i^k = (F_{i-1} + F_{i-2}) \cdot i^k = F_{i-1}\cdot ((i-1)+1)^k + F_{i-2}\cdot ((i-2) + 2)^k =\\= \sum_{j=0}^k \binom{k}{j} F_{i-1}(i-1)^j + \sum_{j=0}^k \binom{k}{j} F_{i-2}(...
[ "combinatorics", "math", "matrices" ]
null
#include <bits/stdc++.h> using namespace std; #define ll long long template<auto P> struct Modular { using value_type = decltype(P); value_type value; Modular(ll k = 0) : value(norm(k)) {} Modular<P>& operator += (const Modular<P>& m) { value += m.value; if (value >= P) value -= P; return *...
392
D
Three Arrays
There are three arrays $a$, $b$ and $c$. Each of them consists of $n$ integers. SmallY wants to find three integers $u$, $v$, $w$ $(0 ≤ u, v, w ≤ n)$ such that the following condition holds: each number that appears in the union of $a$, $b$ and $c$, appears either in the first $u$ elements of $a$, or in the first $v$ e...
Let forget about $a$ for a minute and solve the problem for two arrays. Of course, it can be done with something like two pointers, but it is not extendable to three arrays (at least I don't know how). We need a more general approach. First, let's assume that $b$ has all elements, which $c$ contains. We can achieve tha...
[ "data structures" ]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<int> a(n), b(n), c(n); for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) cin >> b[i]; for (int i = 0; i < ...
392
E
Deleting Substrings
SmallR likes a game called "Deleting Substrings". In the game you are given a sequence of integers $w$, you can modify the sequence and get points. The only type of modification you can perform is (unexpected, right?) deleting substrings. More formally, you can choose several contiguous elements of $w$ and delete them ...
There will be three different $dp$, let's get that out of the way. I wanted to make $4$, but in the end decided to merge two of them. Also, before everything, let's update $v$ with $v[i] = max_j(v[j] + v[i - j])$. Because sometimes we want to remove segment of length $5$, but $2 + 3$ gives more points. First, let's dis...
[]
null
#include <bits/stdc++.h> using namespace std; #define ll long long const int inf = 1e9; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } v.insert(v.begin(), 0); for ...
393
A
Nineteen
Alice likes word "nineteen" very much. She has a string $s$ and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "{x\textbf{nineteen}pp\textbf{nineteen}w}", containing (the ...
Looking at examples and thinking about different cases lead to the idea that the best result would be to build a string which starts with $nineteenineteenineteen...$. The first word $nineteen$ requires 3 letters $n$, 3 letters $e$, 1 letter $i$ and 1 letter $t$. Every next occurrence of $nineteen$ requires the same set...
[]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); string s; cin >> s; map<char, int> cnt; for (auto c : s) { cnt[c]++; } cout << min({(cnt['n'] - 1) / 2, cnt['e'] / 3, cnt['i'], cnt['t']}) << '\n'; retu...
393
B
Three matrices
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an $n × n$ matrix $W$, consisting of integers, and you should find two $n × n$ matrices $A$ and $B$, all the following conditions must hold: - $A_{ij} = A_{ji}$, for all $i, j$ $(1 ≤ i, j ≤ n)$; - $B_{ij} =...
We can write this system of equations, using the fact that $B[j][i] = -B[i][j]$ and $A[i][j] = A[j][i]$ $\begin{cases} A[i][j] + B[i][j] = W[i][j]\\ A[j][i] + B[j][i] = W[j][i] \end{cases} \quad\Rightarrow\quad \begin{cases} A[i][j] + B[i][j] = W[i][j]\\ A[i][j] - B[i][j] = W[j][i] \end{cases}$ From that, it is easy to...
[]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<vector<double>> w(n, vector<double>(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> w[i][j]; } ...
396
A
On Number of Decompositions into Multipliers
You are given an integer $m$ as a product of integers $a_{1}, a_{2}, ... a_{n}$ $(m=\prod_{i=1}^{n}a_{i})$. Your task is to find the number of distinct decompositions of number $m$ into the product of $n$ ordered positive integers. Decomposition into $n$ products, given in the input, must also be considered in the ans...
Let's factorize all $n$ numbers into prime factors. Now we should solve the problem for every prime independently and multiply these answers. The number of ways to split $p^{k}$ into $n$ multipliers, where $p$ is prime, is equal to $C(k + n - 1, n - 1)$ (it can be obtained using the method of stars and bars, you can re...
[ "combinatorics", "math", "number theory" ]
null
null
396
B
On Sum of Fractions
Let's assume that - $v(n)$ is the largest prime number, that does not exceed $n$; - $u(n)$ is the smallest prime number strictly greater than $n$. Find $\sum_{i=2}^{n}{\frac{1}{v(i)u(i)}}$.
First of all, let's consider $n + 1 = p$ is prime. Then we can prove by induction that the answer is ${\frac{1}{2}}-{\frac{1}{p}}$. Base for $p = 3$ is obvious. If this equality holds for $p$, and $q$ is the next prime, then answer for $q$ is equal to answer for $p$ plus $q - p$ equal summands $\mathbf{\Sigma}_{P q}^{1...
[ "math", "number theory" ]
null
null
396
C
On Changing Tree
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$. Initially all vertices contain number $0$. Then come $q$ queries, each query has one of the two types: - The format of the query: $1$ $v$ $x$ $k$. In response to the query, you need to add to ...
We can write all vertices in the list in order of $dfs$, then the descendants of the vertex from a segment of this list. Let's count for every vertex its distance to the root $level[v]$. Let's create two segment trees $st1$ and $st2$. If we are given a query of the first type, in $st1$ we add $x + level[v] \cdot k$ to ...
[ "data structures", "graphs", "trees" ]
null
null
396
D
On Sum of Number of Inversions in Permutations
You are given a permutation $p$. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one. As this number can be very large, print it modulo $1000000007$ $(10^{9} + 7)$.
Let's prove a useful fact: sum of number of invertions for all permutations of size $k$ is equal to $s u m A l l[k]=k!\cdot{\frac{k(k-1)}{4}}$. The prove is simple: let's change in permutation $p$ for every $i$ $p_{i}$ to $k + 1 - p_{i}$. Then the sum of number of invertions of the first and the second permutations is ...
[ "combinatorics", "math" ]
null
null
396
E
On Iteration of One Well-Known Function
Of course, many of you can calculate $φ(n)$ — the number of positive integers that are less than or equal to $n$, that are coprime with $n$. But what if we need to calculate $φ(φ(...φ(n)))$, where function $φ$ is taken $k$ times and $n$ is given in the canonical decomposition into prime factors? You are given $n$ and ...
We will describe an algorithm and then understand why it works. For every prime we will maintain a list of intervals. At the first moment for every $p_{i}$ we add in its list interval $[0;a_{i})$, other primes have an empty list. Then we go from big primes to small. Let's consider that current prime is $p$. If in its l...
[ "math" ]
null
null
397
A
On Segment's Own Points
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a $100$ c...
Create an array $used$ of $100$ elements. i-th element for the segment $(i, i + 1)$. For every student except Alexey set $used[i] = true$ for each segment $(i, i + 1)$ in the segment of that student. After that for each subsegment $(i, i + 1)$ of Alexey's segment add 1 to result if $used[i] = false$.
[ "implementation" ]
null
null
397
B
On Corruption and Numbers
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to w...
First of all, calculate how many $L$'s we can bring so that the result will not exceed $N$. It's $K={\frac{N}{L}}$. Now, if $R \cdot K \ge N$ we may increase any of $K$ numbers by $1$. At some moment sum will be equal to $N$ becase sum of $K$ $R$'s is greater than $N$. So answer in this case is YES. If $R \cdot K < N...
[ "constructive algorithms", "implementation", "math" ]
null
null
398
A
Cards
User ainta loves to play with cards. He has $a$ cards containing letter "o" and $b$ cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. - At first, the score is $0$. - For each block of contiguous "o"s with length $x$ the score increases by $x^{2}$. -...
Let the number of o blocks $p$, and the number of x blocks $q$. It is obvious that $|p - q| \le 1$ and $p, q \le n$. So we can just iterate all $p$ and $q$, and solve these two problems independently, and merge the answer. 1. Maximize the value of $x_{1}^{2} + x_{2}^{2} + ... + x_{p}^{2}$ where $x_{1} + x_{2} + ......
[ "constructive algorithms", "implementation" ]
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <utility> #include <bitset> #inclu...
398
B
Painting The Wall
User ainta decided to paint a wall. The wall consists of $n^{2}$ tiles, that are arranged in an $n × n$ table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below. - Firstly user ainta looks at the wall. If there is at least one painted cell on each row a...
This can be solved by dynamic programming. Let $T[i, j]$ the expected time when $i$ rows and $j$ columns doesn't have any painted cells inside. Let's see all the cases. If we carefully rearrange the order of rows and columns, we can divide the wall into 4 pieces. Choose a cell in rectangle 1. The size of this rectangle...
[ "dp", "probabilities" ]
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <utility> #include <bitset> #inclu...
398
C
Tree and Array
User ainta likes trees. This time he is going to make an undirected tree with $n$ vertices numbered by integers from $1$ to $n$. The tree is weighted, so each edge of the tree will have some integer weight. Also he has an array $t$: $t[1], t[2], ..., t[n]$. At first all the elements of the array are initialized to $0$...
There are two intended solutions. One is easy, and the other is quite tricky. Easy Solution Make a tree by the following method. For all $1\leq i\leq\lfloor{\frac{n}{2}}\rfloor$, make an edge between vertex $i$ and $i+\lfloor{\frac{n}{2}}\rfloor$ with weight 1. For all $\lfloor{\frac{n}{2}}\rfloor<i<n$, make an edge be...
[ "constructive algorithms" ]
null
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <u...
398
D
Instant Messanger
User ainta decided to make a new instant messenger called "aintalk". With aintalk, each user can chat with other people. User ainta made the prototype of some functions to implement this thing. - login($u$): User $u$ logins into aintalk and becomes online. - logout($u$): User $u$ logouts and becomes offline. - add_fri...
Let $x_{i}$ an integer representing the state of the i-th user. If user i is online, $x_{i} = 1$, otherwise, $x_{i} = 0$. Also, let $S_{i}$ the set consisting of i-th friends. One can see that the queries become like this: Online/Offline: change the value of $x_{i}$ to $1 - x_{i}$. Add: add $u$ to set $S_{v}$, and $v$ ...
[ "data structures" ]
null
#include<stdio.h> #include<algorithm> #include<vector> using namespace std; #define N_ 100010 #define Q_ 250010 #define M_ 150010 int n, m, Q, SZ, C[N_], cnt, st[N_], beg[N_], Next[(M_ + Q_) * 2]; bool v[N_]; struct Query{ int a, b; char ck; }w[Q_]; struct Edge{ int a, b; bool ck; bool operator <(const Edge &p)con...
398
E
Sorting Permutations
We are given a permutation sequence $a_{1}, a_{2}, ..., a_{n}$ of numbers from $1$ to $n$. Let's assume that in one second, we can choose some disjoint pairs $(u_{1}, v_{1}), (u_{2}, v_{2}), ..., (u_{k}, v_{k})$ and swap all $a_{ui}$ and $a_{vi}$ for every $i$ at the same time ($1 ≤ u_{i} < v_{i} ≤ n$). The pairs are d...
Let us start with the case when there is no hole. Given any permutation, I will prove that it takes only at most two seconds to sort it completely. Since every permutation can be decomposed into disjoint cycles (link), we only need to take care of each decomposed cycle. That is, we only need to sort a cycle of arbitrar...
[]
null
null
399
A
Pages
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are $n$ pages numbered by integers from $1$ to $n$. Assume that somebody is on the $p$-th page now. The navigation will look like this: \begin{center} << $p - k$ $p - k + 1$ $...$ $p - 1$ $(p)$ $p + 1$ $...$ $p...
You can solve this problem by just following the statement. First, print << if $p - k > 1$. Next, iterate all the integers from $p - k$ to $p + k$, and print if the integer is in $[1..n]$. Finally, print >> if $p + k < n$. Time complexity: $O(n)$.
[ "implementation" ]
null
#include <stdio.h> int n, p, k; int main() { scanf("%d%d%d", &n, &p, &k); if(p - k > 1) printf("<< "); for(int i = p - k; i <= p + k; i++) if(1 <= i && i <= n) printf((i == p) ? "(%d) " : "%d ", i); if(p + k < n) printf(">> "); return 0; }
399
B
Red and Blue Balls
User ainta has a stack of $n$ red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. - While the top ball inside the stack is red, pop the ball from the top of the stack. - Then replace the blue ball on the top with a red ball. - And finally push some blue balls to...
Change the blue balls to bit 1, and blue balls to bit 0. Interpret the stack as an integer represented in binary digits. Now, one may see that a single operation decreases the integer by 1, and will be unavailable iff the integer becomes zero. So the answer will be $2^{a1} + 2^{a2} + ... + 2^{ak}$ where the $(a_{i} + 1...
[]
null
#include <stdio.h> int n; char s[55]; long long res; int main() { scanf("%d%s", &n, s); for(int i = 0; i < n; i++) if(s[i] == 'B') res |= 1ll << i; printf("%I64d\n", res); return 0; }
400
A
Inna and Choose Options
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below: There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"...
Not difficult task. Let's iterate param $a$. If $12$ % $a$ != $0$, continue. Calculate $b = 12 / a$. Let's iterate column (from $1$ to $b$) and for each it's cell $(i, j)$ check, if it contains $X$ or not. Cell $(i, j)$ - is $((i-1) * a + j)$ -th element of string.
[ "implementation" ]
1,000
null
400
B
Inna and New Matrix of Candies
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload". The field for the new game is a rectangle table of size $n × m$. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game ...
In the final version of statement we must choose all lines we haven't finish already. If it is a string where we have $S...G$ - answer $- 1$. Otherwise, the answer is the number of distinct distances, as one step kills all distances of the minimal length.
[ "brute force", "implementation", "schedules" ]
1,200
null
400
C
Inna and Huge Candy Matrix
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from $1$ to $n$ from top to bottom and the columns — from $1$ to $m$, from left to right. We'll represent the cell on the intersection of the $i$-th row and $j$-th colum...
Let's note that the number of 90 clockwise make sence only by modulo 4. Horizontal - by modulo 2, and 90 counterclockwise - by modulo 4, and 1 such rotation is 3 clockwise rotations. 90 clockwise: $newi = j;$ $newj = n-i + 1$ don't forget to $swap(n, m)$. Horizontal: $newj = m-j + 1$
[ "implementation", "math" ]
1,500
null
400
D
Dima and Bacteria
Dima took up the biology of bacteria, as a result of his experiments, he invented $k$ types of bacteria. Overall, there are $n$ bacteria at his laboratory right now, and the number of bacteria of type $i$ equals $c_{i}$. For convenience, we will assume that all the bacteria are numbered from $1$ to $n$. The bacteria of...
If the distribution is correct, after deleting all ribs with cost more than 0 graph will transform to components of corrects size. Also, the nodes are numereted so we should turn dfs for the first node of each type and be sure that we receive exact all nodes of this type and no ohter. Now simple floyd warshall, and put...
[ "dsu", "graphs", "shortest paths" ]
2,000
null
400
E
Inna and Binary Logic
Inna is fed up with jokes about female logic. So she started using binary logic instead. Inna has an array of $n$ elements $a_{1}[1], a_{1}[2], ..., a_{1}[n]$. Girl likes to train in her binary logic, so she does an exercise consisting of $n$ stages: on the first stage Inna writes out all numbers from array $a_{1}$, o...
Let's solve this for each bit separately. Fix some bit. Let's put 1 if the number contains bit and 0 otherwise. Now we receive the sequence, for example $11100111101$. Now let's look on sequence of 1 without 0, for this sequence current bit will be added to the sum on the first stage (with all numbers single) on the se...
[ "binary search", "bitmasks", "data structures" ]
2,100
null
401
A
Vanya and Cards
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed $x$ in the absolute value. Natasha doesn't like when Vanya spends a long time p...
We must sum all numbers, and reduced it to zero by the operations +x and -x.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int ans, sum, x, n, q; int main() { scanf("%d %d", &n, &x); sum = 0; for (int i = 0; i < n; i++) { cin>>q; sum += q; } sum = abs(sum); ans = sum / x; if (sum % x != 0) ans++; cout<<ans<<endl; }
401
B
Sereja and Contests
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: $Div1$ (for advanced coders) and $Div2$ (for beginner coders). Two rounds, $Div1$ and $Div2$, can go simultaneously, ($Div1$ ro...
You must identify the array of numbers contests that remember Sereja, as employed. If we want to find maximal answer, we must count the number of immune cells. If we want to find mininum answer, we must do the following: if i-th element is free and (i+1)-th element is free, and i<x then we using round type of "Div1+Div...
[ "greedy", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int min_ans, max_ans, x, k, t, num1, num2, num, a[4001], i; int main() { scanf("%d%d", &x, &k); for (int i = 0; i < k; i++) { scanf("%d", &t); if (t == 1) { scanf("%d%d", &num1, &num2); a[num1] = 1; ...
401
C
Team
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
n - the number of cards containing number 0 and m - the number of cards containing number 1. We have answer, when ((n-1)<=m && m <= 2 * (n + 1)). If we have answer then we must do the following: if (m == n - 1) then we derive the ones and zeros in one, but we must start from zero. if (m == n) then we derive the ones an...
[ "constructive algorithms", "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; long long n, m, t, a[3000001], k; int main() { scanf("%d%d", &n, &m); if (n - 1 <= m && m <= 2*(n + 1)) { if (m == n - 1) { a[0] = -1; a[m + 1] = -1; t = n - 1; } else if (m == n) { ...
401
D
Roman and Numbers
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number $n$, modulo $m$. Number $x$ is considered close to number...
This problem we can be attributed to the dynamic programming. We must using mask and dynamic. We have dynamic dp[i][x], when i - mask of reshuffle and x - remainder on dividing by m. if we want to add number a[j], we must using it: dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] := dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] + d...
[ "bitmasks", "brute force", "combinatorics", "dp", "number theory" ]
2,000
var l,ans,n,m,q,ost,q1:int64; i,j,t,p,x:longint; s:string; ok:boolean; a,qq:array [0..300000,0..101] of int64; aa,kol:array [0..200] of longint; begin read(q1,m); str(q1,s); l:=length(s); for i:=1 to l do begin val(s[i],aa[i],p); inc(kol[aa[i]]); end;...
401
E
Olympic Games
This problem was deleted from the contest, because it was used previously at another competition.
If first participant of the contest will contain at point (x1;y1) and second participant of the contest will contain at point (x2;y2), then we need to satisfy two conditions: L*L <= (abs(x1-x2)*abs(x1-x2) + abs(y1-y2)*abs(y1-y2)) <= R*R gcd(abs(x1-x2),abs(y1-y2)) == 1 Since the hall can potentially be of size 100,000 x...
[ "math" ]
2,500
#include <bits/stdc++.h> #define nmax 100005 typedef long long ll; ll m, n, l, r, p, num[nmax], d[nmax][6], ans, ii; ll tt(ll ql, ll qh, ll mm) { qh = qh / mm; ql = (ql + mm - 1) / mm; return ((qh - ql + 1) * (n + 1) - mm * ((qh * (qh + 1) - (ql - 1) * ql) / 2)) % p; } int main() { scanf("%lld%lld", &n, &m); ...
402
A
Nuts
You have $a$ nuts and lots of boxes. The boxes have a wonderful feature: if you put $x$ $(x ≥ 0)$ divisors (the spacial bars that can divide a box) to it, you get a box, divided into $x + 1$ sections. You are minimalist. Therefore, on the one hand, you are against dividing some box into more than $k$ sections. On the ...
Let's fix some value of boxes $ans$. After that we can get exactly $cnt = ans + min((k - 1) * ans, B)$ of sections. So, if $cnt * v \ge a$, then $ans$ be an answer. After that you can use brute force to find smallest possible value of $ans$.
[ "greedy", "math" ]
1,100
null
402
B
Trees in a Row
The Queen of England has $n$ trees growing in a row in her garden. At that, the $i$-th $(1 ≤ i ≤ n)$ tree from the left has height $a_{i}$ meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all $i$ $(1 ≤ i < n)$, $a_{i + 1} - a_{i} = k$, where $k...
Let's fix height of the first tree: let's call it $a$. Of course, $a$ is an integer from segment $[1, 1000]$. After that, for the fixed height $a$ of the first tree we can calculate heights of the others trees: $a, a + k, a + 2k$, and so on. After that you should find minimal number of operations $ans$ to achive such h...
[ "brute force", "implementation" ]
1,400
null
402
C
Searching for Graph
Let's call an undirected graph of $n$ vertices $p$-interesting, if the following conditions fulfill: - the graph contains exactly $2n + p$ edges; - the graph doesn't contain self-loops and multiple edges; - for any integer $k$ ($1 ≤ k ≤ n$), any subgraph consisting of $k$ vertices contains at most $2k + p$ edges. A s...
I will describe two solutions. First. Consider all pairs $(i, j)$ ($1 \le i < j \le n$). After you should ouput the first $2n + p$ pairs in lexicographical order. It's clear to understand, that it is enough to prove, that $0$-interesting graph is correct or $- 3$ -interesting graph is correct. We will prove for $- ...
[ "brute force", "constructive algorithms", "graphs" ]
1,500
null
402
D
Upgrading Array
You have an array of positive integers $a[1], a[2], ..., a[n]$ and a set of bad prime numbers $b_{1}, b_{2}, ..., b_{m}$. The prime numbers that do not occur in the set $b$ are considered good. The beauty of array $a$ is the sum $\sum_{i=1}^{n}f(a[i])$, where function $f(s)$ is determined as follows: - $f(1) = 0$; - L...
I will describe two solutions. First. Dynamic programming approach. Let's calculate an DP $d[i][j]$ - which is the best possible answer we can achieve, if current prefix has length $i$ and we used operation of Upgrading last time in position $j$. It is clear to understand, that we should iterate $i$ from $n$ to $1$, an...
[ "dp", "greedy", "math", "number theory" ]
1,800
null
402
E
Strictly Positive Matrix
You have matrix $a$ of size $n × n$. Let's number the rows of the matrix from $1$ to $n$ from top to bottom, let's number the columns from $1$ to $n$ from left to right. Let's use $a_{ij}$ to represent the element on the intersection of the $i$-th row and the $j$-th column. Matrix $a$ meets the following two condition...
Let's look at the matrix $a$ as a connectivity matrix of some graph with n vertices. Moreover, if $a_{ij} > 0$, then we have directed edge in the graph between nodes $(i, j)$. Otherwise, if $a_{ij} = 0$ that graph does not contains directed edge between pair of nodes $(i, j)$. Let $b = a^{k}$. What does $b_{ij}$ means?...
[ "graphs", "math" ]
2,200
null
403
D
Beautiful Pairs of Numbers
The sequence of integer pairs $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{k}, b_{k})$ is beautiful, if the following statements are fulfilled: - $1 ≤ a_{1} ≤ b_{1} < a_{2} ≤ b_{2} < ... < a_{k} ≤ b_{k} ≤ n$, where $n$ is a given positive integer; - all numbers $b_{1} - a_{1}$, $b_{2} - a_{2}$, $...$, $b_{k} - a_{k}$ are...
First, we can note, that length of sequence is not greater then $50$. Ok, but why? Because all numbers $b_{i} - a_{i}$ are different, so $0 + 1 + ... + 50 > 1000$. Let's imagine, that sequence from input is a sequence of non-intersecting segments. So, $c_{i} = b_{i} - a_{i} + 1$ is length of segment $i$. Also, $\textst...
[ "combinatorics", "dp" ]
2,300
null
403
E
Two Rooted Trees
You have two rooted undirected trees, each contains $n$ vertices. Let's number the vertices of each tree with integers from $1$ to $n$. The root of each tree is at vertex $1$. The edges of the first tree are painted blue, the edges of the second one are painted red. For simplicity, let's say that the first tree is blue...
First, for each vertex of the first and second tree we calculate two values $in[s]$, $out[s]$ - the entry time and exit time in dfs order from vertex with number $1$. Also with each edge from both trees we will assosiate a pair $(p, q)$, where $p = min(in[u], in[v])$, $q = max(in[u], in[v])$ (values $in, out$ for each ...
[ "data structures", "implementation", "trees" ]
2,900
#include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <vector> #include <string> #include <deque> #include <bitset> #include <algorithm> #include <utility> #include <functional> #include ...
404
A
Valera and X
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
In this problem it was needed to check the constraints described in statement. You can use two sets here. You should insert diagonal elements of matrix into the first set, and the other elements into the second. Element $a_{i, j}$ belongs to the main diagonal if $i = j$ and belongs to the secondary diagonal if $i = n -...
[ "implementation" ]
1,000
null
404
B
Marathon
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates $(0, 0)$ and the length of the side equals $a$ meters. The sides of the square are parallel to coordinate axes. As the length ...
Let's notice that after Valera run $4 \cdot a$ meters he will be in the same point from which he started. Valera will have run $i \cdot d$ meters before he gets $i$-th bottle of drink. Let's calculate the value $c=\lfloor{\frac{i\,d}{4\,a}}\rfloor$ - how many laps he will run. Then he have already run $L = i \cdot d - ...
[ "implementation", "math" ]
1,500
null
404
C
Restore Graph
Valera had an undirected connected graph without self-loops and multiple edges consisting of $n$ vertices. The graph had an interesting property: there were at most $k$ edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to $n$. One day Valera...
First of all let us notice that it must be only one $0$ in $d$. Also $d[start] = 0$ means that $start$ is the vertex from which Valera calculated the distance to the other vertices. Let's notice that every vertex $u$ with $d[u] = i$ must be adjacent only to the vertices $v$ such that $d[v] \ge i - 1$. Besides there i...
[ "dfs and similar", "graphs", "sortings" ]
1,800
null
404
D
Minesweeper 1D
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is $n$ squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play look...
This problem can be solved by using dynamic programming. Let's calculate $d[i][type]$ - the number of correct ways to fill the prefix of length $i$ so that the last filled cell has one of the $5$ types. These types are the following: the cell contains "0" the cell contains "1" and the cell to the left of it contains bo...
[ "dp", "implementation" ]
1,900
null
404
E
Maze 1D
Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number $0$ has a robot. The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Be...
Let's consider the case when the last move of the robot is equal to "R". If the last move is equal to "L" then we can replace all "L" by "R" and vise versa and the answer doesn't change. Let's show that Valera doesn't need more than one obstacle. Suppose Valera placed obstacles somewhere. We will say that the number of...
[ "binary search", "greedy", "implementation" ]
2,200
null
405
A
Gravity Flip
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are $n$ columns of toy cubes in the box arranged in a line. The $i$-th column contains $a_{i}$ cubes. At first, the gravity in the box i...
Observe that in the final configuration the heights of the columns are in non-decreasing order. Also, the number of columns of each height remains the same. This means that the answer to the problem is the sorted sequence of the given column heights. Solution complexity: $O(n)$, since we can sort by counting.
[ "greedy", "implementation", "sortings" ]
900
null
405
B
Domino Effect
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play \underline{with} the dominoes and make a "domino show". Chris arranges $n$ dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some o...
If the first pushed domino from the left was pushed to the left at position $l$, all dominoes at prefix $[1;l]$ fall down, otherwise let $l$ be 0. Similarly, if the first pushed domino from the right was pushed to the right at position $r$, all dominoes at suffix $[r;n]$ also fall down, otherwise let $r$ be $n + 1$. No...
[]
1,100
null
405
C
Unusual Product
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the \underline{unusual square} of a square matrix. The \underline{dot product} of two integer number vectors $x$ and $y$ of size $n$ is the sum of the products of the corresponding components of the vectors. The \underline{unusu...
Written as a formula, the problem asks to find the value of $\sum_{i=1}^{n}\sum_{j=1}^{n}A_{i j}A_{j i}{\mathrm{~(mod~}}2)$ Suppose that $i \neq j$. Then the sum contains summands $A_{ij}A_{ji}$ and $A_{ji}A_{ij}$. Since the sum is taken modulo 2, these summands together give 0 to the sum. It follows that the express...
[ "implementation", "math" ]
1,600
null
405
D
Toy Sum
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly $s$ blocks in Chris's set, each block has a unique number from 1 to $s$. Chris's teacher picks a subset of blocks $X$ and keeps it to himself. He will give th...
Let's define the symmetric number of $k$ to be $s + 1 - k$. Since in this case $s$ is an even number, $k \neq s - k$. Note that $(k - 1) + (s + 1 - k) = s$, i.e., the sum of a number and its symmetric is always $s$. Let's process the given members $x$ of $X$. There can be two cases: If the symmetric of $x$ does not b...
[ "greedy", "implementation", "math" ]
1,700
null
405
E
Graph Cutting
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with $n$ vertices (numbered from 1 to $n$) and $m$ edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to p...
It can be proved that only graphs with an odd number of edges cannot be partitioned into path of length 2. We will construct a recursive function that solves the problem and also serves as a proof for this statement. The function partition(v) will operate on non-blocked edges. It will partition the component of vertex ...
[ "dfs and similar", "graphs" ]
2,300
null
406
D
Hill Climbing
This problem has nothing to do with Little Chris. It is about hill climbers instead (and Chris definitely isn't one). There are $n$ hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to $n$ from left to right. The $i$-th hil...
Note that the path of each hill climber is strictly convex in any case. Let's draw the paths from all hills to the rightmost hill. Then these paths form a tree with the "root" at the top of the rightmost hill. We can apply the Graham scan from the right to the left to find the edges of this tree. Each pop and insert in...
[ "dfs and similar", "geometry", "trees" ]
2,200
null
406
E
Hamming Triples
Little Chris is having a nightmare. Even in dreams all he thinks about is math. Chris dreams about $m$ binary strings of length $n$, indexed with numbers from 1 to $m$. The most horrifying part is that the bits of each string are ordered in either ascending or descending order. For example, Chris could be dreaming abo...
Let's look at the Hamming graph of all possible distinct $2n$ strings, where each two strings are connected by an edge with length equal to the Hamming distance between these strings. We can observe that this graph has a nice property: if we arrange the vertices cyclically as a regular $2n$-gon with a side length of 1,...
[ "implementation", "math", "two pointers" ]
2,800
null
407
A
Triangle
There is a right triangle with legs of length $a$ and $b$. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the...
In this problem you have to locate the right triangle with cathetuses $a$, $b$ on a plane with its vertices in integer points. If the required layout exists, then cathetus $a$ always can be represented as a vector with integer coordinates $A{x;y}$, and $a^{2} = x^{2} + y^{2}$. Iterate over all possible $x$ ($1 \le x ...
[ "brute force", "geometry", "implementation", "math" ]
1,600
null
407
B
Long Path
One day, little Vasya found himself in a maze consisting of $(n + 1)$ rooms, numbered from $1$ to $(n + 1)$. Initially, Vasya is at the first room and to get out of the maze, he needs to get to the $(n + 1)$-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room nu...
In this problem you had to simulate route of character in graph. Note that if you are in vertice $i$, then edges in all vertices with numbers less than $i$ are turned to $p_{i}$. It gives us opportunity to see a recurrence formula: let $dp_{i}$ be number of steps, needed to get from vertice $1$ to vertice $i$, if all e...
[ "dp", "implementation" ]
1,600
null
407
C
Curious Array
You've got an array consisting of $n$ integers: $a[1], a[2], ..., a[n]$. Moreover, there are $m$ queries, each query can be described by three integers $l_{i}, r_{i}, k_{i}$. Query $l_{i}, r_{i}, k_{i}$ means that we should add $\binom{b-l_{i}+k_{i}}{k_{i}}$ to each element $a[j]$, where $l_{i} ≤ j ≤ r_{i}$. Record $\...
In this problem you had to find how to add binomial coefficients in array offline. Let's see, how problem changes due to increasing k from small to big values. 1) All queries have K = 0 Every time you add 1 on subsegment. For solve this task you can add 1 at some array b[] in b[L] 1, then substract 1 from b[R+1], and a...
[ "brute force", "combinatorics", "implementation", "math" ]
2,500
null
407
D
Largest Submatrix 3
You are given matrix $a$ of size $n × m$, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to $n$, the columns are numbered from left to right from 1 to $m$. We will denote the element on the intersecting of the $i$-th row and the $j$-th column as $a_{ij}$. W...
In this task you have to find largest by area submatrix, consisting from different numbers. Let's see solutions from slow to fast. 1) Solution by $O(n^{6})$: Iterate through two opposite vertices submatrix-answer and check that all numbers are different. 2) Solution by $O(n^{4})$: Let's fix Up and Down borders submatri...
[ "dp", "hashing" ]
2,700
null
407
E
k-d-sequence
We'll call a sequence of integers a good $k$-$d$ sequence if we can add to it at most $k$ numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference $d$. You got hold of some sequence $a$, consisting of $n$ integers. Your task is to find its longest contiguous subsegmen...
In this problem you have to find longest subsegment, satisfying the condition. Reduce problem to $d = 1$. If $d = 0$, then answer is longest subsegment from equal numbers, this case we solve separately. If $d \neq 0$, then notice that if on some subsegment there are two numbers $a_{i}, a_{j}$ so that $a_{i}$%$d \neq...
[ "data structures" ]
3,100
null
408
A
Line to Cashier
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are $n$ cashiers at the exit from the supermarket. At the moment the queue for the $i$-th cashier already has ...
In this problem you were to find waiting the time for every queue by summing up the purchases of all the people, and return the minimum.
[ "implementation" ]
900
null
408
B
Garland
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought $n$ colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly $m$ pieces of colored paper of arbitrary area, each pie...
In this problem it is necessary to find the garland with the maximal length, which can be composed of elements that we have. First, if you need some color, but you don't have it, then the answer is -1 Otherwise, answer is always exists. Let's sum the answers for all the colors separately. Suppose we have $a$ pieces of ...
[ "implementation" ]
1,200
null
411
A
Password Check
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
In the first problem you should correctly implement what was written in statement. It could be done like this:
[ "*special", "implementation" ]
800
null
411
B
Multi-core Processor
The research center Q has developed a new multi-core processor. The processor consists of $n$ cores and has $k$ cells of cache memory. Consider the work of this processor. At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an informat...
In this problem you should read the statement carefully, consider some principal cases and implement them in your program. The author's solution is: We will store array $blockedCell[]$ (value in cell $i$ equals $1$ if this cell is blocked, $0$ otherwise), blockedCore[]$ (value in cell $i$ equals $0$, if this core is no...
[ "implementation" ]
1,600
null
411
C
Kicker
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ...
To solve this problem you should use logic (mathematic logic) :] Logic says: If for some arrangement of the first team there is no arrangement to have even a draw then the first team is guaranteed to win. If for any arrangement of the first team there is some arrangement for the second team when the second team wins th...
[ "*special", "implementation" ]
1,700
null
412
A
Poster
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building. The slogan of the company consists of $n$ characters, so the decorators hung a l...
One of the optimal solutions is the following. If $k - 1 \le n - k$ then firstly let's move ladder to the left by $k - 1$ positions. After that we will do the following pair of operations $n - 1$ times: paint $i$-th symbol of the slogan and move the ladder to the right. In the end we will paint the last symbol of the...
[ "greedy", "implementation" ]
900
null