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 ⌀ |
|---|---|---|---|---|---|---|---|
441 | C | Valera and Tubes | Valera has got a rectangle table consisting of $n$ rows and $m$ columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row $x$ and column $y$ by a pair of integers $(x, y)$.
Valera want... | The solution is pretty simple. First we need to make such route that visits every cell exactly one time. It is not difficult: Initially we stay in $(1, 1)$ cell. Moving from left to right, we should reach $(1, m)$ cell. Move to the next line, in $(2, m)$ cell. Moving from right to left, we should reach the most left se... | [
"constructive algorithms",
"dfs and similar",
"implementation"
] | 1,500 | #undef NDEBUG
#ifdef gridnevvvit
#define _GLIBCXX_DEBUG
#endif
#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>
#inc... |
441 | D | Valera and Swaps | A permutation $p$ of length $n$ is a sequence of distinct integers $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$. A permutation is an identity permutation, if for any $i$ the following equation holds $p_{i} = i$.
A swap $(i, j)$ is the operation that swaps elements $p_{i}$ and $p_{j}$ in the permutation. Let's assume t... | In this task you should represent permutation as graph with $n$ vertexes, and from every vertex $i$ exists exactly one edge to vertex $p[i]$. It's easy to understand that such graph consists of simple cycles only. If we make swap $(i, j)$, edges $i\rightarrow p[i]$ and $j\to p[j]$ will become edges $i\rightarrow p[j]$ ... | [
"constructive algorithms",
"dsu",
"graphs",
"implementation",
"math",
"string suffix structures"
] | 2,100 | #include <cstdio>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
const int N = 3005;
int n, m, k, p[N];
bool used[N];
inline void use_cycle(int v) {
for (int i = v; !used[i]; i = p[i])
used[i] = true;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("... |
441 | E | Valera and Number | Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:
\begin{verbatim}
//input: integers x, k, p
a = x;
for(step = 1; step <= k; step = step + 1){
rnd = [random integer from 1 to 100];
if(rnd <= p)
a = a * 2;
else
a = a + 1;
}
s = 0;
while(remainder after dividing a by ... | We will solve the task by calculating dynamic $d[i][mask][last][cnt]$ - possibility of getting $v$ which $8$ last bits equals $mask$, 9th bit equals $last$, $cnt$ - number of consecutive bits (following 9th bit) and equal to $last$, after $i$ steps. Good, but why we left other bits? It's clear, that using operation $+ ... | [
"bitmasks",
"dp",
"math",
"probabilities"
] | 2,400 | #undef NDEBUG
#ifdef gridnevvvit
#define _GLIBCXX_DEBUG
#endif
#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>
#inc... |
442 | A | Borya and Hanabi | Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding $n$ cards. The game is somewhat complicated by the fact that everybody sees Borya's cards exc... | It's obvious that the order of hints doesn't metter. There are 10 types of hints, so we can try all $2^{10}$ vartiants of what other players should do. Now we need to check if Boris can describe all of his cards. He can do it iff he can distinguish all pairs of different cards. He can do it if somebody told at least on... | [
"bitmasks",
"brute force",
"implementation"
] | 1,700 | null |
442 | B | Andrey and Problem | Andrey needs one more problem to conduct a programming contest. He has $n$ friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choo... | Let's sort all friends in such a way that $p_{i} \le p_{j}$ iff $i \le j$. If there is $p_{i} = 1$ Andrey should ask only this friend. Now we can assume that all probabilities are less then 1. What should we maximize? ${\textstyle\sum_{i=0}^{n-1}p_{i}\prod_{j\neq i}(1-p_{j})=\sum_{i=0}^{n-1}{\textstyle{\frac{p_{i}}... | [
"greedy",
"math",
"probabilities"
] | 1,800 | null |
442 | C | Artem and Array | Artem has an array of $n$ positive integers. Artem decided to play with it. The game consists of $n$ moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets $min(a, b)$ points, where $a$ and $b$ are numbers that were adjacent with the removed number. If the number does... | It's obvious that we should never delete the first and last elements of array. Let's look at the minimum number. Let it be $x$ and there are $n$ elements in the array. We can subtract $x$ from all elements and the answer for the problem will decrease on $(n - 2) \cdot x$, becouse we will do $n - 2$ delitions of middle ... | [
"data structures",
"greedy"
] | 2,500 | null |
442 | D | Adam and Tree | When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions:
- There is no vertex that has more than two incident edges painted the same color.
- For any two verte... | First, let's solve the task with already built tree. We can do it with easy dymanic programming. We will count the answer for subtree with an edge to the parent. If we can count it for all vertices we can calculate the answer for the whole tree as maximum of answers for children of root. How to calculate it for one ver... | [
"data structures",
"trees"
] | 2,600 | null |
442 | E | Gena and Second Distance | Gena doesn't like geometry, so he asks you to solve this problem for him.
A rectangle with sides parallel to coordinate axes contains $n$ dots. Let's consider some point of the plane. Let's count the distances from this point to the given $n$ points. Let's sort these numbers in the non-decreasing order. We'll call the... | To solve this problem we can use a binary search. How do we check that answer if not less than $R$? It means that we can draw a circle with such radius which center locates in the rectangle and there are no more than one point inside this circle. How could we check it? We always can shift this circle in such a way that... | [
"geometry"
] | 3,100 | null |
443 | A | Anton and Letters | Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to tim... | In this task you are to count the number of different letters in the set. In my opinion the easiest way to do this looks like this. You just iterate over all small latin letters and check if the string contains it (with built-in functions). | [
"constructive algorithms",
"implementation"
] | 800 | null |
443 | B | Kolya and Tandem Repeat | Kolya got string $s$ for his birthday, the string consists of small English letters. He immediately added $k$ more characters to the right of the string.
Then Borya came and said that the new string contained a tandem repeat of length $l$ as a substring. How large could $l$ be?
See notes for definition of a tandem re... | Let's add $k$ question marks to the string. Than we can check all possible starting and ending positions of tandem repeat in a new string. We can check each of them in time $O(n + k)$. We only need to check that some symbols are equal (in our task question mark is equal to every symbol). | [
"brute force",
"implementation",
"strings"
] | 1,500 | null |
444 | A | DZY Loves Physics | DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
\[
\left\{{\frac{v}{e}}{\qquad(e>0)}\right.\qquad(e>0)
\]
where $v$ is the sum of the values of the nodes, $e$ i... | If there is a connected induced subgraph containing more than $2$ nodes with the maximum density. The density of every connected induced subgraph of it that contains only one edge can be represented as $\frac{\i I+v}{\mathbb{C}}$, where $u, v$ are the values of the two nodes linked by the edge. The density of the bigge... | [
"greedy",
"math"
] | 1,600 | #include <cstdio>
#include <algorithm>
using namespace std;
int n, m, a, b, c, x[1100];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &x[i]);
double ans = 0;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &a, &b, &c);
ans = max(ans, 1.0 * (x[a] + x[b]) / c);
}
printf("%.15lf\n... |
444 | B | DZY Loves FFT | DZY loves Fast Fourier Transformation, and he enjoys using it.
Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if $a$, $b$ and $c$ are sequences with length $n$, which are indexed from $0$ to $n - 1$, and
\[
c_{i}=\sum_{j=0}^{i}a_{j}b_{i-j}.
\]
We can calculate $c$ fast using... | Firstly, you should notice that $A$, $B$ are given randomly. Then there're many ways to solve this problem, I just introduce one of them. This algorithm can get $C_{i}$ one by one. Firstly, choose an $s$. Then check if $C_{i}$ equals to $n, n - 1, n - 2... n - s + 1$. If none of is the answer, just calculate $C_{i}$ by... | [
"probabilities"
] | 2,300 | #include <cstdio>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
int n, d, X, A[110000], B[110000], q[110000], to[110000];
int pu;
int getNextX() {
X = (X * 37LL + 10007) % 1000000007;
return X;
}
int main() {
scanf("%d%d%d", &n, &d, &X);
for (int i = 0; i < n; i = i + 1)
... |
444 | C | DZY Loves Colors | DZY loves colors, and he enjoys painting.
On a colorful day, DZY gets a colorful ribbon, which consists of $n$ units (they are numbered from $1$ to $n$ from left to right). The color of the $i$-th unit of the ribbon is $i$ at first. It is colorful enough, but we still consider that the colorfulness of each unit is $0$... | The only thing you need to notice is that if there are many continuous units with the same uppermost color, just merge them in one big unit. Every time painting continuous units, such big units will only increase by at most $3$. Then you can use STL set to solve it. But anyway, a segment tree is useful enough, check th... | [
"data structures"
] | 2,400 | #include <cstdio>
#include <algorithm>
using namespace std;
int n, m, t, l, r, x, mark[410000];
long long delta[410000], sum[410000];
void read(int &x) {
char k;
for (k = getchar(); k <= 32; k = getchar());
for (x = 0; '0' <= k; k = getchar()) x = x * 10 + k - '0';
}
void mkt(int k, int q, int h) {
if (q < h) {
... |
444 | D | DZY Loves Strings | DZY loves strings, and he enjoys collecting them.
In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.
Once DZY found a lucky string $s$. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the $i$-th pair has name $a_... | We can solve a subproblem in which all the query strings are characters only first. The problem becomes calculating the shortest substring containing two given characters. If character $ch$ appears more than $T$ times in $S$, use brute force with time complexity $O(|S|)$ to calculate all the queries containing $ch$. Ob... | [
"binary search",
"hashing",
"strings",
"two pointers"
] | 2,500 | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define pb push_back
#define mp make_pair
#define upmin(x,y) x=min(x,y)
const int L=50010,R=4,N=L*R,Q=100010,inf=int(1e9);
int l,q,g,all,i,j,k,p,x,y,p1,p2,res,tot;char s[L],s0[11];
int h[600... |
444 | E | DZY Loves Planting | DZY loves planting, and he enjoys solving tree problems.
DZY has a weighted tree (connected undirected graph without cycles) containing $n$ nodes (they are numbered from $1$ to $n$). He defines the function $g(x, y)$ $(1 ≤ x, y ≤ n)$ as the longest edge in the shortest path between nodes $x$ and $y$. Specially $g(z, z... | Firstly, use binary search. We need to determine whether the answer can be bigger than $L$. Then, every pair $(i, P_{i})$ must contain at least one edge which length is bigger than $L$. It's a problem like bipartite graph matching, and we can use maxflow algorithm to solve it. We create $2$ nodes for every node $i$ of ... | [
"binary search",
"dsu",
"trees"
] | 2,700 | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define REP(i,x,y) for(int i=(x);i<=(y);i++)
#define CL(S,x) memset(S,x,sizeof(S))
#define CP(S1,S2) memcpy(S1,S2,sizeof(S2))
#define pb push_back
const int N=12010,inf=int(1e9),V=100010,E=5... |
445 | A | DZY Loves Chessboard | DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of $n$ rows and $m$ columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th... | Just output the chessboard like this: WBWBWBWB... BWBWBWBW... WBWBWBWB... ... Don't forget to left '-' as it is. The time complexity is $O(nm)$. | [
"dfs and similar",
"implementation"
] | 1,200 | #include <cstdio>
using namespace std;
int n, m;
char S[1100];
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%s", S);
for (int j = 0; j < m; j++)
if (S[j] == '.') {
if ((i + j) & 1) S[j] = 'W';
else S[j] = 'B';
}
printf("%s\n", S);
}
} |
445 | B | DZY Loves Chemistry | DZY loves chemistry, and he enjoys mixing chemicals.
DZY has $n$ chemicals, and $m$ pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is $1$. And every time when DZY... | It's easy to find that answer is equal to $2^{n - v}$, where $v$ is the number of connected components. | [
"dfs and similar",
"dsu",
"greedy"
] | 1,400 | #include <cstdio>
using namespace std;
int n, m, fa[100], x, y;
int gf(int x) {
if (fa[x] != x) fa[x] = gf(fa[x]);
return fa[x];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--) {
scanf("%d%d", &x, &y);
fa[gf(x)] = gf(y);
}
long long ans = (1LL << n);
for (int i =... |
446 | A | DZY Loves Sequences | DZY has a sequence $a$, consisting of $n$ integers.
We'll call a sequence $a_{i}, a_{i + 1}, ..., a_{j}$ $(1 ≤ i ≤ j ≤ n)$ a subsegment of the sequence $a$. The value $(j - i + 1)$ denotes the length of the subsegment.
Your task is to find the longest subsegment of $a$, such that it is possible to change at most one ... | We can first calculate $l_{i}$ for each $1 \le i \le n$, satisfying $a_{i - li + 1} < a_{i - li + 2} < ... < a_{i}$, which $l_{i}$ is maximal. Then calculate $r_{i}$, satisfying $a_{i} < a_{i + 1} < ... < a_{i + ri - 1}$, which $r_{i}$ is also maximal. Update the answer $a n s=\operatorname*{max}(a n s,l_{i-1}+1+r_... | [
"dp",
"implementation",
"two pointers"
] | 1,600 | null |
446 | B | DZY Loves Modification | As we know, DZY loves playing games. One day DZY decided to play with a $n × m$ matrix. To be more precise, he decided to modify the matrix with exactly $k$ operations.
Each modification is one of the following:
- Pick some row of the matrix and decrease each element of the row by $p$. This operation brings to DZY th... | If $p = 0$, apperently the best choice is choosing the row or column which can give greatest pleasure value each time. Ignore $p$ first,then we can get a greatest number $ans$. Then if we choose rows for $i$ times, choose columns for $k - i$ times, $ans$ should subtract $(k - i) \times i \times p$. So we could enum... | [
"brute force",
"data structures",
"greedy"
] | 2,000 | null |
446 | C | DZY Loves Fibonacci Numbers | In mathematical terms, the sequence $F_{n}$ of Fibonacci numbers is defined by the recurrence relation
\[
F_{1} = 1; F_{2} = 1; F_{n} = F_{n - 1} + F_{n - 2} (n > 2).
\]
DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Moreover, there are $m$ ... | As we know, $F_{n}=\stackrel{\sqrt{5}}{5}\left[\left(\frac{1\!+\!\sqrt{5}}{2}\right)^{n}-\left(\frac{1\!-\!\sqrt{5}}{2}\right)^{n}\right]$ Fortunately, we find that $383008016^{2}\equiv5({\mathrm{mod}}\;10^{9}+9)$ So, $383008016\equiv{\sqrt{5}}({\mathrm{mod~}}10^{9}+9)$ With multiplicative inverse, we find, $\textstyle... | [
"data structures",
"math",
"number theory"
] | 2,400 | null |
446 | D | DZY Loves Games | Today DZY begins to play an old game. In this game, he is in a big maze with $n$ rooms connected by $m$ corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly.
DZY has got lost in the maze. Currently he is in the first room and... | Define important room as the trap room. Let $w(u, v)$ be equal to the probability that DZY starts at $u$ ($u$ is a important room or $u$=1) and $v$ is the next important room DZY arrived. For each $u$, we can calculate $w(u, v)$ in $O(n^{3})$ by gauss elimination. Let $A_{i}$ be equal to the $i$'th important room DZY a... | [
"math",
"matrices",
"probabilities"
] | 2,800 | null |
446 | E | DZY Loves Bridges | DZY owns $2^{m}$ islands near his home, numbered from $1$ to $2^{m}$. He loves building bridges to connect the islands. Every bridge he builds takes one day's time to walk across.
DZY has a strange rule of building the bridges. For every pair of islands $u, v (u ≠ v)$, he has built $2^{k}$ different bridges connecting... | Let $n = 2^{m}$. For convenience, we use indices $0, 1, ..., n - 1$ here instead of $1, 2, ..., n$, so we define $a_{0} = a_{n}$. Obviously this problem requires matrix multiplication. We define row vector $A=(a_{0},a_{1},\cdot\cdot\cdot,a_{n-1})$, and matrix $B=(b_{i j})$, where $b_{ii} = 1$, $b_{i j}=\operatorname*{m... | [
"math",
"matrices"
] | 3,100 | null |
447 | A | DZY Loves Hash | DZY has a hash table with $p$ buckets, numbered from $0$ to $p - 1$. He wants to insert $n$ numbers, in the order they are given, into the hash table. For the $i$-th number $x_{i}$, DZY will put it into the bucket numbered $h(x_{i})$, where $h(x)$ is the hash function. In this problem we will assume, that $h(x) = x mod... | We just need an array to store the numbers inserted and check whether a conflict happens. It's easy. | [
"implementation"
] | 800 | null |
447 | B | DZY Loves Strings | DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter $c$ DZY knows its value $w_{c}$. For each special string $s = s_{1}s_{2}... s_{|s|}$ ($|s|$ is the length of the string) he represents its value with a function $f(s)$, where
\[
f(s)=\sum_{i=1}^{\mathbb{N}_{1}}(w_{s_{i... | Firstly the optimal way is to insert letter with maximal $w_{i}$. Let $n u m=\mathbf{max}${$w_{i}$}. If we insert this character into the $k$'th position, the extra value we could get is equal to $\begin{array}{l}{{\sum_{i=k}^{n}w_{s_{i}}+n u m\star k=\sum_{i=1}^{k}n u m+\sum_{i=k}^{n}w_{s_{i}}}}\end{array}$. Because o... | [
"greedy",
"implementation"
] | 1,000 | null |
448 | A | Rewards | Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with $n$ shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has $a_{1}$ first prize cups, $a_{2}$ second pr... | Because rewards of one type can be on one shelf, lets calculate number of cups - $a$ and number of medals - $b$. Minimum number of shelves that will be required for all cups can be found by formula $(a + 5 - 1) / 5$. The same with shelves with medals: $(b + 10 - 1) / 10$. If sum of this two values more than $n$ then an... | [
"implementation"
] | 800 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
int main(){
//freopen("input.txt","r",stdin);// freopen("output... |
448 | B | Suffix Structures | Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.
At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), $s$ and $t$. You need to transform word $s$ into word $t$". The task looked simple to the guys because they know th... | Consider each case separately. If we use only suffix automaton then $s$ transform to some of its subsequence. Checking that $t$ is a subsequence of $s$ can be performed in different ways. Easiest and fastest - well-known two pointers method. In case of using suffix array we can get every permutation of $s$. If it is no... | [
"implementation",
"strings"
] | 1,400 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e5+5;
int cnt[30];
char s[N], t[N];
void solve(){
scanf("%s%s",&s,&... |
448 | C | Painting Fence | Bizon the Champion isn't just attentive, he also is very hardworking.
Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as $n$ vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from o... | To solve this problem we need to understand some little things. First, every horizontally stroke must be as widely as possible. Second, under every horizontally stroke should be only horizontally strokes. So, if bottom of fence painted by horizontally stroke then number of this strokes must at least $min(a_{1}, a_{2}, ... | [
"divide and conquer",
"dp",
"greedy"
] | 1,900 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
const int T = 1e6+6;
int a[N];
int t[T], d;
int rmq(int i, int j){
... |
448 | D | Multiplication Table | Bizon the Champion isn't just charming, he also is very smart.
While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an $n × m$ multiplication table, where the element on the intersection of the $i$-th row and $j$-th column equals $i·j$ (the r... | Solution is binary search by answer. We need to find largest $x$ such that amount of numbers from table, least than $x$, is strictly less than $k$. To calculate this count we sum counts from rows. In $i$ th row there will be $m i n({\frac{x-1}{i}},m)$. Total complexity is $O(nlog(nm))$. | [
"binary search",
"brute force"
] | 1,800 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
ll f(ll x, int n, int m){
ll res = 0;
--x;
for(int i=1;i<=n... |
448 | E | Divisors | Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function $f(a)$, where $a$ is a sequence of integers. Function $f(a)$ returns the following sequence: first all divisors of $a_{1}$ go in the increasing order, then all divisors of $a_{2}$ go in the increasing order, and so on till the l... | Learn how to transform $X_{i}$ into $X_{i + 1}$. For this we need to concatenate lists of divisors for all elements of $X_{i}$. To do this efficiently, precalculate divisors of $X$ (because for every $i$ $X_{i}$ consist of its divisors). It can be done by well-known method with $O({\sqrt{X}})$ complexity. How to calcul... | [
"brute force",
"dfs and similar",
"implementation",
"number theory"
] | 2,200 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e5;
vector<ll> d;
vector<ll> g[N];
vector<int> gi[N];
ll x;
vector<int> f(i... |
449 | A | Jzzhu and Chocolate | Jzzhu has a big rectangular chocolate bar that consists of $n × m$ unit squares. He wants to cut this bar exactly $k$ times. Each cut must meet the following requirements:
- each cut should be straight (horizontal or vertical);
- each cut should go along edges of unit squares (it is prohibited to divide any unit choco... | We assume that $n \le m$ (if $n > m$, we can simply swap $n$ and $m$). If we finally cut the chocolate into $x$ rows and $y$ columns $(1 \le x \le n, 1 \le y \le m, x + y = k + 2)$, we should maximize the narrowest row and maximize the narrowest column, so the answer will be $floor(n / x) * floor(m / y)$. The... | [
"greedy",
"math"
] | 1,700 | null |
449 | B | Jzzhu and Cities | Jzzhu is the president of country A. There are $n$ cities numbered from $1$ to $n$ in his country. City $1$ is the capital of A. Also there are $m$ roads connecting the cities. One can go from city $u_{i}$ to $v_{i}$ (and vise versa) using the $i$-th road, the length of this road is $x_{i}$. Finally, there are $k$ trai... | We consider a train route $(1, v)$ as an undirected deletable edge $(1, v)$. Let $dist(u)$ be the shortest path between $1$ and $u$. We add all of the edges $(u, v)$ weighted $w$ where $dist(u) + w = dist(v)$ into a new directed graph. A deletable edge $(1, v)$ can be deleted only if it isn't in the new graph or the in... | [
"graphs",
"greedy",
"shortest paths"
] | 2,000 | null |
449 | C | Jzzhu and Apples | Jzzhu has picked $n$ apples from his big apple tree. All the apples are numbered from $1$ to $n$. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be gr... | Firstly, we should notice that $1$ and the primes larger than $N / 2$ can not be matched anyway, so we ignore these numbers. Let's consider each prime $P$ where $2 < P \le N / 2$. For each prime $P$, we find all of the numbers which are unmatched and have a divisor $P$. Let $M$ be the count of those numbers we found.... | [
"constructive algorithms",
"number theory"
] | 2,500 | null |
449 | D | Jzzhu and Numbers | Jzzhu have $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. We will call a sequence of indexes $i_{1}, i_{2}, ..., i_{k}$ $(1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n)$ a group of size $k$.
Jzzhu wonders, how many groups exists such that $a_{i1}$ & $a_{i2}$ & ... & $a_{ik} = 0$ $(1 ≤ k ≤ n)$? Help him and print this num... | Firstly, we can use inclusion-exclusion principle in this problem. Let $f(x)$ be the count of number $i$ where $A_{i}&x = x$. Let $g(x)$ be the number of $1$ in the binary respresentation of $x$. Then the answer equals to $\textstyle\sum_{x=0}^{20}(-1)^{g(x)}2^{f(x)}$. Now the task is to calculate $f(x)$ for every inte... | [
"bitmasks",
"combinatorics",
"dp"
] | 2,400 | null |
449 | E | Jzzhu and Squares | Jzzhu has two integers, $n$ and $m$. He calls an integer point $(x, y)$ of a plane special if $0 ≤ x ≤ n$ and $0 ≤ y ≤ m$. Jzzhu defines a unit square as a square with corners at points $(x, y)$, $(x + 1, y)$, $(x + 1, y + 1)$, $(x, y + 1)$, where $x$ and $y$ are some integers.
Let's look at all the squares (their sid... | Consider there is only one query. Let me descripe the picture above. A grid-square can be exactly contained by a bigger square which coincide with grid lines. Let $L$ be the length of a side of the bigger square. Let $i$ be the minimum distance between a vertice of the grid-square and a vertice of the bigger square. Le... | [
"dp",
"math",
"number theory"
] | 2,900 | null |
450 | A | Jzzhu and Children | There are $n$ children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from $1$ to $n$. The $i$-th child wants to get at least $a_{i}$ candies.
Jzzhu asks children to line up. Initially, the $i$-th child stands at the $i$-th place of the line. Then Jzzhu start distribution... | You can simply simulate it or find the last maximum $ceil(a_{i} / m)$. | [
"implementation"
] | 1,000 | null |
450 | B | Jzzhu and Sequences | Jzzhu has invented a kind of sequences, they meet the following property:
\[
f_{1}=x;\ f_{2}=y;\ \forall\ i\ (i\geq2),f_{i}=f_{i-1}+f_{i+1}.
\]
You are given $x$ and $y$, please calculate $f_{n}$ modulo $1000000007$ $(10^{9} + 7)$. | We can easily find that every $6$ numbers are the same. It's like ${x, y, y - x, - x, - y, x - y, x, y, y - x, ...}$. | [
"implementation",
"math"
] | 1,300 | null |
451 | A | Game With Sticks | After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of $n$ horizontal and $m$ vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid show... | From a grid of size $n * m$, if we remove an intersection point, then the grid after removing the sticks passing through it, will of size $n - 1$, $m - 1$. Notice when the grid consists of a single horizontal stick and m vertical sticks, If we pick any intersection point, then the updated grid will be only made of vert... | [
"implementation"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
if (n > m) {
swap(n, m);
}
if (n % 2 == 0) {
cout << "Malvika" << endl;
} else {
cout << "Akshat" << endl;
}
return 0;
} |
451 | B | Sort the Array | Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array $a$ consisting of $n$ \textbf{distinct} integers.
Unfortunately, the size of $a$ is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following ques... | Note that if from a given sorted array, if reverse a segment, then the remaining array will be arranged in following way. First increasing sequence, then decreasing, then again increasing. You can find the first position where the sequences start decreasing from the beginning. Call it $L$. You can find the first positi... | [
"implementation",
"sortings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int N = (int) 1e5 + 5;
int a[N], b[N];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = a[i];
}
map<int, int> mp;
sort(b, b + n);
for (int i = 0; i < n; i++) {
mp[b[i]] = i;
}
for (int i = 0; i < n; i++) {
a[i] = m... |
451 | C | Predict Outcome of the Game | There are $n$ games in a football tournament. Three teams are participating in it. Currently $k$ games had already been played.
You are an avid football fan, but recently you missed the whole $k$ games. Fortunately, you remember a guess of your friend for these $k$ games. Your friend did not tell exact number of wins ... | Let $x_{1}$ be number of wins of first team in the first k games. Let $x_{2}$ be number of wins of second team in the first k games. Let $x_{3}$ be number of wins of third team in the first k games. Note that $x_{1} + x_{2} + x_{3} = k$ ---(1) $|x_{1} - x_{2}| = d_{1}.$ - (a) $|x_{2} - x_{3}| = d_{2}.$ - (b) Note that ... | [
"brute force",
"implementation",
"math"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int solveFaster(LL n, LL k, LL d1, LL d2) {
if (n % 3 != 0) {
return 0;
}
for (int sign1 = -1; sign1 <= 1; sign1++) {
for (int sign2 = -1; sign2 <= 1; sign2++) {
if (sign1 == 0 || sign2... |
451 | D | Count Good Substrings | We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
- the number of good substrings of even length;
- the number of good substri... | Merging Step: We have to convert string like "aaaabbbaabaaa" into "ababa". Important Observation A substring made of the string will be a "good" palindrome if their starting and ending characters are same. If the starting and ending characters are same, then the middle characters after merging will be alternating betwe... | [
"math"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
pair<LL, LL> solve(string s)
{
LL ansEven = 0, ansOdd = 0;
int cntEven[2], cntOdd[2];
cntEven[0] = cntEven[1] = cntOdd[0] = cntOdd[1] = 0;
for (int i = 0; i < s.size(); i++)
{
ansOdd++;
int id ... |
451 | E | Devu and Flowers | Devu wants to decorate his garden with flowers. He has purchased $n$ boxes, where the $i$-th box contains $f_{i}$ flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.
Now Devu wants to select \textbf{exactly} $s$ flowers from ... | The number of ways to choose $N$ items out of $R$ groups where each item in a group is identical is equal to the number of integral solutions to $x_{1} + x_{2} + x_{3}...x_{R} = N$, where $0 \le x_{i} \le L_{i}$, where $L_{i}$ is the number of items in $i^{th}$ group. Number of integral solutions are coefficient of... | [
"bitmasks",
"combinatorics",
"number theory"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define snuke(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
const long long mod = (long long) (1e9 + 7);
int n;
LL f[22], s, inv[55];
LL nCr(LL n, LL r) {
if (r ... |
452 | B | 4-point polyline | You are given a rectangular grid of lattice points from $(0, 0)$ to $(n, m)$ inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.
A polyline defined by points $p_{1}, p_{2}, p_{3}, p_{4}$ consists o... | The critical observation in this problem is that the points will be at the corners or very close to the corners. After that one simple solution would be to generate a set of all the points that are within 4 cells from some corner, and consider all quadruplets of points from that set. | [
"brute force",
"constructive algorithms",
"geometry",
"trees"
] | 1,800 | null |
452 | C | Magic Trick | Alex enjoys performing magic tricks. He has a trick that requires a deck of $n$ cards. He has $m$ identical decks of $n$ different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs $n$ cards at random and performs the trick with those. The resulting deck looks like a normal dec... | When the magician reveals the card, he has $\textstyle{\frac{1}{k}}$ chance to reveal the same exact card that you have chosen. With the remaining $\frac{k{\mathrm{k}}-1}{k}$ chance he will reveal some other card. Since all the cards in all $m$ decks are equally likely to be in the $n$ cards that he uses to perform the... | [
"combinatorics",
"math",
"probabilities"
] | 2,100 | null |
452 | D | Washer, Dryer, Folder | You have $k$ pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has $n_{1}$ washing machines, $n_{2}$ drying machines and $n_{3}$ folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't... | One way to solve this problem is to maintain three deques, one per machine type, each one containing moments of time when the machines of this type will be available in increasing order. Originally each deck has as many zeroes, as many machines of that type are available. For each piece of laundry, see the earliest mom... | [
"greedy",
"implementation"
] | 1,900 | null |
452 | E | Three strings | You are given three strings $(s_{1}, s_{2}, s_{3})$. For each integer $l$ $(1 ≤ l ≤ min(|s_{1}|, |s_{2}|, |s_{3}|)$ you need to find how many triples ($i_{1}, i_{2}, i_{3}$) exist such that three strings $s_{k}[i_{k}... i_{k} + l - 1]$ $(k = 1, 2, 3)$ are pairwise equal. Print all found numbers modulo $1000000007 (10^{... | This problem requires one to use one of the datastructures, such as suffix array, suffix tree or suffix automata. The easiest solution uses a compressed suffix tree. Build one suffix tree on all three strings. For simplicity add some non-alphabetic character at the end of each string. For every node in the tree store h... | [
"data structures",
"dsu",
"string suffix structures",
"strings"
] | 2,400 | null |
452 | F | Permutation | You are given a permutation of numbers from $1$ to $n$. Determine whether there's a pair of integers $a, b$ $(1 ≤ a, b ≤ n; a ≠ b)$ such that the element $\textstyle{\frac{(a+b)}{2}}$ (note, that it is usual division, not integer one) is between $a$ and $b$ in this permutation. | There are at least two different ways to solve this problem First way is to notice that almost all the permutations have such numbers $a$ and $b$. Consider solving the opposite problem: given $n$, build a permutation such that no subsequence of length 3 forms an arithmetic progression. One way to do that is to solve si... | [
"data structures",
"divide and conquer",
"hashing"
] | 2,700 | null |
453 | A | Little Pony and Expected Maximum | Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has $m$ faces: the first face of the dice contains a dot, the second one contains two dots... | Take $m$ = 6, $n$ = 2 as a instance. 6 6 6 6 6 6 5 5 5 5 5 6 4 4 4 4 5 6 3 3 3 4 5 6 2 2 3 4 5 6 1 2 3 4 5 6Enumerate the maximum number, the distribution will be a $n$-dimensional super-cube with $m$-length-side. Each layer will be a large cube minus a smaller cube. So we have: $\textstyle\sum_{i=1}^{m}i(i^{n}-(i-1)^{... | [
"probabilities"
] | 1,600 | null |
453 | B | Little Pony and Harmony Chest | Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.
A sequence of positive integers $b_{i}$ is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony s... | Since {1, 1 $...$, 1} is a pairwise coprime sequence, the maximum element of $b_{i}$ can never greater then $2mx - 1$. Here $mx$ is the maximum elements in $a_{i}$. So what we need consider is the first a few prime factors. It is not hard to use bitmask-dp to solve this: for (int i = 1 ; i <= n ; i ++) { for (int k = 1... | [
"bitmasks",
"brute force",
"dp"
] | 2,000 | null |
453 | C | Little Pony and Summer Sun Celebration | Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.
Twi... | There is no solution if there is more than 1 connected component which have odd node (because we can't move between two component), otherwise it is always solvable. This fact is not obvious, let's focus on one component. You can select any node to start, denoted it as $r$ (root). Start from $r$, you can go to any other... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,200 | null |
453 | D | Little Pony and Elements of Harmony | The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with $n$ vertices labeled from 0 to $n - 1$, where $n$ is a power of two, equal to $2^{m}$.
The en... | Let's consider the $e$ = [1 1 $...$ 1]. After a period, it will be $ke$ where $k$ is a const. So we know that [1 1, $...$, 1] is an eigenvector and $k$ is the corresponding an eigenvalue. The linear transformation has $2^{m}$ eigenvectors. The $i(0 \le i < 2^{m})$-th eigenvector is [(-1)^f(0, i) (-1)^f(1, i) $...$ (-... | [
"dp",
"matrices"
] | 3,000 | null |
453 | E | Little Pony and Lord Tirek | Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger.
The core skill of Tirek is called Absorb Mana. It takes all mana from a ma... | Key Observation The income of a operation, is only relevant with the previous operation. In other words, what we focus on is the difference time between adjacent operations. Weaken the problem Let us assume $s_{i} = 0$ and $r_{i} = 1$ at the beginning to avoid disrupting when we try to find the main direction of the al... | [
"data structures"
] | 3,100 | null |
454 | A | Little Pony and Crystal Mine | Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size $n$ ($n$ is odd; $n > 1$) is an $n × n$ matrix with a diamond inscribed into it.
You are given an odd integer $n$. You need to draw a crystal of size $n$. The diamond cells of the matrix should be represented by character "D". All other cells... | Just a few basics of your programming language. It's easy. | [
"implementation"
] | 800 | null |
454 | B | Little Pony and Sort by Shift | One day, Twilight Sparkle is interested in how to sort a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
\[
a_{1}, a_{2}, ..., a_{n} → a_{n}, a_{1... | Just a few basics of your programming language. It's not hard. | [
"implementation"
] | 1,200 | null |
455 | A | Boredom | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence $a$ consisting of $n$ integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it $a_... | In this task we need to maximize the sum of numbers that we took. Let precalc array $cnt$. $cnt[x]$ - number of integers $x$ in array $a$. Now we can easily calculate the DP: $f(i) = max(f(i - 1), f(i - 2) + cnt[i] \cdot i)$, $2 \le i \le n$; $f(1) = cnt[1]$; $f(0) = 0$; The answer is $f(n)$. Asymptotics - $O(n)$. | [
"dp"
] | 1,500 | null |
455 | B | A Lot of Games | Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of $n$ non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the ... | To solve this problem we need the prefix tree(trie), which will have all the strings from the group. Next we will calculate the two DP: win[v] - Can player win if he makes a move now (players have word equal to prefix $v$ in the prefix tree(trie)). lose[v] - Can player lose if he makes a move now (players have word equ... | [
"dfs and similar",
"dp",
"games",
"implementation",
"strings",
"trees"
] | 1,900 | null |
455 | C | Civilization | Andrew plays a game called "Civilization". Dima helps him.
The game has $n$ cities and $m$ bidirectional roads. The cities are numbered from $1$ to $n$. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities $v_{1}, v_{2}, ..., v_{k}$... | You can see that the road system is a forest. For efficient storage component we need to use DSU. First, we need to build the initial system of roads. For each component of the initial road system, we must find the diameter of component. This can be done using a DFS or BFS. Let $a$ - any vertex of component. Let $b$ - ... | [
"dfs and similar",
"dp",
"dsu",
"ternary search",
"trees"
] | 2,100 | null |
455 | D | Serega and Fun | Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem.
You are given an array $a$ consisting of $n$ positive integers and queries to it. The queries can be of two types:
- Make a unit cyclic shift to the right on the segme... | Let's change the query type $1$ to two more simple requests: Erase a number from $r$-th position. Insert this number after $(l - 1)$-th position. Now let's keep our array as $\sqrt{n}$ blocks. In each block will store the numbers themselves in such a manner as in the array $a$ and will store an array $cnt$. $cnt[x]$ - ... | [
"data structures"
] | 2,700 | null |
455 | E | Function | Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that:
- $f(1, j) = a[j]$, $1 ≤ j ≤ n$.
- $f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j]$, $2 ≤ i ≤ n$, \textbf{$i ≤ j ≤ n$}.
Here $a$ is an integer array of length $n$.
Serega and Fedya want to know what va... | In this problem you should quickly be able to compute the function described in the statement. You may notice that this task is equivalent to next task: Go through the array $a$, starting from the position of $y$, making $(x - 1)$ step. Step might be: step to the left or to stay in place. Function is calculated as foll... | [
"data structures"
] | 2,900 | null |
456 | A | Laptops | One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | In this task you need to check the existense of such pair $i$ and $j$, such that $i \neq j$, $a[i] < a[j]$, $b[i] > b[j]$. If such $i$ and $j$ exist, Alex is happy. There is very simple solution. Let's check that for all $i$ $a[i] = b[i]$. If this condition is true we should print "Poor Alex". We can easy prove it. L... | [
"sortings"
] | 1,100 | null |
456 | B | Fedya and Maths | Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
\[
(1^{n} + 2^{n} + 3^{n} + 4^{n}) mod 5
\]
for given value of $n$. Fedya managed to complete the task. Can you? Note that given number $n$ can be extremely large (e.g. it can exceed any integer type of your programming lan... | In this task you need to calculate formula that given in the statement, but it's hard to calculate it with the naive way. But we can transform our formula to this: $\begin{array}{c}{{\left(1^{n}+2^{n}+3^{n}+4^{n}\right)\,\mathrm{mod}\,\,5\,=\,\left(1^{n}\,\,m o o d\,\,\phi(n)\,+\,3^{n}\,\,m o d\,\,\phi(n)\,+\,3^{n}\,\,... | [
"math",
"number theory"
] | 1,200 | null |
457 | A | Golden System | Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number $q={\frac{{\sqrt{5}}+1}{2}}$, in particular that $q^{2} = q + 1$, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden... | The important observation one needs to make is that $q^{n} = q^{n - 1} + q^{n - 2}$, which means that we can replace two consecutive '1' digits with one higher significance digit without changing the value. Note that sometimes the next digit may become more than '1', but that doesn't affect the solution. There are two ... | [
"math",
"meet-in-the-middle"
] | 1,700 | null |
457 | B | Distributed Join | Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.
Suppose she wants to join two tables, $A$ and $B$. Each of them has certain number of rows which are distributed on different number of partitions. Table $A$ is distributed on the first cluster cons... | One of the optimal strategies in this problem is to locate a node $a$ with the most rows, then move all the data from the cluster $a$ does not belong to onto $a$, and then for every other node $b$ in the cluster that $a$ belongs to either move all the data from $b$ onto $a$, or move all the rows from the other cluster ... | [
"greedy"
] | 1,900 | null |
457 | C | Elections | You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest am... | First let's consider a subproblem in which we know how many votes we will have at the end, and we want to figure out how much money we will spend. To solve this problem, one first needs to buy the cheapest votes from all the candidates who have as many or more votes. If after that we still don't have enough votes, we b... | [
"brute force"
] | 2,100 | null |
457 | D | Bingo! | The game of bingo is played on a $5 × 5$ square grid filled with distinct numbers between $1$ and $75$. In this problem you will consider a generalized version played on an $n × n$ grid with distinct numbers between $1$ and $m$ $(m ≥ n^{2})$.
A player begins by selecting a randomly generated bingo grid (generated unif... | The score function of a board in the problem is $2^{x}$, where $x$ is number of rows and columns fully covered. Since $2^{x}$ is the number of all the subsets of a set of size $x$ (including both a full set and an empty set), the score function is essentially the number of ways to select a set of fully covered rows and... | [
"combinatorics",
"math",
"probabilities"
] | 2,700 | null |
457 | E | Flow Optimality | There is a computer network consisting of $n$ nodes numbered 1 through $n$. There are links in the network that connect pairs of nodes. A pair of nodes may have multiple links between them, but no node has a link to itself.
Each link supports unlimited bandwidth (in either direction), however a link may only transmit ... | Let's begin by considering an arbitrary cycle in the given graph (if one exists). We could add some amount of flow to each edge in the cycle, and doing so must result in an equivalent or worse cost (otherwise the intern's solution would clearly be non-optimal). Thus if we consider the function c(x) = sum(w_i * (f_i + x... | [
"constructive algorithms",
"flows",
"math"
] | 3,000 | null |
457 | F | An easy problem about trees | Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.
On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of th... | The solution for this problem is a dynamic programming on a tree with O(n) complexity. In this editorial "even tree" means a tree in which players will make an even number of turns, while "odd tree" is the tree in which players will make an odd number of turns. We will be solving a slightly modified problem: one in whi... | [
"dp",
"games",
"greedy",
"trees"
] | 3,200 | null |
459 | A | Pashmak and Garden | Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al... | Four vertices of a square with side length $a$ (and sides parallel to coordinate axis) are in this form: $(x_{0}, y_{0})$, $(x_{0} + a, y_{0})$, $(x_{0}, y_{0} + a)$, $(x_{0} + a, y_{0} + a)$. Two vertices are given, calculate the two others (and check the ranges). Total complexity : $O(1)$ | [
"implementation"
] | 1,200 | null |
459 | B | Pashmak and Flowers | Pashmak decided to give Parmida a pair of flowers from the garden. There are $n$ flowers in the garden and the $i$-th of them has a beauty number $b_{i}$. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty dif... | If all numbers are equal then answer will be $n * (n - 1) / 2$, otherwise the answer will be $cnt_{1} * cnt_{2}$, where $cnt_{1}$ is the number of our maximum elements and $cnt_{2}$ is the number of our minimum elements. Total complexity : $O(n)$ | [
"combinatorics",
"implementation",
"sortings"
] | 1,300 | null |
459 | C | Pashmak and Buses | Recently Pashmak has been employed in a transportation company. The company has $k$ buses and has a contract with a school which has $n$ students. The school planned to take the students to $d$ different places for $d$ days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has t... | For each student consider a sequence of $d$ elements from $1$ to $k$ that shows the bus number which is taken by this student on each day. Obviously, there are $k^{d}$ different sequence at all, so if $n > k^{d}$, pigeonhole principle indicates that at least two of this sequences will be equal, so that two students wil... | [
"combinatorics",
"constructive algorithms",
"math"
] | 1,900 | null |
459 | D | Pashmak and Parmida's problem | Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.
There is a sequence $a$ that consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Let's denote $f(l, r, x)$ th... | First of all, we can map the given numbers to integers of range $[1, 10^{6}]$. Let $l_{i}$ be $f(1, i, a_{i})$ and let $r_{i}$ be $f(i, n, a_{i})$, we want to find the number of pairs $(i, j)$ such that $i < j$ and $l_{i} > r_{j}$. For computing $l_{i}$s, we can store an array named $cnt$ to show the number of occurenc... | [
"data structures",
"divide and conquer",
"sortings"
] | 1,800 | null |
459 | E | Pashmak and Graph | Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with $n$ vertices and $m$ edges. You need to find a path (... | In this problem, a directed graph is given and we have to find the length of a longest strictly-increasing trail in it. First of all consider a graph with $n$ vertices and no edges, then just sort the given edges by their weights (non-decreasingly) and add them to the graph one by one. Let $dp[v]$ be the length of a lo... | [
"dp",
"sortings"
] | 1,900 | null |
460 | A | Vasya and Socks | Vasya has $n$ pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every $m$-th day (at days with numbers $m, 2m, 3m, ...$) mom buys a pair of socks to Vasya. She does it late in t... | At this problem you need to model what written in statements. Also, it can be proved, that answer can be calculated using formula: $n+{\bigl\lfloor}{\frac{n-1}{m-1}}{\bigr\rfloor}$ , where $ \lfloor x \rfloor $ is the integer part of $x$. | [
"brute force",
"implementation",
"math"
] | 900 | #include <iostream>
using namespace std;
int solve(int n, int m)
{
int s = 0;
s = n + n/(m - 1);
if (n%(m - 1) == 0)
s -= 1;
return s;
}
int main()
{
int n, m;
cin >> n >> m;
cout << solve(n,m) << endl;
return 0;
} |
460 | B | Little Dima and Equation | Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.
Find all integer solutions $x$ $(0 < x < 10^{9})$ of the equation:
\[
x = b·s(x)^{a} + c,
\]
where $a$, $b$, $c$ are some predetermined constant values and function $s(x)$ determines th... | Obviously $S(x)$ can take only integer values and $1 \le S(x) \le 81$. Let's check $S(x)$ from $1$ to $81$, and calculate $B * S(x)^{A} + C$. After that if sum of digits of this number is equal to $S(x)$, it is positive and less than $10^{9}$, than it is a solution. There could be bug because of using C++ pow() fun... | [
"brute force",
"implementation",
"math",
"number theory"
] | 1,500 | #include<iostream>
#include<vector>
using namespace std;
#define ll long long
ll S(ll x)
{
if (x < 0)return -1;
ll s = 0;
while(x)
{
s += x%10;
x /= 10;
}
return s;
}
ll poww(ll a, ll b)
{
ll res = 1;
for(int i = 1; i<=b; ++i)
res *= a;
return res;
}
... |
460 | C | Present | Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted $n$ flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver no... | Note,that answer is positive integer not greater than $10^{9} + 10^{5}$. Using binary search on answer, we will find answer. Really, we can check in $O(n)$ if some height is achievable. We go from left to right. For current flower we calculate how much times it need to be watered to stand not lower than checking value.... | [
"binary search",
"data structures",
"greedy"
] | 1,700 | #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define lol long long
using namespace std;
const lol MAXVAL = 1000100000;
lol n, m, w;
vector<lol> a;
void read()
{
cin >> n >> m >> w; //m - number of moves, w - width
a.resize(n);
for (lol i = 0; i < n; i++)
cin >> ... |
460 | D | Little Victor and Set | Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers $S$ that has the following properties:
- for all $x$ $(x\in S)$ the following inequality holds $l ≤ x ≤ r$;
- $1 ≤ |S| ≤ k$;
- lets denote the $... | If $r - l \le 4$ we can all subsets of size not greater than $k$. Else, if $k = 1$, obviously that answer is $l$. If $k = 2$, answer is $1$, because $xor$ of numbers $2x$ and $2x + 1$ equls $1$. If $k \ge 4$ answer is $0$ because $xor$ of to pairs with $xor$ $1$ is $0$. If $k = 3$, we can choose numbers $2x$ and $2... | [
"brute force",
"constructive algorithms",
"math"
] | 2,300 | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const long long INF = 10000000000001;
int numberOfOnes(int x)
{
int num=0;
while (x)
{
num += x&1;
x >>= 1;
}
return num;
}
void solution1(long long a, long long b, int k)
{
vector<long long> an... |
460 | E | Roland and Rose | Roland loves growing flowers. He has recently grown a beautiful rose at point $(0, 0)$ of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it.
To protect the rose, Roland wants to build $n$ watch towers. Let's assume that a tower is a point on the p... | Formal statement: 2 natural numbers are given: $R$ - radii, and $N$ - number of points. You have to choose $N$ unnesessarily distinct points $A_{1}, A_{2}, ...A_{N}$ which are lying inside or on side of circle, such that $\textstyle\sum_{i<j}A_{i}A_{j}^{2}$ takes its maximal value. At first let ${\overline{{a_{i}}}}$ b... | [
"brute force",
"geometry",
"math",
"sortings"
] | 2,700 | #include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define lol long long
int N, R;
struct point
{
int x;
int y;
point(int xx, int yy)
{
x = xx;
y = yy;
}
};
bool inner(point A)
{
return (A.x*A.x + A.y*A.y <= R*R);
}
vector <point> c... |
461 | A | Appleman and Toastman | Appleman and Toastman play a game. Initially Appleman gives one group of $n$ numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
- Each time Appleman g... | First I describe the algorithm, and explain why it works. Sort {$a_{i}$} in non-decreasing order. Then, for $i$-th number, add $(i + 1) * a_{i}$ to the result.(i=1...n-1) For $n$-th number, add $n * a_{n}$ to the result. Actually, when you multiply all numbers by -1,the answer will be the minimal possible value, multip... | [
"greedy",
"sortings"
] | 1,200 | null |
461 | B | Appleman and Tree | Appleman has a tree with $n$ vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of $k$ $(0 ≤ k < n)$ edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into $(k + 1)$ parts. Note, that each part will b... | Fill a DP table such as the following bottom-up: DP[v][0] = the number of ways that the subtree rooted at vertex v has no black vertex. DP[v][1] = the number of ways that the subtree rooted at vertex v has one black vertex. The recursion pseudo code is folloing: DFS(v): DP[v][0] = 1 DP[v][1] = 0 foreach u : the childre... | [
"dfs and similar",
"dp",
"trees"
] | 2,000 | null |
461 | C | Appleman and a Sheet of Paper | Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions $1 × n$. Your task is help Appleman with folding of such a sheet. Actually, you need to perform $q$ queries. Each query will have one of the following types:
- Fold the sheet of paper at position $p_{i}$. After this query the le... | For each first type queries that p_i > (the length of the paper) - p_i, you should express the operation in another way: not fold the left side of the paper but fold the right side of the paper. After such query you need to think as the paper is flipped. Let's define count[i] as the number of papers piled up at the seg... | [
"data structures",
"implementation"
] | 2,200 | null |
461 | D | Appleman and Complicated Task | Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must con... | First, we ignore the already drawn cell and dependence of cells. If we decide the first row, then the entire board can decided uniquely. We call 'o' is 1, and 'x' is 0. Then, a[i][j] = a[i-2][j] xor a[i-1][j-1] xor a[i-1][j+1] For example, I'll explain n=5 case. Each column of first row is a, b, c, d, and e. "ac" means... | [
"dsu",
"math"
] | 2,800 | null |
461 | E | Appleman and a Game | Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings $s$ and $t$ both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string $s$ as quickly as possible. Initially he has empty string, and in one second he can ... | Let C be the number of characters(here, C=4) Given string S, the way to achieve minimum steps is as follows: Append one of the longest substring of T that fits current position of string S. Appending a not-longest substring can be replaced by appending longest substring and shortening the next substring appended. Let d... | [
"binary search",
"shortest paths",
"strings"
] | 3,000 | null |
462 | A | Appleman and Easy Task | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of ... | This is a simple implementation problem. You can solve by searching adjacent cells of every cell. | [
"brute force",
"implementation"
] | 1,000 | null |
462 | B | Appleman and Card Game | Appleman has $n$ cards. Each card has an uppercase letter written on it. Toastman must choose $k$ cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card $i$ you should calculate how much Toastman's cards have the letter equal to lette... | This is simple greedy problem, but it seemed to be reading-hard. The statement says, "Choose K cards from N cards, the score of each card is (the number of cards which has the same character in K cards. (not in N cards)" It is clear that this total score is (the number of 'A' in K cards)^2 + (the number of 'B' in K car... | [
"greedy"
] | 1,300 | null |
463 | A | Caisa and Sugar | Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just $s$ dollars for sugar. But that's not a reason to be sad, because there are $n$ types of sugar in the supermarket, maybe he able to buy one. B... | This is a simple implementation problem. | [
"brute force",
"implementation"
] | 1,200 | #include <iostream>
#include <cstdio>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.out","w",stdout);
#endif
int n, s;
cin.sync_with_stdio(false);
cin >> n >> s;
int sol = 100;
bool ok = 0;
for(int i = 1;i <= n; ++i){
... |
463 | B | Caisa and Pylons | Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are $(n + 1)$ pylons numbered from $0$ to $n$ in this game. The pylon with number $0$ has zero height, the pylon with number $i$ $(i > 0)$ has height $h_{i}$. The goal of the game is to ... | We have to use greedy method. Start from the first element and pass all the elements in order(also update by the energy).When energy < 0, add abs(energy) to solution and energy becomes 0 or we can find the answer by binary search. | [
"brute force",
"implementation",
"math"
] | 1,100 | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.out","w",stdout);
#endif
int x = 0, y, n, sol = 0,energy = 0;
cin >> n;
for(int i = 1;i <= n; ++i)
{
cin >> y;
energy += x-y;... |
463 | C | Gargari and Bishops | Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a $n × n$ chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both ... | We preprocess the sum for all the diagonals(principals and secondary diagonals) in two arrays(so that for every element $i$,$j$ we can find sum of elements which are attacked in O(1) time).Also for avoiding the intersection,we need to find two cells so that for one the sum of row and column is even and for the other on... | [
"greedy",
"hashing",
"implementation"
] | 1,900 | #include <iostream>
#include <cstdio>
using namespace std;
const int NMAX = 2014;
long long d1[2*NMAX], d2[2*NMAX], sol[2];
pair < int , int > v[2];
int a[NMAX][NMAX];
inline void Update(const int c,const int i,const int j,const long long val){
if(val > sol[c]){
sol[c] = val;
v[c].first = i;
... |
463 | D | Gargari and Permutations | Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found $k$ permutations. Each of them consists of numbers $1, 2, ..., n$ in some order. Now he should find the length of the longest common subsequence of these permutations.... | We can build a directed acyclic graph with $n$ nodes.If $j$ is after $i$ in all vectors then we add in graph edge ($i$,$j$).Now we have to find the longest path in this graph. Another way is using dp. | [
"dfs and similar",
"dp",
"graphs",
"implementation"
] | 1,900 | #include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 1010;
int N, K, V[10][NMAX], Pos[10][NMAX], Best[NMAX], Ans;
vector<int> G[NMAX];
bool Used[NMAX];
void DFS(int Node)
{
Used[Node] = 1;
for(int i = 0; i < G[Node].size(); ++ i)
{
if(!... |
463 | E | Caisa and Tree | Caisa is now at home and his son has a simple task for him.
Given a rooted tree with $n$ vertices, numbered from $1$ to $n$ (vertex $1$ is the root). Each vertex of the tree has a value. You should answer $q$ queries. Each query is one of the following:
- Format of the query is "1 $v$". Let's write out the sequence o... | We use an array of dynamic stacks for every prime factor.We start a DFS from node 1.For node 1 we decompose its value in prime factors and push it to every prime factor's stack.To answer the question for $x$,we need to see the $y$ ($y$ belongs to the chain from 1 to $x$) that has a common prime factor with x,so the sta... | [
"brute force",
"dfs and similar",
"math",
"number theory",
"trees"
] | 2,100 | #include <vector>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <bitset>
using namespace std;
const int NMAX = 100004;
const int VALMAX = 2e6;
vector < int > Tree[NMAX];
int value[NMAX], niv[NMAX] , answer[NMAX];
bitset < VALMAX+6> viz;
int prime[2*NMAX],pos[6+VALMAX];
stack < in... |
464 | A | No to Palindromes! | Paul \underline{hates} palindromes. He assumes that string $s$ is \underline{tolerable} if each its character is one of the first $p$ letters of the English alphabet and $s$ doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string $s$ of length $n$. Help him find the l... | If string $s$ contains a non-trivial palindromic substring $w$, then it must contain palindromic substring of length 2 or 3 (for instance, center of $w$). Therefore the string is tolerable iff no adjacent symbols or symbols at distance 1 are equal. Now for the lexicographically next tolerable string $t$. $t$ is greater... | [
"greedy",
"strings"
] | 1,700 | null |
464 | B | Restore Cube | Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — c... | There are several ways to solve this problem. We'll describe the most straightforward one: we can generate all possible permutations of coordinates of every point and for every combination check whether given point configuration form a cube. However, number of configurations can go up to $(3!)^{8} > 10^{6}$, so checkin... | [
"brute force",
"geometry"
] | 2,000 | null |
464 | C | Substitutes in Number | Andrew and Eugene are playing a game. Initially, Andrew has string $s$, consisting of digits. Eugene sends Andrew multiple queries of type "$d_{i} → t_{i}$", that means "replace all digits $d_{i}$ in string $s$ with substrings equal to $t_{i}$". For example, if $s = 123123$, then query "$2 → 00$" transforms $s$ to $100... | It is quite diffcult to store the whole string after each query as its length grows exponentially and queries may change it dramatically. The good advice is: if you can't come up with a solution for a problem, try solving it from the other end. =) Suppose we know for some sequence of queries that digit $d$ will turn in... | [
"dp"
] | 2,100 | null |
464 | D | World of Darkraft - 2 | Roma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.
The character can equip himself with $k$ distinct types of items. Power of each item depends on its level (positive integer number). ... | This problem required some skill at probabilities handling, but other than that it's quite simple too. Denote number of earned coins as $X$, and number of earned coins from selling items of type $i$ as $X_{i}$. Clearly $X = X_{1} + ... + X_{k}$, and $EX = EX_{1} + ... + EX_{k}$ (here $EX$ is expectation of $X$). As all... | [
"dp",
"probabilities"
] | 2,700 | null |
464 | E | The Classic Problem | You are given a weighted undirected graph on $n$ vertices and $m$ edges. Find the shortest path from vertex $s$ to vertex $t$ or else state that such path doesn't exist. | This seems to be a simple graph exercise, but the problem is with enormous weights of paths which we need to count and compare with absolute precision to get Dijkstra working. How do we do that? The fact that every edge weight is a power of two gives an idea that we can store binary representation of path value as it d... | [
"data structures",
"graphs",
"shortest paths"
] | 3,000 | null |
465 | A | inc ARG | Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of $n$ bits. These bits are numbered from $1$ to $n$. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stor... | If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l + 1$ except for the case ... | [
"implementation"
] | 900 | null |
465 | B | Inbox (100500) | Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, return to list. It is easy to show that we can not do any better: observe the moment we read the last letter from some segment of conse... | [
"implementation"
] | 1,000 | null |
466 | A | Cheap Travel | Ann has recently started commuting by subway. We know that a one ride subway ticket costs $a$ rubles. Besides, Ann found out that she can buy a special ticket for $m$ rides (she can buy it several times). It costs $b$ rubles. Ann did the math; she will need to use subway $n$ times. Help Ann, tell her what is the minimu... | Solution of this problem is based on two claims: - If $m \cdot a \le b$ then there is no point to buy a ride ticket. - Sometimes it is better to buy summary more ride tickets for amount of rides than we need. If we receive profits bying ride tickets then number of such ones will be $x=\lfloor{\frac{n}{m}}\rfloor$. Fo... | [
"implementation"
] | 1,200 | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, m, a, b;
cin >> n >> m >> a >> b;
if (m * a <= b)
cout << n * a << "\n";
else
cout << (n/m) * b + min((n%m) * a, b) << "\n";
return 0;
} |
466 | B | Wonder Room | The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a $a × b$ square meter wonder room. The caretaker wants to accommodate exactly $n$ students there. But the law says that there must be at least 6 square meters per student in a room (that... | Let's assume that $a \le b$. First of all, let's consider the situation when we can already accommodate all the students. If $6 \cdot n \le a \cdot b$ then answer is $a \cdot b$ $a$ $b$. Otherwise, we have to increase one of the walls(maybe, both). Let's do it in the following way: iterate the size of the smallest ... | [
"brute force",
"math"
] | 2,000 | #include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
long long n, a, b;
cin >> n >> a >> b;
if (6*n <= a*b)
cout << a*b << "\n" << a << " " << b << "\n";
else {
bool f = 0;
if (a > b)
{
swap(a, b);
f = 1;
... |
466 | C | Number of Ways | You've got array $a[1], a[2], ..., a[n]$, consisting of $n$ integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices $i, j$ $(2 ≤ i ≤ j ≤ n - 1)$, that ... | First of all, notice that if sum of all elements is equal $S$ then sum of each of three parts is equal $\frac{\mathrm{S}}{\mathrm{s}}$. Therefore, if $S$ is not divided by $3$ - then answer is $0$. Otherwise, let's iterate the end of first part $i$ ($1 \le i \le n - 2$) and if sum of 1..i elements is equal $\frac{\... | [
"binary search",
"brute force",
"data structures",
"dp",
"two pointers"
] | 1,700 | #include <iostream>
#include <math.h>
using namespace std;
int a[1000010];
long long cnt[1000010];
int main()
{
ios::sync_with_stdio(0);
int n;
cin >> n;
long long s = 0;
for(int i = 0 ; i < n ; ++i)
{
cin >> a[i];
s += a[i];
}
if (s % 3 != 0)
cout << "0\n";... |
466 | D | Increase Sequence | Peter has a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Peter wants all numbers in the sequence to equal $h$. He can perform the operation of "adding one on the segment $[l, r]$": add one to all elements of the sequence with indices from $l$ to $r$ (inclusive). At that, Peter never chooses any element as the begin... | Lets use dynamic programming to solve this problem. $dp[i][opened]$ - the number of ways to cover prefix of array 1..i by segments and make it equal to $h$ and remain after $i$-th element $opened$ segments that are not closed. Consider all possible variants opening/closing segments in each position: - ] closing one seg... | [
"combinatorics",
"dp"
] | 2,100 | #include<iostream>
using namespace std;
#define MOD 1000000007
long long dp[2010][2010];
int a[2010];
inline void add(long long &a,long long b){
a += b;
a %= MOD;
}
int main()
{
ios_base::sync_with_stdio(0);
int n,h;
cin >> n >> h;
for (int i = 1; i <= n ;i ++)
cin >> a[i]... |
466 | E | Information Graph | There are $n$ employees working in company "X" (let's number them from 1 to $n$ for convenience). Initially the employees didn't have any relationships among each other. On each of $m$ next days one of the following events took place:
- either employee $y$ became the boss of employee $x$ (at that, employee $x$ didn't ... | Let's introduce all structure of the company as a graph(if $y$ is the head of $x$ then we add edge $y$ -> $x$). It is obviously to understand that after each operation our graph will be the set of trees. Actually, the third query - to check is our vertex belong to the subtree of the vertex which has received data packa... | [
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,100 | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define MOD 1000000007
const int Nmax = 100100;
int QueryToNumber[Nmax] , NumberToQuery[Nmax];
int tin[Nmax], tout[Nmax], dsu[Nmax];
int Number = 0 , timer = 1 , n , m;
vector<vector<int> > g;
vector<int> Question[Nmax];
int deg[Nma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.